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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.756   ! raeburn     4: # $Id: grades.pm,v 1.755 2019/01/27 23:16:25 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.359     www        51: use LONCAPA;
                     52: 
1.315     bowersj2   53: use POSIX qw(floor);
1.87      www        54: 
1.435     foxr       55: 
1.513     foxr       56: 
1.435     foxr       57: my %perm=();
1.674     raeburn    58: my %old_essays=();
1.447     foxr       59: 
1.513     foxr       60: #  These variables are used to recover from ssi errors
                     61: 
                     62: my $ssi_retries = 5;
                     63: my $ssi_error;
                     64: my $ssi_error_resource;
                     65: my $ssi_error_message;
                     66: 
                     67: 
                     68: sub ssi_with_retries {
                     69:     my ($resource, $retries, %form) = @_;
                     70:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     71:     if ($response->is_error) {
                     72: 	$ssi_error          = 1;
                     73: 	$ssi_error_resource = $resource;
                     74: 	$ssi_error_message  = $response->code . " " . $response->message;
                     75:     }
                     76: 
                     77:     return $content;
                     78: 
                     79: }
                     80: #
                     81: #  Prodcuces an ssi retry failure error message to the user:
                     82: #
                     83: 
                     84: sub ssi_print_error {
                     85:     my ($r) = @_;
1.516     raeburn    86:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     87:     $r->print('
                     88: <br />
                     89: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     90: <p>
                     91: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     92: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     93: '.&mt('Error:').' '.$ssi_error_message.'
                     94: </p>
                     95: <p>'.
                     96: &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 />'.
                     97: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     98: '</p>');
                     99:     return;
1.513     foxr      100: }
                    101: 
1.44      ng        102: #
1.146     albertel  103: # --- Retrieve the parts from the metadata file.---
1.598     www       104: # Returns an array of everything that the resources stores away
                    105: #
                    106: 
1.44      ng        107: sub getpartlist {
1.582     raeburn   108:     my ($symb,$errorref) = @_;
1.439     albertel  109: 
                    110:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   111:     unless (ref($navmap)) {
                    112:         if (ref($errorref)) { 
                    113:             $$errorref = 'navmap';
                    114:             return;
                    115:         }
                    116:     }
1.439     albertel  117:     my $res      = $navmap->getBySymb($symb);
                    118:     my $partlist = $res->parts();
                    119:     my $url      = $res->src();
1.745     raeburn   120:     my $toolsymb;
                    121:     if ($url =~ /ext\.tool$/) {
                    122:         $toolsymb = $symb;
                    123:     }
                    124:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  125: 
1.146     albertel  126:     my @stores;
1.439     albertel  127:     foreach my $part (@{ $partlist }) {
1.146     albertel  128: 	foreach my $key (@metakeys) {
                    129: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    130: 	}
                    131:     }
                    132:     return @stores;
1.2       albertel  133: }
                    134: 
1.129     ng        135: #--- Format fullname, username:domain if different for display
                    136: #--- Use anywhere where the student names are listed
                    137: sub nameUserString {
                    138:     my ($type,$fullname,$uname,$udom) = @_;
                    139:     if ($type eq 'header') {
1.485     albertel  140: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        141:     } else {
1.398     albertel  142: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    143: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        144:     }
                    145: }
                    146: 
1.44      ng        147: #--- Get the partlist and the response type for a given problem. ---
                    148: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       149: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        150: sub response_type {
1.582     raeburn   151:     my ($symb,$response_error) = @_;
1.377     albertel  152: 
                    153:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   154:     unless (ref($navmap)) {
                    155:         if (ref($response_error)) {
                    156:             $$response_error = 1;
                    157:         }
                    158:         return;
                    159:     }
1.377     albertel  160:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   161:     unless (ref($res)) {
                    162:         $$response_error = 1;
                    163:         return;
                    164:     }
1.377     albertel  165:     my $partlist = $res->parts();
1.392     albertel  166:     my %vPart = 
                    167: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  168:     my (%response_types,%handgrade);
                    169:     foreach my $part (@{ $partlist }) {
1.392     albertel  170: 	next if (%vPart && !exists($vPart{$part}));
                    171: 
1.377     albertel  172: 	my @types = $res->responseType($part);
                    173: 	my @ids = $res->responseIds($part);
                    174: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    176: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    177: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    178: 				     '.handgrade',$symb);
1.41      ng        179: 	}
                    180:     }
1.377     albertel  181:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        182: }
                    183: 
1.375     albertel  184: sub flatten_responseType {
                    185:     my ($responseType) = @_;
                    186:     my @part_response_id =
                    187: 	map { 
                    188: 	    my $part = $_;
                    189: 	    map {
                    190: 		[$part,$_]
                    191: 		} sort(keys(%{ $responseType->{$part} }));
                    192: 	} sort(keys(%$responseType));
                    193:     return @part_response_id;
                    194: }
                    195: 
1.207     albertel  196: sub get_display_part {
1.324     albertel  197:     my ($partID,$symb)=@_;
1.207     albertel  198:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    199:     if (defined($display) and $display ne '') {
1.577     bisitz    200:         $display.= ' (<span class="LC_internal_info">'
                    201:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  202:     } else {
                    203: 	$display=$partID;
                    204:     }
                    205:     return $display;
                    206: }
1.269     raeburn   207: 
1.434     albertel  208: sub reset_caches {
                    209:     &reset_analyze_cache();
                    210:     &reset_perm();
1.674     raeburn   211:     &reset_old_essays();
1.434     albertel  212: }
                    213: 
                    214: {
                    215:     my %analyze_cache;
1.557     raeburn   216:     my %analyze_cache_formkeys;
1.148     albertel  217: 
1.434     albertel  218:     sub reset_analyze_cache {
                    219: 	undef(%analyze_cache);
1.557     raeburn   220:         undef(%analyze_cache_formkeys);
1.434     albertel  221:     }
                    222: 
                    223:     sub get_analyze {
1.649     raeburn   224: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  225: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   226:         if ($type eq 'randomizetry') {
                    227:             if ($trial ne '') {
                    228:                 $key .= "\0".$trial;
                    229:             }
                    230:         }
1.557     raeburn   231: 	if (exists($analyze_cache{$key})) {
                    232:             my $getupdate = 0;
                    233:             if (ref($add_to_hash) eq 'HASH') {
                    234:                 foreach my $item (keys(%{$add_to_hash})) {
                    235:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    236:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    237:                             $getupdate = 1;
                    238:                             last;
                    239:                         }
                    240:                     } else {
                    241:                         $getupdate = 1;
                    242:                     }
                    243:                 }
                    244:             }
                    245:             if (!$getupdate) {
                    246:                 return $analyze_cache{$key};
                    247:             }
                    248:         }
1.434     albertel  249: 
                    250: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    251: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   252:         my %form = ('grade_target'      => 'analyze',
                    253:                     'grade_domain'      => $udom,
                    254:                     'grade_symb'        => $symb,
                    255:                     'grade_courseid'    =>  $env{'request.course.id'},
                    256:                     'grade_username'    => $uname,
                    257:                     'grade_noincrement' => $no_increment);
1.649     raeburn   258:         if ($bubbles_per_row ne '') {
                    259:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    260:         }
1.640     raeburn   261:         if ($type eq 'randomizetry') {
                    262:             $form{'grade_questiontype'} = $type;
                    263:             if ($rndseed ne '') {
                    264:                 $form{'grade_rndseed'} = $rndseed;
                    265:             }
                    266:         }
1.557     raeburn   267:         if (ref($add_to_hash)) {
                    268:             %form = (%form,%{$add_to_hash});
1.640     raeburn   269:         }
1.557     raeburn   270: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  271: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    272: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   273:         if (ref($add_to_hash) eq 'HASH') {
                    274:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    275:         } else {
                    276:             $analyze_cache_formkeys{$key} = {};
                    277:         }
1.434     albertel  278: 	return $analyze_cache{$key} = \%analyze;
                    279:     }
                    280: 
                    281:     sub get_order {
1.640     raeburn   282: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    283: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  284: 	return $analyze->{"$partid.$respid.shown"};
                    285:     }
                    286: 
                    287:     sub get_radiobutton_correct_foil {
1.640     raeburn   288: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    289: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    290:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   291:         if (ref($foils) eq 'ARRAY') {
                    292: 	    foreach my $foil (@{$foils}) {
                    293: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    294: 		    return $foil;
                    295: 	        }
1.434     albertel  296: 	    }
                    297: 	}
                    298:     }
1.554     raeburn   299: 
                    300:     sub scantron_partids_tograde {
1.741     raeburn   301:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   302:         my (%analysis,@parts);
                    303:         if (ref($resource)) {
                    304:             my $symb = $resource->symb();
1.557     raeburn   305:             my $add_to_form;
                    306:             if ($check_for_randomlist) {
                    307:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    308:             }
1.741     raeburn   309:             if ($scancode) {
                    310:                 if (ref($add_to_form) eq 'HASH') {
                    311:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    312:                 } else {
                    313:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    314:                 }
                    315:             }
1.649     raeburn   316:             my $analyze = 
                    317:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    318:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   319:             if (ref($analyze) eq 'HASH') {
                    320:                 %analysis = %{$analyze};
                    321:             }
                    322:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    323:                 foreach my $part (@{$analysis{'parts'}}) {
                    324:                     my ($id,$respid) = split(/\./,$part);
                    325:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    326:                         push(@parts,$part);
                    327:                     }
                    328:                 }
                    329:             }
                    330:         }
                    331:         return (\%analysis,\@parts);
                    332:     }
                    333: 
1.148     albertel  334: }
1.434     albertel  335: 
1.118     ng        336: #--- Clean response type for display
1.335     albertel  337: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    338: #        response types only.
1.118     ng        339: sub cleanRecord {
1.336     albertel  340:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   341: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  342:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  343:     if ($response =~ /^(option|rank)$/) {
                    344: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     345:         my @answer = %answer;
                    346:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  347: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    348: 	my ($toprow,$bottomrow);
                    349: 	foreach my $foil (@$order) {
                    350: 	    if ($grading{$foil} == 1) {
                    351: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    352: 	    } else {
                    353: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    354: 	    }
1.398     albertel  355: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  356: 	}
                    357: 	return '<blockquote><table border="1">'.
1.466     albertel  358: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   360: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  361:     } elsif ($response eq 'match') {
                    362: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     363:         my @answer = %answer;
                    364:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  365: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    366: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    367: 	my ($toprow,$middlerow,$bottomrow);
                    368: 	foreach my $foil (@$order) {
                    369: 	    my $item=shift(@items);
                    370: 	    if ($grading{$foil} == 1) {
                    371: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  372: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  373: 	    } else {
                    374: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  375: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  376: 	    }
1.398     albertel  377: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        378: 	}
1.126     ng        379: 	return '<blockquote><table border="1">'.
1.466     albertel  380: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    381: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  382: 	    $middlerow.'</tr>'.
1.466     albertel  383: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   384: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  385:     } elsif ($response eq 'radiobutton') {
                    386: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     387:         my @answer = %answer;
                    388:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  389: 	my ($toprow,$bottomrow);
1.434     albertel  390: 	my $correct = 
1.640     raeburn   391: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  392: 	foreach my $foil (@$order) {
1.148     albertel  393: 	    if (exists($answer{$foil})) {
1.434     albertel  394: 		if ($foil eq $correct) {
1.466     albertel  395: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  396: 		} else {
1.466     albertel  397: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  398: 		}
                    399: 	    } else {
1.466     albertel  400: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  401: 	    }
1.398     albertel  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  403: 	}
                    404: 	return '<blockquote><table border="1">'.
1.466     albertel  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   407: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  408:     } elsif ($response eq 'essay') {
1.257     albertel  409: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        410: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  411: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    412: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        413: 
1.257     albertel  414: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    415: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    416: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    417: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    418: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    419: 	    $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        420: 	}
1.751     raeburn   421:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     422: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     423: 
1.268     albertel  424:     } elsif ( $response eq 'organic') {
1.721     bisitz    425:         my $result=&mt('Smile representation: [_1]',
                    426:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  427: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    428: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    429: 	return $result;
1.335     albertel  430:     } elsif ( $response eq 'Task') {
                    431: 	if ( $answer eq 'SUBMITTED') {
                    432: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  433: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  434: 	    return $result;
                    435: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    436: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    437: 			       keys(%{$record}));
                    438: 	    return join('<br />',($version,@matches));
                    439: 			       
                    440: 			       
                    441: 	} else {
                    442: 	    my $result =
                    443: 		'<p>'
                    444: 		.&mt('Overall result: [_1]',
                    445: 		     $record->{$version."resource.$respid.$partid.status"})
                    446: 		.'</p>';
                    447: 	    
                    448: 	    $result .= '<ul>';
                    449: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    450: 			     keys(%{$record}));
                    451: 	    foreach my $grade (sort(@grade)) {
                    452: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    453: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    454: 				     $dim, $record->{$grade}).
                    455: 			  '</li>';
                    456: 	    }
                    457: 	    $result.='</ul>';
                    458: 	    return $result;
                    459: 	}
1.716     bisitz    460:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    461:         # Respect multiple input fields, see Bug #5409
1.440     albertel  462: 	$answer = 
                    463: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    464: 							      $answer);
1.720     kruse     465: 	return $answer;
1.122     ng        466:     }
1.720     kruse     467:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        468: }
                    469: 
                    470: #-- A couple of common js functions
                    471: sub commonJSfunctions {
                    472:     my $request = shift;
1.597     wenzelju  473:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        474:     function radioSelection(radioButton) {
                    475: 	var selection=null;
                    476: 	if (radioButton.length > 1) {
                    477: 	    for (var i=0; i<radioButton.length; i++) {
                    478: 		if (radioButton[i].checked) {
                    479: 		    return radioButton[i].value;
                    480: 		}
                    481: 	    }
                    482: 	} else {
                    483: 	    if (radioButton.checked) return radioButton.value;
                    484: 	}
                    485: 	return selection;
                    486:     }
                    487: 
                    488:     function pullDownSelection(selectOne) {
                    489: 	var selection="";
                    490: 	if (selectOne.length > 1) {
                    491: 	    for (var i=0; i<selectOne.length; i++) {
                    492: 		if (selectOne[i].selected) {
                    493: 		    return selectOne[i].value;
                    494: 		}
                    495: 	    }
                    496: 	} else {
1.138     albertel  497:             // only one value it must be the selected one
                    498: 	    return selectOne.value;
1.118     ng        499: 	}
                    500:     }
                    501: COMMONJSFUNCTIONS
                    502: }
                    503: 
1.44      ng        504: #--- Dumps the class list with usernames,list of sections,
                    505: #--- section, ids and fullnames for each user.
                    506: sub getclasslist {
1.750     raeburn   507:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  508:     my @getsec;
1.450     banghart  509:     my @getgroup;
1.442     banghart  510:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  511:     if (!ref($getsec)) {
                    512: 	if ($getsec ne '' && $getsec ne 'all') {
                    513: 	    @getsec=($getsec);
                    514: 	}
                    515:     } else {
                    516: 	@getsec=@{$getsec};
                    517:     }
                    518:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  519:     if (!ref($getgroup)) {
                    520: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    521: 	    @getgroup=($getgroup);
                    522: 	}
                    523:     } else {
                    524: 	@getgroup=@{$getgroup};
                    525:     }
                    526:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  527: 
1.449     banghart  528:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  529:     # Bail out if we were unable to get the classlist
1.56      matthew   530:     return if (! defined($classlist));
1.449     banghart  531:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   532:     #
                    533:     my %sections;
                    534:     my %fullnames;
1.750     raeburn   535:     my ($cdom,$cnum,$partlist);
                    536:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    537:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    538:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    539:         my $res_error;
                    540:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
                    541:     }
1.205     matthew   542:     foreach my $student (keys(%$classlist)) {
                    543:         my $end      = 
                    544:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    545:         my $start    = 
                    546:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    547:         my $id       = 
                    548:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    549:         my $section  = 
                    550:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    551:         my $fullname = 
                    552:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    553:         my $status   = 
                    554:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  555:         my $group   = 
                    556:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        557: 	# filter students according to status selected
1.750     raeburn   558: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  559: 	    if (!($stu_status =~ $status)) {
1.450     banghart  560: 		delete($classlist->{$student});
1.76      ng        561: 		next;
                    562: 	    }
                    563: 	}
1.450     banghart  564: 	# filter students according to groups selected
1.453     banghart  565: 	my @stu_groups = split(/,/,$group);
1.450     banghart  566: 	if (@getgroup) {
                    567: 	    my $exclude = 1;
1.454     banghart  568: 	    foreach my $grp (@getgroup) {
                    569: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  570: 	            if ($stu_group eq $grp) {
                    571: 	                $exclude = 0;
                    572:     	            } 
1.450     banghart  573: 	        }
1.453     banghart  574:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   575:         	    $exclude = 0;
1.453     banghart  576:         	}
1.450     banghart  577: 	    }
                    578: 	    if ($exclude) {
                    579: 	        delete($classlist->{$student});
1.750     raeburn   580: 		next;
1.450     banghart  581: 	    }
                    582: 	}
1.750     raeburn   583:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    584:             my $udom =
                    585:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    586:             my $uname =
                    587:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    588:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    589:                 if ($submitonly eq 'queued') {
                    590:                     my %queue_status =
                    591:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    592:                                                                 $udom,$uname);
                    593:                     if (!defined($queue_status{'gradingqueue'})) {
                    594:                         delete($classlist->{$student});
                    595:                         next;
                    596:                     }
                    597:                 } else {
                    598:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    599:                     my $submitted = 0;
                    600:                     my $graded = 0;
                    601:                     my $incorrect = 0;
                    602:                     foreach (keys(%status)) {
                    603:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    604:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    605:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    606: 
                    607:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    608:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    609:                             $submitted = 0;
                    610:                         }
                    611:                     }
                    612:                     if (!$submitted && ($submitonly eq 'yes' ||
                    613:                                         $submitonly eq 'incorrect' ||
                    614:                                         $submitonly eq 'graded')) {
                    615:                         delete($classlist->{$student});
                    616:                         next;
                    617:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    618:                         delete($classlist->{$student});
                    619:                         next;
                    620:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    621:                         delete($classlist->{$student});
                    622:                         next;
                    623:                     }
                    624:                 }
                    625:             }
                    626:         }
1.205     matthew   627: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  628: 	if (&canview($section)) {
1.291     albertel  629: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  630: 		$sections{$section}++;
1.450     banghart  631: 		if ($classlist->{$student}) {
                    632: 		    $fullnames{$student}=$fullname;
                    633: 		}
1.103     albertel  634: 	    } else {
1.205     matthew   635: 		delete($classlist->{$student});
1.103     albertel  636: 	    }
                    637: 	} else {
1.205     matthew   638: 	    delete($classlist->{$student});
1.103     albertel  639: 	}
1.44      ng        640:     }
1.56      matthew   641:     my @sections = sort(keys(%sections));
                    642:     return ($classlist,\@sections,\%fullnames);
1.44      ng        643: }
                    644: 
1.103     albertel  645: sub canmodify {
                    646:     my ($sec)=@_;
                    647:     if ($perm{'mgr'}) {
                    648: 	if (!defined($perm{'mgr_section'})) {
                    649: 	    # can modify whole class
                    650: 	    return 1;
                    651: 	} else {
                    652: 	    if ($sec eq $perm{'mgr_section'}) {
                    653: 		#can modify the requested section
                    654: 		return 1;
                    655: 	    } else {
                    656: 		# can't modify the request section
                    657: 		return 0;
                    658: 	    }
                    659: 	}
                    660:     }
                    661:     #can't modify
                    662:     return 0;
                    663: }
                    664: 
                    665: sub canview {
                    666:     my ($sec)=@_;
                    667:     if ($perm{'vgr'}) {
                    668: 	if (!defined($perm{'vgr_section'})) {
                    669: 	    # can modify whole class
                    670: 	    return 1;
                    671: 	} else {
                    672: 	    if ($sec eq $perm{'vgr_section'}) {
                    673: 		#can modify the requested section
                    674: 		return 1;
                    675: 	    } else {
                    676: 		# can't modify the request section
                    677: 		return 0;
                    678: 	    }
                    679: 	}
                    680:     }
                    681:     #can't modify
                    682:     return 0;
                    683: }
                    684: 
1.44      ng        685: #--- Retrieve the grade status of a student for all the parts
                    686: sub student_gradeStatus {
1.324     albertel  687:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  688:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        689:     my %partstatus = ();
                    690:     foreach (@$partlist) {
1.128     ng        691: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        692: 	$status              = 'nothing' if ($status eq '');
                    693: 	$partstatus{$_}      = $status;
                    694: 	my $subkey           = "resource.$_.submitted_by";
                    695: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    696:     }
                    697:     return %partstatus;
                    698: }
                    699: 
1.45      ng        700: # hidden form and javascript that calls the form
                    701: # Use by verifyscript and viewgrades
                    702: # Shows a student's view of problem and submission
                    703: sub jscriptNform {
1.324     albertel  704:     my ($symb) = @_;
1.442     banghart  705:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  706:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        707: 	'    function viewOneStudent(user,domain) {'."\n".
                    708: 	'	document.onestudent.student.value = user;'."\n".
                    709: 	'	document.onestudent.userdom.value = domain;'."\n".
                    710: 	'	document.onestudent.submit();'."\n".
                    711: 	'    }'."\n".
1.597     wenzelju  712: 	"\n");
1.45      ng        713:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  714: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  715: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        716: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    717: 	'<input type="hidden" name="student" value="" />'."\n".
                    718: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    719: 	'</form>'."\n";
                    720:     return $jscript;
                    721: }
1.39      ng        722: 
1.447     foxr      723: 
                    724: 
1.315     bowersj2  725: # Given the score (as a number [0-1] and the weight) what is the final
                    726: # point value? This function will round to the nearest tenth, third,
                    727: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  728: sub compute_points {
1.315     bowersj2  729:     my ($score, $weight) = @_;
                    730:     
                    731:     my $tolerance = .00001;
                    732:     my $points = $score * $weight;
                    733: 
                    734:     # Check for nearness to 1/x.
                    735:     my $check_for_nearness = sub {
                    736:         my ($factor) = @_;
                    737:         my $num = ($points * $factor) + $tolerance;
                    738:         my $floored_num = floor($num);
1.316     albertel  739:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  740:             return $floored_num / $factor;
                    741:         }
                    742:         return $points;
                    743:     };
                    744: 
                    745:     $points = $check_for_nearness->(10);
                    746:     $points = $check_for_nearness->(3);
                    747:     $points = $check_for_nearness->(4);
                    748:     
                    749:     return $points;
                    750: }
                    751: 
1.44      ng        752: #------------------ End of general use routines --------------------
1.87      www       753: 
                    754: #
                    755: # Find most similar essay
                    756: #
                    757: 
                    758: sub most_similar {
1.674     raeburn   759:     my ($uname,$udom,$symb,$uessay)=@_;
                    760: 
                    761:     unless ($symb) { return ''; }
                    762: 
                    763:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       764: 
                    765: # ignore spaces and punctuation
                    766: 
                    767:     $uessay=~s/\W+/ /gs;
                    768: 
1.282     www       769: # ignore empty submissions (occuring when only files are sent)
                    770: 
1.598     www       771:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       772: 
1.87      www       773: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       774:     my $limit=0.6;
1.87      www       775:     my $sname='';
                    776:     my $sdom='';
                    777:     my $scrsid='';
                    778:     my $sessay='';
                    779: # go through all essays ...
1.674     raeburn   780:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  781: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       782: # ... except the same student
1.426     albertel  783:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   784: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  785: 	$tessay=~s/\W+/ /gs;
1.87      www       786: # String similarity gives up if not even limit
1.426     albertel  787: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       788: # Found one
1.426     albertel  789: 	if ($tsimilar>$limit) {
                    790: 	    $limit=$tsimilar;
                    791: 	    $sname=$tname;
                    792: 	    $sdom=$tdom;
                    793: 	    $scrsid=$tcrsid;
1.674     raeburn   794: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  795: 	}
1.87      www       796:     }
1.88      www       797:     if ($limit>0.6) {
1.87      www       798:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    799:     } else {
                    800:        return ('','','','',0);
                    801:     }
                    802: }
                    803: 
1.44      ng        804: #-------------------------------------------------------------------
                    805: 
                    806: #------------------------------------ Receipt Verification Routines
1.45      ng        807: #
1.602     www       808: 
                    809: sub initialverifyreceipt {
1.608     www       810:    my ($request,$symb) = @_;
1.602     www       811:    &commonJSfunctions($request);
1.694     bisitz    812:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       813:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    814:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       815:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    816:         '<input type="hidden" name="command" value="verify" />'.
                    817:         "</form>\n";
1.602     www       818: }
                    819: 
1.44      ng        820: #--- Check whether a receipt number is valid.---
                    821: sub verifyreceipt {
1.608     www       822:     my ($request,$symb)  = @_;
1.44      ng        823: 
1.257     albertel  824:     my $courseid = $env{'request.course.id'};
1.184     www       825:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  826: 	$env{'form.receipt'};
1.44      ng        827:     $receipt     =~ s/[^\-\d]//g;
                    828: 
1.487     albertel  829:     my $title.=
                    830: 	'<h3><span class="LC_info">'.
1.605     www       831: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    832: 	'</span></h3>'."\n";
1.44      ng        833: 
                    834:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   835:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  836:     
                    837:     my $receiptparts=0;
1.390     albertel  838:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    839: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  840:     my $parts=['0'];
1.582     raeburn   841:     if ($receiptparts) {
                    842:         my $res_error; 
                    843:         ($parts)=&response_type($symb,\$res_error);
                    844:         if ($res_error) {
                    845:             return &navmap_errormsg();
                    846:         } 
                    847:     }
1.486     albertel  848:     
                    849:     my $header = 
                    850: 	&Apache::loncommon::start_data_table().
                    851: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  852: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    853: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    854: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  855:     if ($receiptparts) {
1.487     albertel  856: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  857:     }
                    858:     $header.=
                    859: 	&Apache::loncommon::end_data_table_header_row();
                    860: 
1.294     albertel  861:     foreach (sort 
                    862: 	     {
                    863: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    864: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    865: 		 }
                    866: 		 return $a cmp $b;
                    867: 	     } (keys(%$fullname))) {
1.44      ng        868: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  869: 	foreach my $part (@$parts) {
                    870: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  871: 		$contents.=
                    872: 		    &Apache::loncommon::start_data_table_row().
                    873: 		    '<td>&nbsp;'."\n".
1.177     albertel  874: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  875: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  876: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    877: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    878: 		if ($receiptparts) {
                    879: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    880: 		}
1.486     albertel  881: 		$contents.= 
                    882: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  883: 		
                    884: 		$matches++;
                    885: 	    }
1.44      ng        886: 	}
                    887:     }
                    888:     if ($matches == 0) {
1.584     bisitz    889:         $string = $title
                    890:                  .'<p class="LC_warning">'
                    891:                  .&mt('No match found for the above receipt number.')
                    892:                  .'</p>';
1.44      ng        893:     } else {
1.324     albertel  894: 	$string = &jscriptNform($symb).$title.
1.487     albertel  895: 	    '<p>'.
1.584     bisitz    896: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  897: 	    '</p>'.
1.486     albertel  898: 	    $header.
                    899: 	    $contents.
                    900: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        901:     }
1.614     www       902:     return $string;
1.44      ng        903: }
                    904: 
                    905: #--- This is called by a number of programs.
                    906: #--- Called from the Grading Menu - View/Grade an individual student
                    907: #--- Also called directly when one clicks on the subm button 
                    908: #    on the problem page.
1.30      ng        909: sub listStudents {
1.617     www       910:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  911: 
1.747     raeburn   912:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  913:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    914:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    915:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  916:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       917:     unless ($submitonly) {
                    918:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    919:     }
1.49      albertel  920: 
1.632     www       921:     my $result='';
1.623     www       922:     my $res_error;
                    923:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  924: 
1.736     damieng   925:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   926: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    927: 		'single'   => 'Please select the student before clicking on the Next button.',
                    928: 	     );
1.736     damieng   929:     &js_escape(\%js_lt);
1.597     wenzelju  930:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        931:     function checkSelect(checkBox) {
                    932: 	var ctr=0;
                    933: 	var sense="";
                    934: 	if (checkBox.length > 1) {
                    935: 	    for (var i=0; i<checkBox.length; i++) {
                    936: 		if (checkBox[i].checked) {
                    937: 		    ctr++;
                    938: 		}
                    939: 	    }
1.736     damieng   940: 	    sense = '$js_lt{'multiple'}';
1.110     ng        941: 	} else {
                    942: 	    if (checkBox.checked) {
                    943: 		ctr = 1;
                    944: 	    }
1.736     damieng   945: 	    sense = '$js_lt{'single'}';
1.110     ng        946: 	}
                    947: 	if (ctr == 0) {
1.485     albertel  948: 	    alert(sense);
1.110     ng        949: 	    return false;
                    950: 	}
                    951: 	document.gradesub.submit();
                    952:     }
                    953: 
                    954:     function reLoadList(formname) {
1.112     ng        955: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        956: 	formname.command.value = 'submission';
                    957: 	formname.submit();
                    958:     }
1.45      ng        959: LISTJAVASCRIPT
                    960: 
1.118     ng        961:     &commonJSfunctions($request);
1.41      ng        962:     $request->print($result);
1.39      ng        963: 
1.154     albertel  964:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       965: 	"\n";
1.485     albertel  966: 	
1.561     bisitz    967:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   968:     unless ($is_tool) {
                    969:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    970:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    971:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    972:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    973:                       .&Apache::lonhtmlcommon::row_closure();
                    974:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    975:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    976:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    977:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    978:                       .&Apache::lonhtmlcommon::row_closure();
                    979:     }
1.485     albertel  980: 
                    981:     my $submission_options;
1.442     banghart  982:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    983:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  984:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   985:     my %optiontext;
                    986:     if ($is_tool) {
                    987:         %optiontext = &Apache::lonlocal::texthash (
                    988:                           lastonly => 'last transaction',
                    989:                           last     => 'last transaction with details',
                    990:                           datesub  => 'all transactions',
                    991:                           all      => 'all transactions with details',
                    992:                       );
                    993:     } else {
                    994:         %optiontext = &Apache::lonlocal::texthash (
                    995:                           lastonly => 'last submission',
                    996:                           last     => 'last submission with details',
                    997:                           datesub  => 'all submissions',
                    998:                           all      => 'all submissions with details',
                    999:                       );
                   1000:     }
1.485     albertel 1001:     $submission_options.=
1.592     bisitz   1002:         '<span class="LC_nobreak">'.
1.624     www      1003:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1004:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1005:         '<span class="LC_nobreak">'.
                   1006:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1007:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1008:         '<span class="LC_nobreak">'.
1.628     www      1009:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1010:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1011:         '<span class="LC_nobreak">'.
                   1012:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1013:         $optiontext{'all'}.'</label></span>';
                   1014:     my $viewtitle;
                   1015:     if ($is_tool) {
                   1016:         $viewtitle = &mt('View Transactions');
                   1017:     } else {
                   1018:         $viewtitle = &mt('View Submissions');
                   1019:     }
                   1020:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1021:                   .$submission_options
                   1022:                   .&Apache::lonhtmlcommon::row_closure();
                   1023: 
1.745     raeburn  1024:     my $closure;
                   1025:     if (($is_tool) && (exists($env{'form.Status'}))) {
                   1026:         $closure = 1;
                   1027:     }
1.561     bisitz   1028:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1029:                   .'<select name="increment">'
                   1030:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1031:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1032:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1033:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1034:                   .'</select>'
1.745     raeburn  1035:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel 1036: 
                   1037:     $gradeTable .= 
1.432     banghart 1038:         &build_section_inputs().
1.45      ng       1039: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1040: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1041: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1042: 
1.618     www      1043:     if (exists($env{'form.Status'})) {
1.561     bisitz   1044: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1045:     } else {
1.745     raeburn  1046:         if ($is_tool) {
                   1047:             $closure = 1;
                   1048:         }
1.561     bisitz   1049:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1050:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1051:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn  1052:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1053:     }
1.112     ng       1054: 
1.745     raeburn  1055:     unless ($is_tool) {
                   1056:         $closure = 1;
                   1057:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1058:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1059:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1060:     }
                   1061:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1062:     my $regrademsg;
                   1063:     if ($is_tool) {
                   1064:         $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.");
                   1065:     } else {
                   1066:         $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.");
                   1067:     }
1.561     bisitz   1068:     $gradeTable .= '<p>'
1.745     raeburn  1069:                   .$regrademsg."\n"
1.561     bisitz   1070:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1071:                   .'</p>';
1.249     albertel 1072: 
                   1073: # checkall buttons
                   1074:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1075:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1076:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1077:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1078:     $gradeTable.=&check_buttons();
1.450     banghart 1079:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1080:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1081: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1082:     my $loop = 0;
                   1083:     while ($loop < 2) {
1.485     albertel 1084: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1085: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1086: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1087: 	    foreach my $part (sort(@$partlist)) {
                   1088: 		my $display_part=
                   1089: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1090: 		$gradeTable.=
                   1091: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1092: 	    }
1.301     albertel 1093: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1094: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1095: 	}
                   1096: 	$loop++;
1.126     ng       1097: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1098:     }
1.474     albertel 1099:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1100: 
1.45      ng       1101:     my $ctr = 0;
1.294     albertel 1102:     foreach my $student (sort 
                   1103: 			 {
                   1104: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1105: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1106: 			     }
                   1107: 			     return $a cmp $b;
                   1108: 			 }
                   1109: 			 (keys(%$fullname))) {
1.41      ng       1110: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1111: 
1.110     ng       1112: 	my %status = ();
1.301     albertel 1113: 
                   1114: 	if ($submitonly eq 'queued') {
                   1115: 	    my %queue_status = 
                   1116: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1117: 							$udom,$uname);
                   1118: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1119: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1120: 	}
                   1121: 
1.618     www      1122: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1123: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1124: 	    my $submitted = 0;
1.164     albertel 1125: 	    my $graded = 0;
1.248     albertel 1126: 	    my $incorrect = 0;
1.110     ng       1127: 	    foreach (keys(%status)) {
1.145     albertel 1128: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1129: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1130: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1131: 		
1.110     ng       1132: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1133: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1134: 		    $submitted = 0;
1.150     albertel 1135: 		    my ($part)=split(/\./,$partid);
1.110     ng       1136: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1137: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1138: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1139: 		}
1.41      ng       1140: 	    }
1.248     albertel 1141: 	    
1.156     albertel 1142: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1143: 				     $submitonly eq 'incorrect' ||
                   1144: 				     $submitonly eq 'graded'));
1.248     albertel 1145: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1146: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1147: 	}
1.34      ng       1148: 
1.45      ng       1149: 	$ctr++;
1.249     albertel 1150: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1151:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1152: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1153: 	    if ($ctr%2 ==1) {
                   1154: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1155: 	    }
1.126     ng       1156: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1157:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1158:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1159: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1160: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1161: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1162: 
1.618     www      1163: 	    if ($submitonly ne 'all') {
1.524     raeburn  1164: 		foreach (sort(keys(%status))) {
1.485     albertel 1165: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1166: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1167: 		}
1.41      ng       1168: 	    }
1.126     ng       1169: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1170: 	    if ($ctr%2 ==0) {
                   1171: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1172: 	    }
1.41      ng       1173: 	}
                   1174:     }
1.110     ng       1175:     if ($ctr%2 ==1) {
1.126     ng       1176: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1177: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1178: 		foreach (@$partlist) {
                   1179: 		    $gradeTable.='<td>&nbsp;</td>';
                   1180: 		}
1.301     albertel 1181: 	    } elsif ($submitonly eq 'queued') {
                   1182: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1183: 	    }
1.474     albertel 1184: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1185:     }
                   1186: 
1.474     albertel 1187:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1188:         '<input type="button" '.
                   1189:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1190:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1191:     if ($ctr == 0) {
1.96      albertel 1192: 	my $num_students=(scalar(keys(%$fullname)));
                   1193: 	if ($num_students eq 0) {
1.485     albertel 1194: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1195: 	} else {
1.171     albertel 1196: 	    my $submissions='submissions';
                   1197: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1198: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1199: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1200: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1201: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1202: 		    $num_students).
                   1203: 		'</span><br />';
1.96      albertel 1204: 	}
1.46      ng       1205:     } elsif ($ctr == 1) {
1.474     albertel 1206: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1207:     }
                   1208:     $request->print($gradeTable);
1.44      ng       1209:     return '';
1.10      ng       1210: }
                   1211: 
1.44      ng       1212: #---- Called from the listStudents routine
1.249     albertel 1213: 
                   1214: sub check_script {
                   1215:     my ($form, $type)=@_;
1.597     wenzelju 1216:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1217:     function checkall() {
                   1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1219:             ele = document.forms.'.$form.'.elements[i];
                   1220:             if (ele.name == "'.$type.'") {
                   1221:             document.forms.'.$form.'.elements[i].checked=true;
                   1222:                                        }
                   1223:         }
                   1224:     }
                   1225: 
                   1226:     function checksec() {
                   1227:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1228:             ele = document.forms.'.$form.'.elements[i];
                   1229:            string = document.forms.'.$form.'.chksec.value;
                   1230:            if
                   1231:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1232:               document.forms.'.$form.'.elements[i].checked=true;
                   1233:             }
                   1234:         }
                   1235:     }
                   1236: 
                   1237: 
                   1238:     function uncheckall() {
                   1239:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1240:             ele = document.forms.'.$form.'.elements[i];
                   1241:             if (ele.name == "'.$type.'") {
                   1242:             document.forms.'.$form.'.elements[i].checked=false;
                   1243:                                        }
                   1244:         }
                   1245:     }
                   1246: 
1.597     wenzelju 1247: '."\n");
1.249     albertel 1248:     return $chkallscript;
                   1249: }
                   1250: 
                   1251: sub check_buttons {
1.485     albertel 1252:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1253:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1254:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1255:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1256:     return $buttons;
                   1257: }
                   1258: 
1.44      ng       1259: #     Displays the submissions for one student or a group of students
1.34      ng       1260: sub processGroup {
1.619     www      1261:     my ($request,$symb)  = @_;
1.41      ng       1262:     my $ctr        = 0;
1.155     albertel 1263:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1264:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1265: 
1.396     banghart 1266:     foreach my $student (@stuchecked) {
                   1267: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1268: 	$env{'form.student'}        = $uname;
                   1269: 	$env{'form.userdom'}        = $udom;
                   1270: 	$env{'form.fullname'}       = $fullname;
1.619     www      1271: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1272: 	$ctr++;
                   1273:     }
                   1274:     return '';
1.35      ng       1275: }
1.34      ng       1276: 
1.44      ng       1277: #------------------------------------------------------------------------------------
                   1278: #
                   1279: #-------------------------- Next few routines handles grading by student, essentially
                   1280: #                           handles essay response type problem/part
                   1281: #
                   1282: #--- Javascript to handle the submission page functionality ---
                   1283: sub sub_page_js {
                   1284:     my $request = shift;
1.736     damieng  1285:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1286:     &js_escape(\$alertmsg);
1.597     wenzelju 1287:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1288:     function updateRadio(formname,id,weight) {
1.125     ng       1289: 	var gradeBox = formname["GD_BOX"+id];
                   1290: 	var radioButton = formname["RADVAL"+id];
                   1291: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1292: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1293: 	gradeBox.value = pts;
                   1294: 	var resetbox = false;
                   1295: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1296: 	    alert("$alertmsg"+pts);
1.71      ng       1297: 	    for (var i=0; i<radioButton.length; i++) {
                   1298: 		if (radioButton[i].checked) {
                   1299: 		    gradeBox.value = i;
                   1300: 		    resetbox = true;
                   1301: 		}
                   1302: 	    }
                   1303: 	    if (!resetbox) {
                   1304: 		formtextbox.value = "";
                   1305: 	    }
                   1306: 	    return;
1.44      ng       1307: 	}
1.71      ng       1308: 
                   1309: 	if (pts > weight) {
                   1310: 	    var resp = confirm("You entered a value ("+pts+
                   1311: 			       ") greater than the weight for the part. Accept?");
                   1312: 	    if (resp == false) {
1.125     ng       1313: 		gradeBox.value = oldpts;
1.71      ng       1314: 		return;
                   1315: 	    }
1.44      ng       1316: 	}
1.13      albertel 1317: 
1.71      ng       1318: 	for (var i=0; i<radioButton.length; i++) {
                   1319: 	    radioButton[i].checked=false;
                   1320: 	    if (pts == i && pts != "") {
                   1321: 		radioButton[i].checked=true;
                   1322: 	    }
                   1323: 	}
                   1324: 	updateSelect(formname,id);
1.125     ng       1325: 	formname["stores"+id].value = "0";
1.41      ng       1326:     }
1.5       albertel 1327: 
1.72      ng       1328:     function writeBox(formname,id,pts) {
1.125     ng       1329: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1330: 	if (checkSolved(formname,id) == 'update') {
                   1331: 	    gradeBox.value = pts;
                   1332: 	} else {
1.125     ng       1333: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1334: 	    gradeBox.value = oldpts;
1.125     ng       1335: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1336: 	    for (var i=0; i<radioButton.length; i++) {
                   1337: 		radioButton[i].checked=false;
1.72      ng       1338: 		if (i == oldpts) {
1.71      ng       1339: 		    radioButton[i].checked=true;
                   1340: 		}
                   1341: 	    }
1.41      ng       1342: 	}
1.125     ng       1343: 	formname["stores"+id].value = "0";
1.71      ng       1344: 	updateSelect(formname,id);
                   1345: 	return;
1.41      ng       1346:     }
1.44      ng       1347: 
1.71      ng       1348:     function clearRadBox(formname,id) {
                   1349: 	if (checkSolved(formname,id) == 'noupdate') {
                   1350: 	    updateSelect(formname,id);
                   1351: 	    return;
                   1352: 	}
1.125     ng       1353: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1354: 	for (var i=0; i<gradeSelect.length; i++) {
                   1355: 	    if (gradeSelect[i].selected) {
                   1356: 		var selectx=i;
                   1357: 	    }
                   1358: 	}
1.125     ng       1359: 	var stores = formname["stores"+id];
1.71      ng       1360: 	if (selectx == stores.value) { return };
1.125     ng       1361: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1362: 	gradeBox.value = "";
1.125     ng       1363: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1364: 	for (var i=0; i<radioButton.length; i++) {
                   1365: 	    radioButton[i].checked=false;
                   1366: 	}
                   1367: 	stores.value = selectx;
                   1368:     }
1.5       albertel 1369: 
1.71      ng       1370:     function checkSolved(formname,id) {
1.125     ng       1371: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1372: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1373: 	    if (!reply) {return "noupdate";}
1.120     ng       1374: 	    formname.overRideScore.value = 'yes';
1.41      ng       1375: 	}
1.71      ng       1376: 	return "update";
1.13      albertel 1377:     }
1.71      ng       1378: 
                   1379:     function updateSelect(formname,id) {
1.125     ng       1380: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1381: 	return;
1.41      ng       1382:     }
1.33      ng       1383: 
1.121     ng       1384: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1385:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1386: 	formname.gradeOpt.value = val;
1.71      ng       1387: 	if (val == "Save & Next") {
                   1388: 	    for (i=0;i<=total;i++) {
                   1389: 		for (j=0;j<parttot;j++) {
1.125     ng       1390: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1391: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1392: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1393: 			if (points == "") {
1.125     ng       1394: 			    var name = formname["name"+i].value;
1.129     ng       1395: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1396: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1397: 					       ", part "+partid+". Continue?");
1.71      ng       1398: 			    if (resp == false) {
1.125     ng       1399: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1400: 				return false;
                   1401: 			    }
                   1402: 			}
                   1403: 		    }
                   1404: 		}
                   1405: 	    }
                   1406: 	}
1.120     ng       1407: 	formname.submit();
                   1408:     }
                   1409: 
1.71      ng       1410: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1411:     function checkSubmitPage(formname,total) {
                   1412: 	noscore = new Array(100);
                   1413: 	var ptr = 0;
                   1414: 	for (i=1;i<total;i++) {
1.125     ng       1415: 	    var partid = formname["q_"+i].value;
1.127     ng       1416: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1417: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1418: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1419: 		if (points == "" && status != "correct_by_student") {
                   1420: 		    noscore[ptr] = i;
                   1421: 		    ptr++;
                   1422: 		}
                   1423: 	    }
                   1424: 	}
                   1425: 	if (ptr != 0) {
                   1426: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1427: 	    var prolist = "";
                   1428: 	    if (ptr == 1) {
                   1429: 		prolist = noscore[0];
                   1430: 	    } else {
                   1431: 		var i = 0;
                   1432: 		while (i < ptr-1) {
                   1433: 		    prolist += noscore[i]+", ";
                   1434: 		    i++;
                   1435: 		}
                   1436: 		prolist += "and "+noscore[i];
                   1437: 	    }
                   1438: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1439: 	    if (resp == false) {
                   1440: 		return false;
                   1441: 	    }
                   1442: 	}
1.45      ng       1443: 
1.71      ng       1444: 	formname.submit();
                   1445:     }
                   1446: SUBJAVASCRIPT
                   1447: }
1.45      ng       1448: 
1.71      ng       1449: #--- javascript for essay type problem --
                   1450: sub sub_page_kw_js {
                   1451:     my $request = shift;
1.80      ng       1452:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1453:     &commonJSfunctions($request);
1.350     albertel 1454: 
1.629     www      1455:     my $inner_js_msg_central= (<<INNERJS);
                   1456: <script type="text/javascript">
1.350     albertel 1457:     function checkInput() {
                   1458:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1459:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1460:       var usrctr = document.msgcenter.usrctr.value;
                   1461:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1462:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1463: 
                   1464:       var msgchk = "";
                   1465:       if (document.msgcenter.subchk.checked) {
                   1466:          msgchk = "msgsub,";
                   1467:       }
                   1468:       var includemsg = 0;
                   1469:       for (var i=1; i<=nmsg; i++) {
                   1470:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1471:           var frmmsg = document.msgcenter["msg"+i];
                   1472:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1473:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1474:           showflg.value = "1";
                   1475:           var chkbox = document.msgcenter["msgn"+i];
                   1476:           if (chkbox.checked) {
                   1477:              msgchk += "savemsg"+i+",";
                   1478:              includemsg = 1;
                   1479:           }
                   1480:       }
                   1481:       if (document.msgcenter.newmsgchk.checked) {
                   1482:          msgchk += "newmsg"+usrctr;
                   1483:          includemsg = 1;
                   1484:       }
                   1485:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1486:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1487:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1488:       includemsg.value = msgchk;
                   1489: 
                   1490:       self.close()
                   1491: 
                   1492:     }
1.629     www      1493: </script>
1.350     albertel 1494: INNERJS
                   1495: 
1.629     www      1496:     my $inner_js_highlight_central= (<<INNERJS);
                   1497: <script type="text/javascript">
1.351     albertel 1498:     function updateChoice(flag) {
                   1499:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1500:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1501:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1502:       opener.document.SCORE.refresh.value = "on";
                   1503:       if (opener.document.SCORE.keywords.value!=""){
                   1504:          opener.document.SCORE.submit();
                   1505:       }
                   1506:       self.close()
                   1507:     }
1.629     www      1508: </script>
1.351     albertel 1509: INNERJS
                   1510: 
                   1511:     my $start_page_msg_central = 
                   1512:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1513: 				       {'js_ready'  => 1,
                   1514: 					'only_body' => 1,
                   1515: 					'bgcolor'   =>'#FFFFFF',});
                   1516:     my $end_page_msg_central = 
                   1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1518: 
                   1519: 
                   1520:     my $start_page_highlight_central = 
                   1521:         &Apache::loncommon::start_page('Highlight Central',
                   1522: 				       $inner_js_highlight_central,
1.350     albertel 1523: 				       {'js_ready'  => 1,
                   1524: 					'only_body' => 1,
                   1525: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1526:     my $end_page_highlight_central = 
1.350     albertel 1527: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1528: 
1.219     www      1529:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1530:     $docopen=~s/^document\.//;
1.736     damieng  1531:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1532:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1533:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1534:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1535:                 col1 => 'red',
                   1536:                 col2 => 'green',
                   1537:                 col3 => 'blue',
                   1538:                 siz1 => 'normal',
                   1539:                 siz2 => '+1',
                   1540:                 siz3 => '+2',
                   1541:                 sty1 => 'normal',
                   1542:                 sty2 => 'italic',
                   1543:                 sty3 => 'bold',
                   1544:              );
                   1545:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1546:                 comp => 'Compose Message for: ',
                   1547:                 incl => 'Include',
1.656     raeburn  1548:                 type => 'Type',
1.652     raeburn  1549:                 subj => 'Subject',
                   1550:                 mesa => 'Message',
                   1551:                 new  => 'New',
                   1552:                 save => 'Save',
                   1553:                 canc => 'Cancel',
                   1554:                 kehi => 'Keyword Highlight Options',
                   1555:                 txtc => 'Text Color',
                   1556:                 font => 'Font Size',
1.656     raeburn  1557:                 fnst => 'Font Style',
1.652     raeburn  1558:              );
1.736     damieng  1559:     &js_escape(\%js_lt);
                   1560:     &html_escape(\%html_js_lt);
                   1561:     &js_escape(\%html_js_lt);
1.597     wenzelju 1562:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1563: 
1.44      ng       1564: //===================== Show list of keywords ====================
1.122     ng       1565:   function keywords(formname) {
1.736     damieng  1566:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1567:     if (nret==null) return;
1.122     ng       1568:     formname.keywords.value = nret;
1.44      ng       1569: 
1.122     ng       1570:     if (formname.keywords.value != "") {
1.128     ng       1571: 	formname.refresh.value = "on";
1.122     ng       1572: 	formname.submit();
1.44      ng       1573:     }
                   1574:     return;
                   1575:   }
                   1576: 
                   1577: //===================== Script to view submitted by ==================
                   1578:   function viewSubmitter(submitter) {
                   1579:     document.SCORE.refresh.value = "on";
                   1580:     document.SCORE.NCT.value = "1";
                   1581:     document.SCORE.unamedom0.value = submitter;
                   1582:     document.SCORE.submit();
                   1583:     return;
                   1584:   }
                   1585: 
                   1586: //===================== Script to add keyword(s) ==================
                   1587:   function getSel() {
                   1588:     if (document.getSelection) txt = document.getSelection();
                   1589:     else if (document.selection) txt = document.selection.createRange().text;
                   1590:     else return;
                   1591:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1592:     if (cleantxt=="") {
1.736     damieng  1593: 	alert("$js_lt{'plse'}");
1.44      ng       1594: 	return;
                   1595:     }
1.736     damieng  1596:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1597:     if (nret==null) return;
1.127     ng       1598:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1599:     if (document.SCORE.keywords.value != "") {
1.127     ng       1600: 	document.SCORE.refresh.value = "on";
1.44      ng       1601: 	document.SCORE.submit();
                   1602:     }
                   1603:     return;
                   1604:   }
                   1605: 
                   1606: //====================== Script for composing message ==============
1.80      ng       1607:    // preload images
                   1608:    img1 = new Image();
                   1609:    img1.src = "$iconpath/mailbkgrd.gif";
                   1610:    img2 = new Image();
                   1611:    img2.src = "$iconpath/mailto.gif";
                   1612: 
1.44      ng       1613:   function msgCenter(msgform,usrctr,fullname) {
                   1614:     var Nmsg  = msgform.savemsgN.value;
                   1615:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1616:     var subject = msgform.msgsub.value;
1.127     ng       1617:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1618:     re = /msgsub/;
                   1619:     var shwsel = "";
                   1620:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1621:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1622:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1623:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1624: 	var testmsg = "savemsg"+i+",";
                   1625: 	re = new RegExp(testmsg,"g");
1.44      ng       1626: 	shwsel = "";
                   1627: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1628: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1629: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1630: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1631: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1632:     }
1.125     ng       1633:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1634:     shwsel = "";
                   1635:     re = /newmsg/;
                   1636:     if (re.test(msgchk)) { shwsel = "checked" }
                   1637:     newMsg(newmsg,shwsel);
                   1638:     msgTail(); 
                   1639:     return;
                   1640:   }
                   1641: 
1.123     ng       1642:   function checkEntities(strx) {
                   1643:     if (strx.length == 0) return strx;
                   1644:     var orgStr = ["&", "<", ">", '"']; 
                   1645:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1646:     var counter = 0;
                   1647:     while (counter < 4) {
                   1648: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1649: 	counter++;
                   1650:     }
                   1651:     return strx;
                   1652:   }
                   1653: 
                   1654:   function strReplace(strx, orgStr, newStr) {
                   1655:     return strx.split(orgStr).join(newStr);
                   1656:   }
                   1657: 
1.44      ng       1658:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1659:     var height = 70*Nmsg+250;
1.44      ng       1660:     if (height > 600) {
                   1661: 	height = 600;
                   1662:     }
1.118     ng       1663:     var xpos = (screen.width-600)/2;
                   1664:     xpos = (xpos < 0) ? '0' : xpos;
                   1665:     var ypos = (screen.height-height)/2-30;
                   1666:     ypos = (ypos < 0) ? '0' : ypos;
                   1667: 
1.668     www      1668:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1669:     pWin.focus();
                   1670:     pDoc = pWin.document;
1.219     www      1671:     pDoc.$docopen;
1.351     albertel 1672:     pDoc.write('$start_page_msg_central');
1.76      ng       1673: 
                   1674:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1675:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1676:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1677: 
1.676     golterma 1678:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1679:     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       1680: }
                   1681:     function displaySubject(msg,shwsel) {
1.76      ng       1682:     pDoc = pWin.document;
1.676     golterma 1683:     pDoc.write("<tr>");
                   1684:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1685:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1686:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1687: }
                   1688: 
1.72      ng       1689:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1690:     pDoc = pWin.document;
1.676     golterma 1691:     pDoc.write("<tr>");
                   1692:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1693:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1694:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1695: }
                   1696: 
                   1697:   function newMsg(newmsg,shwsel) {
1.76      ng       1698:     pDoc = pWin.document;
1.676     golterma 1699:     pDoc.write("<tr>");
                   1700:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1701:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1702:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1703: }
                   1704: 
                   1705:   function msgTail() {
1.76      ng       1706:     pDoc = pWin.document;
1.676     golterma 1707:     //pDoc.write("<\\/table>");
1.465     albertel 1708:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1709:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1710:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1711:     pDoc.write("<\\/form>");
1.351     albertel 1712:     pDoc.write('$end_page_msg_central');
1.128     ng       1713:     pDoc.close();
1.44      ng       1714: }
                   1715: 
                   1716: //====================== Script for keyword highlight options ==============
                   1717:   function kwhighlight() {
                   1718:     var kwclr    = document.SCORE.kwclr.value;
                   1719:     var kwsize   = document.SCORE.kwsize.value;
                   1720:     var kwstyle  = document.SCORE.kwstyle.value;
                   1721:     var redsel = "";
                   1722:     var grnsel = "";
                   1723:     var blusel = "";
1.736     damieng  1724:     var txtcol1 = "$js_lt{'col1'}";
                   1725:     var txtcol2 = "$js_lt{'col2'}";
                   1726:     var txtcol3 = "$js_lt{'col3'}";
                   1727:     var txtsiz1 = "$js_lt{'siz1'}";
                   1728:     var txtsiz2 = "$js_lt{'siz2'}";
                   1729:     var txtsiz3 = "$js_lt{'siz3'}";
                   1730:     var txtsty1 = "$js_lt{'sty1'}";
                   1731:     var txtsty2 = "$js_lt{'sty2'}";
                   1732:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1733:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1734:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1735:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1736:     var sznsel = "";
                   1737:     var sz1sel = "";
                   1738:     var sz2sel = "";
1.718     bisitz   1739:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1740:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1741:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1742:     var synsel = "";
                   1743:     var syisel = "";
                   1744:     var sybsel = "";
1.718     bisitz   1745:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1746:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1747:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1748:     highlightCentral();
1.718     bisitz   1749:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1750:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1751:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1752:     highlightend();
                   1753:     return;
                   1754:   }
                   1755: 
                   1756:   function highlightCentral() {
1.76      ng       1757: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1758:     var xpos = (screen.width-400)/2;
                   1759:     xpos = (xpos < 0) ? '0' : xpos;
                   1760:     var ypos = (screen.height-330)/2-30;
                   1761:     ypos = (ypos < 0) ? '0' : ypos;
                   1762: 
1.206     albertel 1763:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1764:     hwdWin.focus();
                   1765:     var hDoc = hwdWin.document;
1.219     www      1766:     hDoc.$docopen;
1.351     albertel 1767:     hDoc.write('$start_page_highlight_central');
1.76      ng       1768:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1769:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1770: 
1.718     bisitz   1771:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1772:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1773:   }
                   1774: 
                   1775:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1776:     var hDoc = hwdWin.document;
1.718     bisitz   1777:     hDoc.write("<tr>");
1.76      ng       1778:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1779:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1780:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1781:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1782:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1783:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1784:     hDoc.write("<\\/tr>");
1.44      ng       1785:   }
                   1786: 
                   1787:   function highlightend() { 
1.76      ng       1788:     var hDoc = hwdWin.document;
1.718     bisitz   1789:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1790:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1791:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1792:     hDoc.write("<\\/form>");
1.351     albertel 1793:     hDoc.write('$end_page_highlight_central');
1.128     ng       1794:     hDoc.close();
1.44      ng       1795:   }
                   1796: 
                   1797: SUBJAVASCRIPT
                   1798: }
                   1799: 
1.349     albertel 1800: sub get_increment {
1.348     bowersj2 1801:     my $increment = $env{'form.increment'};
                   1802:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1803:         $increment != .1) {
                   1804:         $increment = 1;
                   1805:     }
                   1806:     return $increment;
                   1807: }
                   1808: 
1.585     bisitz   1809: sub gradeBox_start {
                   1810:     return (
                   1811:         &Apache::loncommon::start_data_table()
                   1812:        .&Apache::loncommon::start_data_table_header_row()
                   1813:        .'<th>'.&mt('Part').'</th>'
                   1814:        .'<th>'.&mt('Points').'</th>'
                   1815:        .'<th>&nbsp;</th>'
                   1816:        .'<th>'.&mt('Assign Grade').'</th>'
                   1817:        .'<th>'.&mt('Weight').'</th>'
                   1818:        .'<th>'.&mt('Grade Status').'</th>'
                   1819:        .&Apache::loncommon::end_data_table_header_row()
                   1820:     );
                   1821: }
                   1822: 
                   1823: sub gradeBox_end {
                   1824:     return (
                   1825:         &Apache::loncommon::end_data_table()
                   1826:     );
                   1827: }
1.71      ng       1828: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1829: sub gradeBox {
1.322     albertel 1830:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1831:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1832: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1833:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1834:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1835:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1836:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1837:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1838: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1839:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1840:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1841:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1842: 				       [$partid]);
                   1843:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1844:     if ($last_resets{$partid}) {
                   1845:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1846:     }
1.695     bisitz   1847:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1848:     my $ctr = 0;
1.348     bowersj2 1849:     my $thisweight = 0;
1.349     albertel 1850:     my $increment = &get_increment();
1.485     albertel 1851: 
                   1852:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1853:     while ($thisweight<=$wgt) {
1.532     bisitz   1854: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1855:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1856: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1857: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1858: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1859:         $thisweight += $increment;
1.71      ng       1860: 	$ctr++;
                   1861:     }
1.485     albertel 1862:     $radio.='</tr></table>';
                   1863: 
                   1864:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1865: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1866: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1867: 	$wgt.')" /></td>'."\n";
1.485     albertel 1868:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1869: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1870: 	' </td>'."\n";
                   1871:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1872: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1873:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1874: 	$line.='<option></option>'.
                   1875: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1876:     } else {
1.485     albertel 1877: 	$line.='<option selected="selected"></option>'.
                   1878: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1879:     }
1.485     albertel 1880:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1881: 
                   1882: 
                   1883:     $result .= 
1.695     bisitz   1884: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1885:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1886:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1887:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1888: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1889: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1890: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1891:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1892:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1893:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1894:         $aggtries.'" />'."\n";
1.582     raeburn  1895:     my $res_error;
                   1896:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1897:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1898:     if ($res_error) {
                   1899:         return &navmap_errormsg();
                   1900:     }
1.318     banghart 1901:     return $result;
                   1902: }
1.322     albertel 1903: 
                   1904: sub handback_box {
1.623     www      1905:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1906:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1907:     my (@respids);
1.652     raeburn  1908:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1909:     foreach my $part_response_id (@part_response_id) {
                   1910:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1911:         if ($part eq $partid) {
1.375     albertel 1912:             push(@respids,$resp);
1.323     banghart 1913:         }
                   1914:     }
1.318     banghart 1915:     my $result;
1.323     banghart 1916:     foreach my $respid (@respids) {
1.322     albertel 1917: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1918: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1919: 	next if (!@$files);
1.654     raeburn  1920: 	my $file_counter = 0;
1.313     banghart 1921: 	foreach my $file (@$files) {
1.368     banghart 1922: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1923:                 $file_counter++;
1.368     banghart 1924:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1925:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1926:     	        $file_disp = "$name.$ext";
                   1927:     	        $file = $file_path.$file_disp;
                   1928:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1929:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1930:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1931:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1932: 	    }
1.322     albertel 1933: 	}
1.654     raeburn  1934:         if ($file_counter) {
                   1935:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1936:                        '<span class="LC_info">'.
                   1937:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1938:         }
1.313     banghart 1939:     }
1.318     banghart 1940:     return $result;    
1.71      ng       1941: }
1.44      ng       1942: 
1.58      albertel 1943: sub show_problem {
1.382     albertel 1944:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1945:     my $rendered;
1.382     albertel 1946:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1947:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1948:     if ($mode eq 'both' or $mode eq 'text') {
                   1949: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1950: 						       $env{'request.course.id'},
                   1951: 						       undef,\%form);
1.144     albertel 1952:     }
1.58      albertel 1953:     if ($removeform) {
                   1954: 	$rendered=~s|<form(.*?)>||g;
                   1955: 	$rendered=~s|</form>||g;
1.374     albertel 1956: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1957:     }
1.144     albertel 1958:     my $companswer;
                   1959:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1960: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1961: 	$companswer=
                   1962: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1963: 						    $env{'request.course.id'},
                   1964: 						    %form);
1.144     albertel 1965:     }
1.58      albertel 1966:     if ($removeform) {
                   1967: 	$companswer=~s|<form(.*?)>||g;
                   1968: 	$companswer=~s|</form>||g;
1.144     albertel 1969: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1970:     }
1.671     raeburn  1971:     my $renderheading = &mt('View of the problem');
                   1972:     my $answerheading = &mt('Correct answer');
                   1973:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1974:         my $stu_fullname = $env{'form.fullname'};
                   1975:         if ($stu_fullname eq '') {
                   1976:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1977:         }
                   1978:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1979:         if ($forwhom ne '') {
                   1980:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1981:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1982:         }
                   1983:     }
1.468     albertel 1984:     $rendered=
1.588     bisitz   1985:         '<div class="LC_Box">'
1.671     raeburn  1986:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1987:        .$rendered
                   1988:        .'</div>';
1.468     albertel 1989:     $companswer=
1.588     bisitz   1990:         '<div class="LC_Box">'
1.671     raeburn  1991:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1992:        .$companswer
                   1993:        .'</div>';
1.468     albertel 1994:     my $result;
1.144     albertel 1995:     if ($mode eq 'both') {
1.588     bisitz   1996:         $result=$rendered.$companswer;
1.144     albertel 1997:     } elsif ($mode eq 'text') {
1.588     bisitz   1998:         $result=$rendered;
1.144     albertel 1999:     } elsif ($mode eq 'answer') {
1.588     bisitz   2000:         $result=$companswer;
1.144     albertel 2001:     }
1.71      ng       2002:     return $result;
1.58      albertel 2003: }
1.397     albertel 2004: 
1.396     banghart 2005: sub files_exist {
                   2006:     my ($r, $symb) = @_;
                   2007:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2008:     foreach my $student (@students) {
                   2009:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2010:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2011: 					      $udom,$uname);
1.396     banghart 2012:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2013:         foreach my $submission (@$string) {
                   2014:             my ($partid,$respid) =
                   2015: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2016:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2017: 					   \%record);
                   2018:             return 1 if (@$files);
1.396     banghart 2019:         }
                   2020:     }
1.397     albertel 2021:     return 0;
1.396     banghart 2022: }
1.397     albertel 2023: 
1.394     banghart 2024: sub download_all_link {
                   2025:     my ($r,$symb) = @_;
1.621     www      2026:     unless (&files_exist($r, $symb)) {
                   2027:        $r->print(&mt('There are currently no submitted documents.'));
                   2028:        return;
                   2029:     }
1.395     albertel 2030:     my $all_students = 
                   2031: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2032: 
                   2033:     my $parts =
                   2034: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2035: 
1.394     banghart 2036:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2037:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2038:                              'cgi.'.$identifier.'.symb' => $symb,
                   2039:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2040:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2041: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2042:     return;
                   2043: }
                   2044: 
                   2045: sub submit_download_link {
                   2046:     my ($request,$symb) = @_;
                   2047:     if (!$symb) { return ''; }
                   2048: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750     raeburn  2049:     my $res_error;
                   2050:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                   2051:     if (ref($res_error)) {
                   2052:         if ($$res_error) {
                   2053:             $request->print(&mt('An error occurred retrieving response types'));
                   2054:             return;
                   2055:         }
                   2056:     }
                   2057:     my ($numupload,$numessay) = (0,0);
                   2058:     if (ref($responseType) eq 'HASH') {
                   2059:         foreach my $part (sort(keys(%$responseType))) {
                   2060:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
                   2061:                 my $responsetype = $responseType->{$part}->{$id};
                   2062:                 if ($responsetype eq 'essay') {
                   2063:                     my $uploadedfiletypes =
                   2064:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
                   2065:                     if ($uploadedfiletypes) {
                   2066:                         $numupload++;
                   2067:                     } else {
                   2068:                         $numessay++;
                   2069:                     }
                   2070:                 }
                   2071:             }
                   2072:         }
                   2073:     }
                   2074:     if (($numupload) || ($numessay)) {
                   2075:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2076:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2077:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2078:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2079:         if (ref($fullname) eq 'HASH') {
                   2080:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2081:             if (@students) {
                   2082:                 @{$env{'form.stuinfo'}} = @students;
                   2083:                 if ($numupload) {
                   2084:                     &download_all_link($request,$symb);
                   2085:                 }
                   2086: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
                   2087: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2088:             } else {
                   2089:                 $request->print(&mt('No students match the criteria you selected'));
                   2090:             }
                   2091:         } else {
                   2092:             $request->print(&mt('Could not retrieve student information'));
                   2093:         }
                   2094:     } else {
                   2095:         $request->print(&mt('No essayresponse items found'));
                   2096:     }
                   2097:     return;
1.394     banghart 2098: }
1.395     albertel 2099: 
1.432     banghart 2100: sub build_section_inputs {
                   2101:     my $section_inputs;
                   2102:     if ($env{'form.section'} eq '') {
                   2103:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2104:     } else {
                   2105:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2106:         foreach my $section (@sections) {
1.432     banghart 2107:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2108:         }
                   2109:     }
                   2110:     return $section_inputs;
                   2111: }
                   2112: 
1.44      ng       2113: # --------------------------- show submissions of a student, option to grade 
                   2114: sub submission {
1.608     www      2115:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2116:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2117:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2118:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2119:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2120: 
1.605     www      2121:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2122:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2123:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2124:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2125: 
                   2126:     if (!&canview($usec)) {
1.712     bisitz   2127:         $request->print(
                   2128:             '<span class="LC_warning">'.
1.713     bisitz   2129:             &mt('Unable to view requested student.').
1.712     bisitz   2130:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2131:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2132:             '</span>');
1.104     albertel 2133: 	return;
                   2134:     }
                   2135: 
1.257     albertel 2136:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2137:     unless ($is_tool) { 
                   2138:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2139:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2140:     }
1.257     albertel 2141:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2142:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2143: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2144: 	'/check.gif" height="16" border="0" />';
1.41      ng       2145: 
                   2146:     # header info
                   2147:     if ($counter == 0) {
                   2148: 	&sub_page_js($request);
1.621     www      2149: 	&sub_page_kw_js($request);
1.118     ng       2150: 
1.44      ng       2151: 	# option to display problem, only once else it cause problems 
                   2152:         # with the form later since the problem has a form.
1.257     albertel 2153: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2154: 	    my $mode;
1.257     albertel 2155: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2156: 		$mode='both';
1.257     albertel 2157: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2158: 		$mode='text';
1.257     albertel 2159: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2160: 		$mode='answer';
                   2161: 	    }
1.329     albertel 2162: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2163: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2164: 	}
1.441     www      2165: 
1.704     raeburn  2166: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2167:         # if this subroutine has been called once.
1.41      ng       2168: 	my %keyhash = ();
1.624     www      2169: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2170:         if (1) {
1.41      ng       2171: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2172: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2173: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2174: 
1.257     albertel 2175: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2176: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2177: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2178: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2179: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2180: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2181: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2182: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2183: 	}
1.257     albertel 2184: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2185: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2186: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2187: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2188: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2189: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2190: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2191: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2192: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2193: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2194: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2195: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2196: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2197: 			&build_section_inputs().
1.326     albertel 2198: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2199: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2200: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2201: #	if ($env{'form.handgrade'} eq 'yes') {
                   2202:         if (1) {
1.257     albertel 2203: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2204: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2205: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2206: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2207: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2208: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2209: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2210: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2211: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2212: 	    }
1.123     ng       2213: 	}
1.41      ng       2214: 	
                   2215: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2216: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2217: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2218: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2219: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2220: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2221: 		'" />'."\n".
                   2222: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2223: 	    $cts++;
                   2224: 	}
                   2225: 	$request->print($prnmsg);
1.32      ng       2226: 
1.624     www      2227: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2228:         unless ($is_tool) {
1.652     raeburn  2229: 
                   2230:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2231:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2232:                           keyw => 'Keyword Options',
1.655     raeburn  2233:                           list => 'List',
1.652     raeburn  2234:                           past => 'Paste Selection to List',
1.661     www      2235:                           high => 'Highlight Attribute',
1.652     raeburn  2236:                      );    
1.88      www      2237: #
                   2238: # Print out the keyword options line
                   2239: #
1.718     bisitz   2240: 	    $request->print(
                   2241:                 '<div class="LC_columnSection">'
                   2242:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2243:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2244:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2245:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2246:  class="page">'.$lt{'past'}.'</a>',
                   2247:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2248:                     {legend => $lt{'keyw'}})
                   2249:                .'</fieldset></div>'
                   2250:             );
                   2251: 
1.88      www      2252: #
                   2253: # Load the other essays for similarity check
                   2254: #
1.753     raeburn  2255:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2256:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2257:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2258:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2259:                 if ($cdom ne '' && $cnum ne '') {
                   2260:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2261:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2262:                         my $apath = $1.'_'.$id;
                   2263:                         $apath=~s/\W/\_/gs;
                   2264:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2265:                     }
                   2266:                 }
                   2267:             } else {
                   2268: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2269: 	        $apath=&escape($apath);
                   2270: 	        $apath=~s/\W/\_/gs;
                   2271:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2272:             }
1.41      ng       2273:         }
                   2274:     }
1.44      ng       2275: 
1.441     www      2276: # This is where output for one specific student would start
1.592     bisitz   2277:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2278:     $request->print(
                   2279:         "\n\n"
                   2280:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2281:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2282:        ."\n"
                   2283:     );
1.441     www      2284: 
1.592     bisitz   2285:     # Show additional functions if allowed
                   2286:     if ($perm{'vgr'}) {
                   2287:         $request->print(
                   2288:             &Apache::loncommon::track_student_link(
1.708     bisitz   2289:                 'View recent activity',
1.592     bisitz   2290:                 $uname,$udom,'check')
                   2291:            .' '
                   2292:         );
                   2293:     }
                   2294:     if ($perm{'opa'}) {
                   2295:         $request->print(
                   2296:             &Apache::loncommon::pprmlink(
                   2297:                 &mt('Set/Change parameters'),
                   2298:                 $uname,$udom,$symb,'check'));
                   2299:     }
                   2300: 
                   2301:     # Show Problem
1.257     albertel 2302:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2303: 	my $mode;
1.257     albertel 2304: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2305: 	    $mode='both';
1.257     albertel 2306: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2307: 	    $mode='text';
1.257     albertel 2308: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2309: 	    $mode='answer';
                   2310: 	}
1.329     albertel 2311: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2312: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2313:     }
1.144     albertel 2314: 
1.257     albertel 2315:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2316:     my $res_error;
                   2317:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2318:     if ($res_error) {
                   2319:         $request->print(&navmap_errormsg());
                   2320:         return;
                   2321:     }
1.41      ng       2322: 
1.44      ng       2323:     # Display student info
1.41      ng       2324:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2325: 
1.745     raeburn  2326:     my $boxtitle = &mt('Submissions');
                   2327:     if ($is_tool) {
                   2328:         $boxtitle = &mt('Transactions')
                   2329:     }
1.590     bisitz   2330:     my $result='<div class="LC_Box">'
1.745     raeburn  2331:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2332:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2333:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2334: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2335:     unless ($is_tool) {
1.588     bisitz   2336:         $result.='<p class="LC_info">'
                   2337:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2338:                 ."</p>\n";
1.469     albertel 2339:     }
                   2340: 
1.118     ng       2341:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2342:     my $fullname;
                   2343:     my $col_fullnames = [];
1.624     www      2344: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2345:     unless ($is_tool) {
1.464     albertel 2346: 	(my $sub_result,$fullname,$col_fullnames)=
                   2347: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2348: 				 $counter);
                   2349: 	$result.=$sub_result;
1.41      ng       2350:     }
1.44      ng       2351:     $request->print($result."\n");
1.702     kruse    2352:     
1.44      ng       2353:     # print student answer/submission
1.588     bisitz   2354:     # Options are (1) Handgraded submission only
1.44      ng       2355:     #             (2) Last submission, includes submission that is not handgraded 
                   2356:     #                  (for multi-response type part)
                   2357:     #             (3) Last submission plus the parts info
                   2358:     #             (4) The whole record for this student
1.702     kruse    2359:     
1.745     raeburn  2360:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2361: 	
1.702     kruse    2362:     my $lastsubonly;
1.468     albertel 2363: 
1.702     kruse    2364:     if ($$timestamp eq '') {
                   2365:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2366:     } elsif ($is_tool) {
                   2367:         $lastsubonly =
                   2368:             '<div class="LC_grade_submissions_body">'
                   2369:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2370:     } else {
                   2371:         $lastsubonly =
                   2372:             '<div class="LC_grade_submissions_body">'
                   2373:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2374: 
                   2375: 	my %seenparts;
                   2376: 	my @part_response_id = &flatten_responseType($responseType);
                   2377: 	foreach my $part (@part_response_id) {
                   2378: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2379: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2380: 
1.702     kruse    2381: 	    my ($partid,$respid) = @{ $part };
                   2382: 	    my $display_part=&get_display_part($partid,$symb);
                   2383: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2384: 		if (exists($seenparts{$partid})) { next; }
                   2385: 		$seenparts{$partid}=1;
                   2386:                 $request->print(
                   2387:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2388:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2389:                                '<a href="javascript:viewSubmitter(\''.
                   2390:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2391:                                '\');" target="_self">'.
                   2392:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2393:                     '<br />');
                   2394: 		next;
                   2395: 		}
                   2396: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2397: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2398:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2399:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2400:                     ' <span class="LC_internal_info">'.
                   2401:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2402:                     '</span>&nbsp; &nbsp;'.
                   2403: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2404: 		next;
                   2405: 	    }
                   2406: 	    foreach my $submission (@$string) {
                   2407: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2408: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2409: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2410: 		# Similarity check
                   2411:                 my $similar='';
                   2412:                 my ($type,$trial,$rndseed);
                   2413:                 if ($hide eq 'rand') {
                   2414:                     $type = 'randomizetry';
                   2415:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2416:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2417:                 }
                   2418: 	        if ($env{'form.checkPlag'}) {
                   2419:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2420: 		        &most_similar($uname,$udom,$symb,$subval);
                   2421: 		    if ($osim) {
                   2422: 			$osim=int($osim*100.0);
                   2423:                         if ($hide eq 'anon') {
                   2424:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2425:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2426:                         } else {
1.753     raeburn  2427: 			    $similar='<hr />';
                   2428:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2429:                                 $similar .= '<h3><span class="LC_warning">'.
                   2430:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2431:                                                 $osim,
                   2432:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2433:                                             '</span></h3>';
                   2434:                             } else {
                   2435:                                 my %old_course_desc;
                   2436:                                 if ($ocrsid ne '') {
                   2437:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2438:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2439:                                     } else {
                   2440:                                         my $args;
                   2441:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2442:                                             $args = {'one_time' => 1};
                   2443:                                         }
                   2444:                                         %old_course_desc =
                   2445:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2446:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2447:                                     }
                   2448:                                     $similar .=
                   2449:                                         '<h3><span class="LC_warning">'.
                   2450:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2451:                                             $osim,
                   2452:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2453:                                             $old_course_desc{'description'},
                   2454:                                             $old_course_desc{'num'},
                   2455:                                             $old_course_desc{'domain'}).
                   2456:                                         '</span></h3>';
                   2457:                                 } else {
                   2458:                                     $similar .=
                   2459:                                         '<h3><span class="LC_warning">'.
                   2460:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2461:                                             $osim,
                   2462:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2463:                                         '</span></h3>';
                   2464:                                 }
                   2465:                             }
                   2466:                             $similar .= '<blockquote><i>'.
                   2467:                                         &keywords_highlight($oessay).
                   2468:                                         '</i></blockquote><hr />';
1.702     kruse    2469:                         }
                   2470: 	            }
                   2471: 		}
                   2472: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2473:                                      undef,$type,$trial,$rndseed);
                   2474:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2475: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2476: 		    my $display_part=&get_display_part($partid,$symb);
                   2477:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2478:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2479:                         ' <span class="LC_internal_info">'.
                   2480:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2481:                         '</span>&nbsp; &nbsp;';
                   2482: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2483:                         
                   2484: 		    if (@$files) {
                   2485:                         if ($hide eq 'anon') {
                   2486:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2487:                         } else {
                   2488:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2489:                                         .'<br /><span class="LC_warning">';
                   2490:                             if(@$files == 1) {
                   2491:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2492:                             } else {
1.702     kruse    2493:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2494:                             }
                   2495:                             $lastsubonly .= '</span>';                         
                   2496:                             foreach my $file (@$files) {
                   2497:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2498:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2499:                             }
                   2500:                         }
1.702     kruse    2501: 			$lastsubonly.='<br />';
                   2502:                     }
                   2503:                     if ($hide eq 'anon') {
                   2504:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2505:                     } else {
1.724     raeburn  2506:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2507:                         if ($draft) {
                   2508:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2509:                         }
                   2510:                         $subval =
1.702     kruse    2511: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2512: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2513:                         if ($responsetype eq 'essay') {
                   2514:                             $subval =~ s{\n}{<br />}g;
                   2515:                         }
                   2516:                         $lastsubonly.=$subval."\n";
1.702     kruse    2517:                     }
                   2518: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2519: 		    $lastsubonly.='</div>';
1.41      ng       2520: 		}
1.702     kruse    2521:             }
1.151     albertel 2522: 	}
1.702     kruse    2523: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2524:     }
                   2525:     $request->print($lastsubonly);
                   2526:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2527:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2528: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2529:   
1.702     kruse    2530:     } 
                   2531:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2532:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2533:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2534: 								 $env{'request.course.id'},
1.44      ng       2535: 								 $last,'.submission',
1.726     raeburn  2536: 								 'Apache::grades::keywords_highlight',
                   2537:                                                                  $usec,$identifier));
1.41      ng       2538:     }
1.121     ng       2539:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2540: 	.$udom.'" />'."\n");
1.44      ng       2541:     # return if view submission with no grading option
1.618     www      2542:     if (!&canmodify($usec)) {
1.633     www      2543: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2544: 	return;
1.180     albertel 2545:     } else {
1.468     albertel 2546: 	$request->print('</div>'."\n");
1.41      ng       2547:     }
1.33      ng       2548: 
1.121     ng       2549:     # essay grading message center
1.624     www      2550: #    if ($env{'form.handgrade'} eq 'yes') {
                   2551:     if (1) {
1.468     albertel 2552: 	my $result='<div class="LC_grade_message_center">';
                   2553:     
                   2554: 	$result.='<div class="LC_grade_message_center_header">'.
                   2555: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2556: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2557: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2558: 	if (scalar(@$col_fullnames) > 0) {
                   2559: 	    my $lastone = pop(@$col_fullnames);
                   2560: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2561: 	}
                   2562: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2563: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2564: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2565: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2566: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2567: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2568: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2569: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2570: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2571: 	    '<br />&nbsp;('.
1.468     albertel 2572: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2573: 	$result.='</div></div>';
1.121     ng       2574: 	$request->print($result);
1.118     ng       2575:     }
1.41      ng       2576: 
                   2577:     my %seen = ();
                   2578:     my @partlist;
1.129     ng       2579:     my @gradePartRespid;
1.745     raeburn  2580:     my @part_response_id;
                   2581:     if ($is_tool) {
                   2582:         @part_response_id = ([0,'']);
                   2583:     } else {
                   2584:         @part_response_id = &flatten_responseType($responseType);
                   2585:     }
1.585     bisitz   2586:     $request->print(
1.588     bisitz   2587:         '<div class="LC_Box">'
                   2588:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2589:     );
1.592     bisitz   2590:     $request->print(&gradeBox_start());
1.375     albertel 2591:     foreach my $part_response_id (@part_response_id) {
                   2592:     	my ($partid,$respid) = @{ $part_response_id };
                   2593: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2594: 	next if ($seen{$partid} > 0);
1.41      ng       2595: 	$seen{$partid}++;
1.393     albertel 2596: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2597: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2598: 	push(@partlist,$partid);
                   2599: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2600: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2601:     }
1.585     bisitz   2602:     $request->print(&gradeBox_end()); # </div>
                   2603:     $request->print('</div>');
1.468     albertel 2604: 
                   2605:     $request->print('<div class="LC_grade_info_links">');
                   2606:     $request->print('</div>');
                   2607: 
1.45      ng       2608:     $result='<input type="hidden" name="partlist'.$counter.
                   2609: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2610:     $result.='<input type="hidden" name="gradePartRespid'.
                   2611: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2612:     my $ctr = 0;
                   2613:     while ($ctr < scalar(@partlist)) {
                   2614: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2615: 	    $partlist[$ctr].'" />'."\n";
                   2616: 	$ctr++;
                   2617:     }
1.468     albertel 2618:     $request->print($result.''."\n");
1.41      ng       2619: 
1.441     www      2620: # Done with printing info for one student
                   2621: 
1.468     albertel 2622:     $request->print('</div>');#LC_grade_show_user
1.441     www      2623: 
                   2624: 
1.41      ng       2625:     # print end of form
                   2626:     if ($counter == $total) {
1.592     bisitz   2627:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2628: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2629: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2630: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2631: 	my $ntstu ='<select name="NTSTU">'.
                   2632: 	    '<option>1</option><option>2</option>'.
                   2633: 	    '<option>3</option><option>5</option>'.
                   2634: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2635: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2636: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2637:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2638: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2639: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2640: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2641: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2642:         $endform.='<span class="LC_warning">'.
                   2643:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2644:                   '</span>'."\n" ;
1.349     albertel 2645:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2646:             "' name='increment' />";
1.485     albertel 2647: 	$endform.='</td></tr></table></form>';
1.41      ng       2648: 	$request->print($endform);
                   2649:     }
                   2650:     return '';
1.38      ng       2651: }
                   2652: 
1.464     albertel 2653: sub check_collaborators {
                   2654:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2655:     my ($result,@col_fullnames);
                   2656:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2657:     foreach my $part (keys(%$handgrade)) {
                   2658: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2659: 					'.maxcollaborators',
                   2660: 					$symb,$udom,$uname);
                   2661: 	next if ($ncol <= 0);
                   2662: 	$part =~ s/\_/\./g;
                   2663: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2664: 	my (@good_collaborators, @bad_collaborators);
                   2665: 	foreach my $possible_collaborator
1.630     www      2666: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2667: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2668: 	    next if ($possible_collaborator eq '');
1.631     www      2669: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2670: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2671: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2672: 	    # Doing this grep allows 'fuzzy' specification
                   2673: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2674: 			       keys(%$classlist));
                   2675: 	    if (! scalar(@matches)) {
                   2676: 		push(@bad_collaborators, $possible_collaborator);
                   2677: 	    } else {
                   2678: 		push(@good_collaborators, @matches);
                   2679: 	    }
                   2680: 	}
                   2681: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2682: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2683: 	    foreach my $name (@good_collaborators) {
                   2684: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2685: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2686: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2687: 	    }
1.630     www      2688: 	    $result.='</ol><br />'."\n";
1.466     albertel 2689: 	    my ($part)=split(/\./,$part);
1.464     albertel 2690: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2691: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2692: 		"\n";
                   2693: 	}
                   2694: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2695: 	    $result.='<div class="LC_warning">';
1.464     albertel 2696: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2697: 	    $result .= '</div>';
                   2698: 	}         
                   2699: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2700: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2701: 	    $result .= &mt('This student has submitted too many '.
                   2702: 		'collaborators.  Maximum is [_1].',$ncol);
                   2703: 	    $result .= '</div>';
                   2704: 	}
                   2705:     }
                   2706:     return ($result,$fullname,\@col_fullnames);
                   2707: }
                   2708: 
1.44      ng       2709: #--- Retrieve the last submission for all the parts
1.38      ng       2710: sub get_last_submission {
1.745     raeburn  2711:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2712:     my (@string,$timestamp,%lasthidden);
1.119     ng       2713:     if ($$returnhash{'version'}) {
1.46      ng       2714: 	my %lasthash=();
                   2715: 	my ($version);
1.119     ng       2716: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2717: 	    foreach my $key (sort(split(/\:/,
                   2718: 					$$returnhash{$version.':keys'}))) {
                   2719: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2720: 		$timestamp = 
1.545     raeburn  2721: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2722: 	    }
                   2723: 	}
1.640     raeburn  2724:         my (%typeparts,%randombytry);
1.596     raeburn  2725:         my $showsurv = 
                   2726:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2727:         foreach my $key (sort(keys(%lasthash))) {
                   2728:             if ($key =~ /\.type$/) {
                   2729:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2730:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2731:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2732:                     my ($ign,@parts) = split(/\./,$key);
                   2733:                     pop(@parts);
1.641     raeburn  2734:                     my $id = join('.',@parts);
1.640     raeburn  2735:                     if ($lasthash{$key} eq 'randomizetry') {
                   2736:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2737:                     } else {
                   2738:                         unless ($showsurv) {
                   2739:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2740:                         }
1.596     raeburn  2741:                     }
                   2742:                     delete($lasthash{$key});
                   2743:                 }
                   2744:             }
                   2745:         }
                   2746:         my @hidden = keys(%typeparts);
1.640     raeburn  2747:         my @randomize = keys(%randombytry);
1.397     albertel 2748: 	foreach my $key (keys(%lasthash)) {
                   2749: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2750:             my $hide;
                   2751:             if (@hidden) {
                   2752:                 foreach my $id (@hidden) {
                   2753:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2754:                         $hide = 'anon';
1.596     raeburn  2755:                         last;
                   2756:                     }
                   2757:                 }
                   2758:             }
1.640     raeburn  2759:             unless ($hide) {
                   2760:                 if (@randomize) {
1.732     raeburn  2761:                     foreach my $id (@randomize) {
1.640     raeburn  2762:                         if ($key =~ /^\Q$id\E/) {
                   2763:                             $hide = 'rand';
                   2764:                             last;
                   2765:                         }
                   2766:                     }
                   2767:                 }
                   2768:             }
1.397     albertel 2769: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2770: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2771:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2772:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2773:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2774: 	}
                   2775:     }
1.397     albertel 2776:     if (!@string) {
1.745     raeburn  2777:         my $msg;
                   2778:         if ($is_tool) {
1.747     raeburn  2779:             $msg = &mt('No grade passed back.');
1.745     raeburn  2780:         } else {
                   2781:             $msg = &mt('Nothing submitted - no attempts.');
                   2782:         }
1.397     albertel 2783: 	$string[0] =
1.745     raeburn  2784: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2785:     }
                   2786:     return (\@string,\$timestamp);
1.38      ng       2787: }
1.35      ng       2788: 
1.44      ng       2789: #--- High light keywords, with style choosen by user.
1.38      ng       2790: sub keywords_highlight {
1.44      ng       2791:     my $string    = shift;
1.257     albertel 2792:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2793:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2794:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2795:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2796:     foreach my $keyword (@keylist) {
                   2797: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2798:     }
                   2799:     return $string;
1.38      ng       2800: }
1.36      ng       2801: 
1.671     raeburn  2802: # For Tasks provide a mechanism to display previous version for one specific student
                   2803: 
                   2804: sub show_previous_task_version {
                   2805:     my ($request,$symb) = @_;
                   2806:     if ($symb eq '') {
1.717     bisitz   2807:         $request->print(
                   2808:             '<span class="LC_error">'.
                   2809:             &mt('Unable to handle ambiguous references.').
                   2810:             '</span>');
1.671     raeburn  2811:         return '';
                   2812:     }
                   2813:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2814:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2815:     if (!&canview($usec)) {
1.712     bisitz   2816:         $request->print(
                   2817:             '<span class="LC_warning">'.
1.713     bisitz   2818:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2819:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2820:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2821:             '</span>');
1.671     raeburn  2822:         return;
                   2823:     }
                   2824:     my $mode = 'both';
                   2825:     my $isTask = ($symb =~/\.task$/);
                   2826:     if ($isTask) {
                   2827:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2828:             if ($env{'form.fullname'} eq '') {
                   2829:                 $env{'form.fullname'} =
                   2830:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2831:             }
                   2832:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2833:             $request->print("\n\n".
                   2834:                             '<div class="LC_grade_show_user">'.
                   2835:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2836:                             '</h2>'."\n");
                   2837:             &Apache::lonxml::clear_problem_counter();
                   2838:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2839:                             {'previousversion' => $env{'form.previousversion'} }));
                   2840:             $request->print("\n</div>");
                   2841:         }
                   2842:     }
                   2843:     return;
                   2844: }
                   2845: 
                   2846: sub choose_task_version_form {
                   2847:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2848:     my $isTask = ($symb =~/\.task$/);
                   2849:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2850:     if ($isTask) {
                   2851:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2852:                                               $udom,$uname);
                   2853:         if (($record{'resource.0.version'} eq '') ||
                   2854:             ($record{'resource.0.version'} < 2)) {
                   2855:             return ($record{'resource.0.version'},
                   2856:                     $record{'resource.0.version'},$result,$js);
                   2857:         } else {
                   2858:             $current = $record{'resource.0.version'};
                   2859:         }
                   2860:         if ($env{'form.previousversion'}) {
                   2861:             $displayed = $env{'form.previousversion'};
                   2862:             $rowtitle = &mt('Choose another version:')
                   2863:         } else {
                   2864:             $displayed = $current;
                   2865:             $rowtitle = &mt('Show earlier version:');
                   2866:         }
                   2867:         $result = '<div class="LC_left_float">';
                   2868:         my $list;
                   2869:         my $numversions = 0;
                   2870:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2871:             if ($i == $current) {
                   2872:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2873:                     next;
                   2874:                 } else {
                   2875:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2876:                     $numversions ++;
                   2877:                 }
                   2878:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2879:                 unless ($i == $env{'form.previousversion'}) {
                   2880:                     $numversions ++;
                   2881:                 }
                   2882:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2883:             }
                   2884:         }
                   2885:         if ($numversions) {
                   2886:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2887:             $result .=
                   2888:                 '<form name="getprev" method="post" action=""'.
                   2889:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2890:                 &Apache::loncommon::start_data_table().
                   2891:                 &Apache::loncommon::start_data_table_row().
                   2892:                 '<th align="left">'.$rowtitle.'</th>'.
                   2893:                 '<td><select name="version">'.
                   2894:                 '<option>'.&mt('Select').'</option>'.
                   2895:                 $list.
                   2896:                 '</select></td>'.
                   2897:                 &Apache::loncommon::end_data_table_row();
                   2898:             unless ($nomenu) {
                   2899:                 $result .= &Apache::loncommon::start_data_table_row().
                   2900:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2901:                 '<td><span class="LC_nobreak">'.
                   2902:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2903:                 &mt('Yes').'</label>'.
                   2904:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2905:                 '</span></td>'.
                   2906:                 &Apache::loncommon::end_data_table_row();
                   2907:             }
                   2908:             $result .=
                   2909:                 &Apache::loncommon::start_data_table_row().
                   2910:                 '<th align="left">&nbsp;</th>'.
                   2911:                 '<td>'.
                   2912:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2913:                 '</td>'.
                   2914:                 &Apache::loncommon::end_data_table_row().
                   2915:                 &Apache::loncommon::end_data_table().
                   2916:                 '</form>';
                   2917:             $js = &previous_display_javascript($nomenu,$current);
                   2918:         } elsif ($displayed && $nomenu) {
                   2919:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2920:         } else {
                   2921:             $result .= &mt('No previous versions to show for this student');
                   2922:         }
                   2923:         $result .= '</div>';
                   2924:     }
                   2925:     return ($current,$displayed,$result,$js);
                   2926: }
                   2927: 
                   2928: sub previous_display_javascript {
                   2929:     my ($nomenu,$current) = @_;
                   2930:     my $js = <<"JSONE";
                   2931: <script type="text/javascript">
                   2932: // <![CDATA[
                   2933: function previousVersion(uname,udom,symb) {
                   2934:     var current = '$current';
                   2935:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2936:     var prevstr = new RegExp("^\\\\d+\$");
                   2937:     if (!prevstr.test(version)) {
                   2938:         return false;
                   2939:     }
                   2940:     var url = '';
                   2941:     if (version == current) {
                   2942:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2943:     } else {
                   2944:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2945:     }
                   2946: JSONE
                   2947:     if ($nomenu) {
                   2948:         $js .= <<"JSTWO";
                   2949:     document.location.href = url;
                   2950: JSTWO
                   2951:     } else {
                   2952:         $js .= <<"JSTHREE";
                   2953:     var newwin = 0;
                   2954:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2955:         if (document.getprev.prevwin[i].checked == true) {
                   2956:             newwin = document.getprev.prevwin[i].value;
                   2957:         }
                   2958:     }
                   2959:     if (newwin == 1) {
                   2960:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2961:         url = url+'&inhibitmenu=yes';
                   2962:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2963:             previousWin = window.open(url,'',options,1);
                   2964:         } else {
                   2965:             previousWin.location.href = url;
                   2966:         }
                   2967:         previousWin.focus();
                   2968:         return false;
                   2969:     } else {
                   2970:         document.location.href = url;
                   2971:         return false;
                   2972:     }
                   2973: JSTHREE
                   2974:     }
                   2975:     $js .= <<"ENDJS";
                   2976:     return false;
                   2977: }
                   2978: // ]]>
                   2979: </script>
                   2980: ENDJS
                   2981: 
                   2982: }
                   2983: 
1.44      ng       2984: #--- Called from submission routine
1.38      ng       2985: sub processHandGrade {
1.608     www      2986:     my ($request,$symb) = @_;
1.324     albertel 2987:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2988:     my $button = $env{'form.gradeOpt'};
                   2989:     my $ngrade = $env{'form.NCT'};
                   2990:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2991:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2992:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2993: 
1.44      ng       2994:     if ($button eq 'Save & Next') {
                   2995: 	my $ctr = 0;
                   2996: 	while ($ctr < $ngrade) {
1.257     albertel 2997: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2998: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2999:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3000: 	    if ($errorflag eq 'no_score') {
                   3001: 		$ctr++;
                   3002: 		next;
                   3003: 	    }
1.104     albertel 3004: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3005: 		$request->print(
                   3006:                     '<span class="LC_error">'
                   3007:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3008:                    .'</span>');
1.104     albertel 3009: 		$ctr++;
                   3010: 		next;
                   3011: 	    }
1.726     raeburn  3012:             if ($numhidden) {
                   3013:                 $request->print(
                   3014:                     '<span class="LC_info">'
                   3015:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3016:                    .'</span><br />');
                   3017:             }
1.257     albertel 3018: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3019: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3020: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3021:             my ($feedurl,$showsymb) =
                   3022: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3023: 	    my $messagetail;
1.62      albertel 3024: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3025: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3026: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3027: 		$subject.=' ['.$restitle.']';
1.44      ng       3028: 		my (@msgnum) = split(/,/,$includemsg);
                   3029: 		foreach (@msgnum) {
1.257     albertel 3030: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3031: 		}
1.80      ng       3032: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3033: 		if ($env{'form.withgrades'.$ctr}) {
                   3034: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3035: 		    $messagetail = " for <a href=\"".
1.605     www      3036: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3037: 		}
                   3038: 		$msgstatus = 
                   3039:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3040: 						     $message.$messagetail,
1.418     albertel 3041:                                                      undef,$feedurl,undef,
1.386     raeburn  3042:                                                      undef,undef,$showsymb,
                   3043:                                                      $restitle);
1.574     bisitz   3044: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3045: 				$msgstatus.'<br />');
1.44      ng       3046: 	    }
1.257     albertel 3047: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3048: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3049: 		foreach my $collabstr (@collabstrs) {
                   3050: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3051: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3052: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3053: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3054: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3055: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3056: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3057: 			    next;
1.418     albertel 3058: 			} elsif ($message ne '') {
                   3059: 			    my ($baseurl,$showsymb) = 
                   3060: 				&get_feedurl_and_symb($symb,$collaborator,
                   3061: 						      $udom);
                   3062: 			    if ($env{'form.withgrades'.$ctr}) {
                   3063: 				$messagetail = " for <a href=\"".
1.605     www      3064:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3065: 			    }
1.418     albertel 3066: 			    $msgstatus = 
                   3067: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3068: 			}
1.44      ng       3069: 		    }
                   3070: 		}
                   3071: 	    }
                   3072: 	    $ctr++;
                   3073: 	}
                   3074:     }
                   3075: 
1.624     www      3076: #    if ($env{'form.handgrade'} eq 'yes') {
                   3077:     if (1) {
1.119     ng       3078: 	# Keywords sorted in alphabatical order
1.257     albertel 3079: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3080: 	my %keyhash = ();
1.257     albertel 3081: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3082: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3083: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3084: 	$env{'form.keywords'} = join(' ',@keywords);
                   3085: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3086: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3087: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3088: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3089: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3090: 
                   3091: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3092: 	# New messages are saved in env for the next student.
1.119     ng       3093: 	# All messages are saved in nohist_handgrade.db
                   3094: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3095: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3096: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3097: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3098: 		$idx++;
                   3099: 	    }
                   3100: 	    $ctr++;
1.41      ng       3101: 	}
1.119     ng       3102: 	$ctr = 0;
                   3103: 	while ($ctr < $ngrade) {
1.257     albertel 3104: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3105: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3106: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3107: 		$idx++;
                   3108: 	    }
                   3109: 	    $ctr++;
1.41      ng       3110: 	}
1.257     albertel 3111: 	$env{'form.savemsgN'} = --$idx;
                   3112: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3113: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3114: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3115:     }
1.44      ng       3116:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3117:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3118:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3119: 	my ($ctr,$total) = (0,0);
                   3120: 	while ($ctr < $ngrade) {
1.257     albertel 3121: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3122: 	    $ctr++;
                   3123: 	}
1.257     albertel 3124: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3125: 	$ctr = 0;
                   3126: 	while ($ctr < $total) {
1.257     albertel 3127: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3128: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3129: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3130: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3131: 	    $ctr++;
                   3132: 	}
                   3133: 	return '';
                   3134:     }
1.36      ng       3135: 
1.44      ng       3136:     # Get the next/previous one or group of students
1.257     albertel 3137:     my $firststu = $env{'form.unamedom0'};
                   3138:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3139:     my $ctr = 2;
1.41      ng       3140:     while ($laststu eq '') {
1.257     albertel 3141: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3142: 	$ctr++;
                   3143: 	$laststu = $firststu if ($ctr > $ngrade);
                   3144:     }
1.44      ng       3145: 
1.41      ng       3146:     my (@parsedlist,@nextlist);
                   3147:     my ($nextflg) = 0;
1.524     raeburn  3148:     foreach my $item (sort 
1.294     albertel 3149: 	     {
                   3150: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3151: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3152: 		 }
                   3153: 		 return $a cmp $b;
                   3154: 	     } (keys(%$fullname))) {
1.605     www      3155: # FIXME: this is fishy, looks like the button label
1.41      ng       3156: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3157: 	    push(@parsedlist,$item);
1.41      ng       3158: 	}
1.524     raeburn  3159: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3160: 	if ($button eq 'Previous') {
1.524     raeburn  3161: 	    last if ($item eq $firststu);
                   3162: 	    push(@parsedlist,$item);
1.41      ng       3163: 	}
                   3164:     }
                   3165:     $ctr = 0;
1.605     www      3166: # FIXME: this is fishy, looks like the button label
1.41      ng       3167:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3168:     my $res_error;
                   3169:     my ($partlist) = &response_type($symb,\$res_error);
                   3170:     if ($res_error) {
                   3171:         $request->print(&navmap_errormsg());
                   3172:         return;
                   3173:     }
1.41      ng       3174:     foreach my $student (@parsedlist) {
1.257     albertel 3175: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3176: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3177: 	
                   3178: 	if ($submitonly eq 'queued') {
                   3179: 	    my %queue_status = 
                   3180: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3181: 							$udom,$uname);
                   3182: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3183: 	}
                   3184: 
1.156     albertel 3185: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3186: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3187: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3188: 	    my $submitted = 0;
1.248     albertel 3189: 	    my $ungraded = 0;
                   3190: 	    my $incorrect = 0;
1.524     raeburn  3191: 	    foreach my $item (keys(%status)) {
                   3192: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3193: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3194: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3195: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3196: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3197: 		    $submitted = 0;
                   3198: 		}
1.41      ng       3199: 	    }
1.156     albertel 3200: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3201: 				     $submitonly eq 'incorrect' ||
                   3202: 				     $submitonly eq 'graded'));
1.248     albertel 3203: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3204: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3205: 	}
1.524     raeburn  3206: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3207: 	last if ($ctr == $ntstu);
1.41      ng       3208: 	$ctr++;
                   3209:     }
1.36      ng       3210: 
1.41      ng       3211:     $ctr = 0;
                   3212:     my $total = scalar(@nextlist)-1;
1.39      ng       3213: 
1.524     raeburn  3214:     foreach (sort(@nextlist)) {
1.41      ng       3215: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3216: 	$env{'form.student'}  = $uname;
                   3217: 	$env{'form.userdom'}  = $udom;
                   3218: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3219: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3220: 	$ctr++;
                   3221:     }
                   3222:     if ($total < 0) {
1.653     raeburn  3223: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3224: 	$request->print($the_end);
                   3225:     }
                   3226:     return '';
1.38      ng       3227: }
1.36      ng       3228: 
1.44      ng       3229: #---- Save the score and award for each student, if changed
1.38      ng       3230: sub saveHandGrade {
1.324     albertel 3231:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3232:     my @version_parts;
1.104     albertel 3233:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3234: 					   $env{'request.course.id'});
1.104     albertel 3235:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3236:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3237:     my @parts_graded;
1.77      ng       3238:     my %newrecord  = ();
1.726     raeburn  3239:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3240:     my %aggregate = ();
                   3241:     my $aggregateflag = 0;
1.726     raeburn  3242:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3243:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3244:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3245:         $totchg += $numchgs;
                   3246:     }
1.301     albertel 3247:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3248:     foreach my $new_part (@parts) {
1.337     banghart 3249: 	#collaborator ($submi may vary for different parts
1.259     banghart 3250: 	if ($submitter && $new_part ne $part) { next; }
                   3251: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3252: 	if ($dropMenu eq 'excused') {
1.259     banghart 3253: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3254: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3255: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3256: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3257: 		}
1.364     banghart 3258: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3259: 	    }
1.125     ng       3260: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3261: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3262: 	    foreach my $key (keys(%record)) {
1.259     banghart 3263: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3264: 	    }
1.259     banghart 3265: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3266: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3267:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3268: 
                   3269:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3270: 					       [$new_part]);
                   3271:             my $aggtries =$totaltries;
1.269     raeburn  3272:             if ($last_resets{$new_part}) {
1.270     albertel 3273:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3274: 					   $new_part);
1.269     raeburn  3275:             }
1.270     albertel 3276: 
                   3277:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3278:             if ($aggtries > 0) {
1.327     albertel 3279:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3280:                 $aggregateflag = 1;
                   3281:             }
1.125     ng       3282: 	} elsif ($dropMenu eq '') {
1.259     banghart 3283: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3284: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3285: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3286: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3287: 		next;
                   3288: 	    }
1.259     banghart 3289: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3290: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3291: 	    my $partial= $pts/$wgt;
1.259     banghart 3292: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3293: 		#do not update score for part if not changed.
1.346     banghart 3294:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3295: 		next;
1.251     banghart 3296: 	    } else {
1.524     raeburn  3297: 	        push(@parts_graded,$new_part);
1.153     albertel 3298: 	    }
1.259     banghart 3299: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3300: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3301: 	    }
1.259     banghart 3302: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3303: 	    if ($partial == 0) {
1.153     albertel 3304: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3305: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3306: 		}
1.41      ng       3307: 	    } else {
1.153     albertel 3308: 		if ($record{$reckey} ne 'correct_by_override') {
                   3309: 		    $newrecord{$reckey} = 'correct_by_override';
                   3310: 		}
                   3311: 	    }	    
                   3312: 	    if ($submitter && 
1.259     banghart 3313: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3314: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3315: 	    }
1.259     banghart 3316: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3317: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3318: 	}
1.259     banghart 3319: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3320: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3321: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3322: 	        $dropMenu eq 'reset status')
                   3323: 	   {
1.524     raeburn  3324: 	    push(@version_parts,$new_part);
1.259     banghart 3325: 	}
1.41      ng       3326:     }
1.301     albertel 3327:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3328:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3329: 
1.344     albertel 3330:     if (%newrecord) {
                   3331:         if (@version_parts) {
1.364     banghart 3332:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3333:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3334: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3335: 	    foreach my $new_part (@version_parts) {
                   3336: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3337: 				$new_part,\%newrecord);
                   3338: 	    }
1.259     banghart 3339:         }
1.44      ng       3340: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3341: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3342: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3343: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3344:     }
1.269     raeburn  3345:     if ($aggregateflag) {
                   3346:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3347: 			      $cdom,$cnum);
1.269     raeburn  3348:     }
1.726     raeburn  3349:     return ('',$pts,$wgt,$totchg);
                   3350: }
                   3351: 
                   3352: sub makehidden {
1.728     raeburn  3353:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3354:     return unless (ref($record) eq 'HASH');
                   3355:     my %modified;
                   3356:     my $numchanged = 0;
                   3357:     if (exists($record->{$version.':keys'})) {
                   3358:         my $partsregexp = $parts;
                   3359:         $partsregexp =~ s/,/|/g;
                   3360:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3361:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3362:                  my $item = $1;
                   3363:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3364:                      $modified{$key} = $record->{$version.':'.$key};
                   3365:                  }
                   3366:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3367:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3368:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3369:                 $modified{$key} = $record->{$version.':'.$key};
                   3370:             }
                   3371:         }
                   3372:         if (keys(%modified)) {
                   3373:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3374:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3375:                 $numchanged ++;
                   3376:             }
                   3377:         }
                   3378:     }
                   3379:     return $numchanged;
1.36      ng       3380: }
1.322     albertel 3381: 
1.380     albertel 3382: sub check_and_remove_from_queue {
                   3383:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3384:     my @ungraded_parts;
                   3385:     foreach my $part (@{$parts}) {
                   3386: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3387: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3388: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3389: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3390: 		) {
                   3391: 	    push(@ungraded_parts, $part);
                   3392: 	}
                   3393:     }
                   3394:     if ( !@ungraded_parts ) {
                   3395: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3396: 					       $cnum,$domain,$stuname);
                   3397:     }
                   3398: }
                   3399: 
1.337     banghart 3400: sub handback_files {
                   3401:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3402:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3403:     my $res_error;
                   3404:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3405:     if ($res_error) {
                   3406:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3407:         return;
                   3408:     }
1.654     raeburn  3409:     my @handedback;
                   3410:     my $file_msg;
1.375     albertel 3411:     my @part_response_id = &flatten_responseType($responseType);
                   3412:     foreach my $part_response_id (@part_response_id) {
                   3413:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3414: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3415:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3416:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3417:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3418:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3419:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3420:                     my ($directory,$answer_file) = 
1.654     raeburn  3421:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3422:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3423: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3424: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3425:                     my $getpropath = 1;
1.662     raeburn  3426:                     my ($dir_list,$listerror) = 
                   3427:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3428:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3429: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3430:                     # fix filename
1.355     banghart 3431:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3432:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3433:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3434:             	                                $save_file_name);
1.337     banghart 3435:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3436:                         $request->print('<br /><span class="LC_error">'.
                   3437:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3438:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3439:                                         '</span>');
1.356     banghart 3440:                     } else {
1.360     banghart 3441:                         # mark the file as read only
1.654     raeburn  3442:                         push(@handedback,$save_file_name);
1.367     albertel 3443: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3444: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3445: 			}
                   3446:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3447: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3448:                     }
1.686     bisitz   3449:                     $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 3450:                 }
                   3451:             }
                   3452:         }
1.654     raeburn  3453:     }
                   3454:     if (@handedback > 0) {
                   3455:         $request->print('<br />');
                   3456:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3457:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3458:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3459:         my ($subject,$message);
                   3460:         if (scalar(@handedback) == 1) {
                   3461:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3462:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3463:         } else {
                   3464:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3465:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3466:         }
                   3467:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3468:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3469:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3470:         my ($feedurl,$showsymb) =
                   3471:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3472:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3473:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3474:         my $msgstatus =
                   3475:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3476:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3477:                  $restitle);
                   3478:         if ($msgstatus) {
                   3479:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3480:         }
                   3481:     }
1.338     banghart 3482:     return;
1.337     banghart 3483: }
                   3484: 
1.418     albertel 3485: sub get_feedurl_and_symb {
                   3486:     my ($symb,$uname,$udom) = @_;
                   3487:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3488:     $url = &Apache::lonnet::clutter($url);
                   3489:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3490: 					$symb,$udom,$uname);
                   3491:     if ($encrypturl =~ /^yes$/i) {
                   3492: 	&Apache::lonenc::encrypted(\$url,1);
                   3493: 	&Apache::lonenc::encrypted(\$symb,1);
                   3494:     }
                   3495:     return ($url,$symb);
                   3496: }
                   3497: 
1.313     banghart 3498: sub get_submitted_files {
                   3499:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3500:     my @files;
                   3501:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3502:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3503:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3504:     	    push(@files,$file_url.$file);
                   3505:         }
                   3506:     }
                   3507:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3508:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3509:     }
                   3510:     return (\@files);
                   3511: }
1.322     albertel 3512: 
1.269     raeburn  3513: # ----------- Provides number of tries since last reset.
                   3514: sub get_num_tries {
                   3515:     my ($record,$last_reset,$part) = @_;
                   3516:     my $timestamp = '';
                   3517:     my $num_tries = 0;
                   3518:     if ($$record{'version'}) {
                   3519:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3520:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3521:                 $timestamp = $$record{$version.':timestamp'};
                   3522:                 if ($timestamp > $last_reset) {
                   3523:                     $num_tries ++;
                   3524:                 } else {
                   3525:                     last;
                   3526:                 }
                   3527:             }
                   3528:         }
                   3529:     }
                   3530:     return $num_tries;
                   3531: }
                   3532: 
                   3533: # ----------- Determine decrements required in aggregate totals 
                   3534: sub decrement_aggs {
                   3535:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3536:     my %decrement = (
                   3537:                         attempts => 0,
                   3538:                         users => 0,
                   3539:                         correct => 0
                   3540:                     );
                   3541:     $decrement{'attempts'} = $aggtries;
                   3542:     if ($solvedstatus =~ /^correct/) {
                   3543:         $decrement{'correct'} = 1;
                   3544:     }
                   3545:     if ($aggtries == $totaltries) {
                   3546:         $decrement{'users'} = 1;
                   3547:     }
1.524     raeburn  3548:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3549:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3550:     }
                   3551:     return;
                   3552: }
                   3553: 
                   3554: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3555: sub get_last_resets {
1.270     albertel 3556:     my ($symb,$courseid,$partids) =@_;
                   3557:     my %last_resets;
1.269     raeburn  3558:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3559:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3560:     my @keys;
                   3561:     foreach my $part (@{$partids}) {
                   3562: 	push(@keys,"$symb\0$part\0resettime");
                   3563:     }
                   3564:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3565: 				     $cdom,$cname);
                   3566:     foreach my $part (@{$partids}) {
                   3567: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3568:     }
1.270     albertel 3569:     return %last_resets;
1.269     raeburn  3570: }
                   3571: 
1.251     banghart 3572: # ----------- Handles creating versions for portfolio files as answers
                   3573: sub version_portfiles {
1.343     banghart 3574:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3575:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3576:     my @returned_keys;
1.255     banghart 3577:     my $parts = join('|', @$parts_graded);
1.277     albertel 3578:     foreach my $key (keys(%$record)) {
1.259     banghart 3579:         my $new_portfiles;
1.263     banghart 3580:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3581:             my @versioned_portfiles;
1.367     albertel 3582:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3583:             if (@portfiles) {
                   3584:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3585:                                                       \@versioned_portfiles);
1.252     banghart 3586:             }
1.343     banghart 3587:             $$record{$key} = join(',',@versioned_portfiles);
                   3588:             push(@returned_keys,$key);
1.251     banghart 3589:         }
                   3590:     } 
1.343     banghart 3591:     return (@returned_keys);   
1.305     banghart 3592: }
                   3593: 
1.44      ng       3594: #--------------------------------------------------------------------------------------
                   3595: #
                   3596: #-------------------------- Next few routines handles grading by section or whole class
                   3597: #
                   3598: #--- Javascript to handle grading by section or whole class
1.42      ng       3599: sub viewgrades_js {
                   3600:     my ($request) = shift;
                   3601: 
1.539     riegler  3602:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3603:     &js_escape(\$alertmsg);
1.597     wenzelju 3604:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3605:    function writePoint(partid,weight,point) {
1.125     ng       3606: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3607: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3608: 	if (point == "textval") {
1.125     ng       3609: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3610: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3611: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3612: 		var resetbox = false;
                   3613: 		for (var i=0; i<radioButton.length; i++) {
                   3614: 		    if (radioButton[i].checked) {
                   3615: 			textbox.value = i;
                   3616: 			resetbox = true;
                   3617: 		    }
                   3618: 		}
                   3619: 		if (!resetbox) {
                   3620: 		    textbox.value = "";
                   3621: 		}
                   3622: 		return;
                   3623: 	    }
1.109     matthew  3624: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3625: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3626: 				   ") greater than the weight for the part. Accept?");
                   3627: 		if (resp == false) {
                   3628: 		    textbox.value = "";
                   3629: 		    return;
                   3630: 		}
                   3631: 	    }
1.42      ng       3632: 	    for (var i=0; i<radioButton.length; i++) {
                   3633: 		radioButton[i].checked=false;
1.109     matthew  3634: 		if (parseFloat(point) == i) {
1.42      ng       3635: 		    radioButton[i].checked=true;
                   3636: 		}
                   3637: 	    }
1.41      ng       3638: 
1.42      ng       3639: 	} else {
1.125     ng       3640: 	    textbox.value = parseFloat(point);
1.42      ng       3641: 	}
1.41      ng       3642: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3643: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3644: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3645: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3646: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3647: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3648: 	    if (saveval != "correct") {
                   3649: 		scorename.value = point;
1.43      ng       3650: 		if (selname[0].selected != true) {
                   3651: 		    selname[0].selected = true;
                   3652: 		}
1.42      ng       3653: 	    }
                   3654: 	}
1.125     ng       3655: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3656:     }
                   3657: 
                   3658:     function writeRadText(partid,weight) {
1.125     ng       3659: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3660: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3661:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3662: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3663: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3664: 	    for (var i=0; i<radioButton.length; i++) {
                   3665: 		radioButton[i].checked=false;
                   3666: 
                   3667: 	    }
                   3668: 	    textbox.value = "";
                   3669: 
                   3670: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3671: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3672: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3673: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3674: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3675: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3676: 		if ((saveval != "correct") || override) {
1.42      ng       3677: 		    scorename.value = "";
1.125     ng       3678: 		    if (selval[1].selected) {
                   3679: 			selname[1].selected = true;
                   3680: 		    } else {
                   3681: 			selname[2].selected = true;
                   3682: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3683: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3684: 		    }
1.42      ng       3685: 		}
                   3686: 	    }
1.43      ng       3687: 	} else {
                   3688: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3689: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3690: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3691: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3692: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3693: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3694: 		if ((saveval != "correct") || override) {
1.125     ng       3695: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3696: 		    selname[0].selected = true;
                   3697: 		}
                   3698: 	    }
                   3699: 	}	    
1.42      ng       3700:     }
                   3701: 
                   3702:     function changeSelect(partid,user) {
1.125     ng       3703: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3704: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3705: 	var point  = textbox.value;
1.125     ng       3706: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3707: 
1.109     matthew  3708: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3709: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3710: 	    textbox.value = "";
                   3711: 	    return;
                   3712: 	}
1.109     matthew  3713: 	if (parseFloat(point) > parseFloat(weight)) {
                   3714: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3715: 			       ") greater than the weight of the part. Accept?");
                   3716: 	    if (resp == false) {
                   3717: 		textbox.value = "";
                   3718: 		return;
                   3719: 	    }
                   3720: 	}
1.42      ng       3721: 	selval[0].selected = true;
                   3722:     }
                   3723: 
                   3724:     function changeOneScore(partid,user) {
1.125     ng       3725: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3726: 	if (selval[1].selected || selval[2].selected) {
                   3727: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3728: 	    if (selval[2].selected) {
                   3729: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3730: 	    }
1.269     raeburn  3731:         }
1.42      ng       3732:     }
                   3733: 
                   3734:     function resetEntry(numpart) {
                   3735: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3736: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3737: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3738: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3739: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3740: 	    for (var i=0; i<radioButton.length; i++) {
                   3741: 		radioButton[i].checked=false;
                   3742: 
                   3743: 	    }
                   3744: 	    textbox.value = "";
                   3745: 	    selval[0].selected = true;
                   3746: 
                   3747: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3748: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3749: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3750: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3751: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3752: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3753: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3754: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3755: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3756: 		if (saveselval == "excused") {
1.43      ng       3757: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3758: 		} else {
1.43      ng       3759: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3760: 		}
                   3761: 	    }
1.41      ng       3762: 	}
1.42      ng       3763:     }
                   3764: 
1.41      ng       3765: VIEWJAVASCRIPT
1.42      ng       3766: }
                   3767: 
1.44      ng       3768: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3769: sub viewgrades {
1.608     www      3770:     my ($request,$symb) = @_;
1.745     raeburn  3771:     my ($is_tool,$toolsymb);
                   3772:     if ($symb =~ /ext\.tool$/) {
                   3773:         $is_tool = 1;
                   3774:         $toolsymb = $symb;
                   3775:     }
1.42      ng       3776:     &viewgrades_js($request);
1.41      ng       3777: 
1.168     albertel 3778:     #need to make sure we have the correct data for later EXT calls, 
                   3779:     #thus invalidate the cache
                   3780:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3781:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3782:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3783:     &Apache::lonnet::clear_EXT_cache_status();
                   3784: 
1.398     albertel 3785:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3786: 
                   3787:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3788:     $result.=&jscriptNform($symb);
1.41      ng       3789: 
1.44      ng       3790:     #beginning of class grading form
1.442     banghart 3791:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3792:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3793: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3794: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3795: 	&build_section_inputs().
1.442     banghart 3796: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3797: 
1.738     raeburn  3798:     #retrieve selected groups
                   3799:     my (@groups,$group_display);
                   3800:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3801:     if (grep(/^all$/,@groups)) {
                   3802:         @groups = ('all');
                   3803:     } elsif (grep(/^none$/,@groups)) {
                   3804:         @groups = ('none');
                   3805:     } elsif (@groups > 0) {
                   3806:         $group_display = join(', ',@groups);
                   3807:     }
                   3808: 
                   3809:     my ($common_header,$specific_header,@sections,$section_display);
                   3810:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3811:     if (grep(/^all$/,@sections)) {
                   3812:         @sections = ('all');
                   3813:         if ($group_display) {
                   3814:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3815:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3816:         } elsif (grep(/^none$/,@groups)) {
                   3817:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3818:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3819:         } else {
                   3820: 	    $common_header = &mt('Assign Common Grade to Class');
                   3821:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3822:         }
                   3823:     } elsif (grep(/^none$/,@sections)) {
                   3824:         @sections = ('none');
                   3825:         if ($group_display) {
                   3826:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3827:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3828:         } elsif (grep(/^none$/,@groups)) {
                   3829:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3830:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3831:         } else {
                   3832:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3833: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3834:         }
                   3835:     } else {
                   3836:         $section_display = join (", ",@sections);
                   3837:         if ($group_display) {
                   3838:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3839:                                  $section_display,$group_display);
                   3840:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3841:                                    $section_display,$group_display);
                   3842:         } elsif (grep(/^none$/,@groups)) {
                   3843:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3844:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3845:         } else {
                   3846:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3847: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3848:         }
                   3849:     }
                   3850:     my %submit_types = &substatus_options();
                   3851:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3852: 
                   3853:     if ($env{'form.submitonly'} eq 'all') {
                   3854:         $result.= '<h3>'.$common_header.'</h3>';
                   3855:     } else {
1.745     raeburn  3856:         my $text;
                   3857:         if ($is_tool) {
                   3858:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3859:         } else {
                   3860:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3861:         }
                   3862:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3863:     }
1.738     raeburn  3864:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3865:     #radio buttons/text box for assigning points for a section or class.
                   3866:     #handles different parts of a problem
1.582     raeburn  3867:     my $res_error;
                   3868:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3869:     if ($res_error) {
                   3870:         return &navmap_errormsg();
                   3871:     }
1.42      ng       3872:     my %weight = ();
                   3873:     my $ctsparts = 0;
1.45      ng       3874:     my %seen = ();
1.745     raeburn  3875:     my @part_response_id;
                   3876:     if ($is_tool) {
                   3877:         @part_response_id = ([0,'']);
                   3878:     } else {
                   3879:         @part_response_id = &flatten_responseType($responseType);
                   3880:     }
1.375     albertel 3881:     foreach my $part_response_id (@part_response_id) {
                   3882:     	my ($partid,$respid) = @{ $part_response_id };
                   3883: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3884: 	next if $seen{$partid};
                   3885: 	$seen{$partid}++;
1.744     raeburn  3886: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3887: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3888: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3889: 
1.324     albertel 3890: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3891: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3892: 	my $ctr = 0;
1.42      ng       3893: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3894: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3895: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3896: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3897: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3898: 	    $ctr++;
                   3899: 	}
1.485     albertel 3900: 	$radio.='</tr></table>';
                   3901: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3902: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3903: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3904: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3905:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3906:             '<select name="SELVAL_'.$partid.'" '.
                   3907:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3908:                 $weight{$partid}.')"> '.
1.401     albertel 3909: 	    '<option selected="selected"> </option>'.
1.485     albertel 3910: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3911: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3912: 	    '</select></td>'.
                   3913:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3914: 	$line.='<input type="hidden" name="partid_'.
                   3915: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3916: 	$line.='<input type="hidden" name="weight_'.
                   3917: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3918: 
                   3919: 	$result.=
                   3920: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3921: 	    '<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 3922: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3923: 	$ctsparts++;
1.41      ng       3924:     }
1.474     albertel 3925:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3926: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3927:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3928: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3929: 
1.44      ng       3930:     #table listing all the students in a section/class
                   3931:     #header of table
1.738     raeburn  3932:     if ($env{'form.submitonly'} eq 'all') {
                   3933:         $result.= '<h3>'.$specific_header.'</h3>';
                   3934:     } else {
1.745     raeburn  3935:         my $text;
                   3936:         if ($is_tool) {
                   3937:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3938:         } else {
                   3939:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3940:         }
                   3941:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3942:     }
                   3943:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3944: 	      &Apache::loncommon::start_data_table_header_row().
                   3945: 	      '<th>'.&mt('No.').'</th>'.
                   3946: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3947:     my $partserror;
                   3948:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3949:     if ($partserror) {
                   3950:         return &navmap_errormsg();
                   3951:     }
1.324     albertel 3952:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3953:     my @partids = ();
1.41      ng       3954:     foreach my $part (@parts) {
1.745     raeburn  3955: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3956:         my $narrowtext = &mt('Tries');
                   3957: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3958: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3959: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3960:         push(@partids,$partid);
1.628     www      3961: #
                   3962: # FIXME: Looks like $display looks at English text
                   3963: #
1.324     albertel 3964: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3965: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3966: 	    $result.='<th>'.
1.697     bisitz   3967: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3968: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3969: 	    next;
1.485     albertel 3970: 	    
1.207     albertel 3971: 	} else {
1.485     albertel 3972: 	    if ($display =~ /Problem Status/) {
                   3973: 		my $grade_status_mt = &mt('Grade Status');
                   3974: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3975: 	    }
                   3976: 	    my $part_mt = &mt('Part:');
                   3977: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3978: 	}
1.485     albertel 3979: 
1.474     albertel 3980: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3981:     }
1.474     albertel 3982:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3983: 
1.270     albertel 3984:     my %last_resets = 
                   3985: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3986: 
1.41      ng       3987:     #get info for each student
1.44      ng       3988:     #list all the students - with points and grade status
1.738     raeburn  3989:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3990:     my $ctr = 0;
1.294     albertel 3991:     foreach (sort 
                   3992: 	     {
                   3993: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3994: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3995: 		 }
                   3996: 		 return $a cmp $b;
                   3997: 	     } (keys(%$fullname))) {
1.324     albertel 3998: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  3999: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4000:     }
1.474     albertel 4001:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4002:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4003:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4004: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4005:     if ($ctr == 0) {
1.442     banghart 4006:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4007:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4008:                 '<span class="LC_warning">';
                   4009:         if ($env{'form.submitonly'} eq 'all') {
                   4010:             if (grep(/^all$/,@sections)) {
                   4011:                 if (grep(/^all$/,@groups)) {
                   4012:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4013:                                    $stu_status);
                   4014:                 } elsif (grep(/^none$/,@groups)) {
                   4015:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4016:                                    $stu_status); 
                   4017:                 } else {
                   4018:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4019:                                    $group_display,$stu_status);
                   4020:                 }
                   4021:             } elsif (grep(/^none$/,@sections)) {
                   4022:                 if (grep(/^all$/,@groups)) {
                   4023:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4024:                                    $stu_status);
                   4025:                 } elsif (grep(/^none$/,@groups)) {
                   4026:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4027:                                    $stu_status);
                   4028:                 } else {
                   4029:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4030:                                    $group_display,$stu_status);
                   4031:                 }
                   4032:             } else {
                   4033:                 if (grep(/^all$/,@groups)) {
                   4034:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4035:                                    $section_display,$stu_status);
                   4036:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4037:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4038:                                    $section_display,$stu_status);
                   4039:                 } else {
                   4040:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4041:                                    $section_display,$group_display,$stu_status);
                   4042:                 }
                   4043:             }
                   4044:         } else {
                   4045:             if (grep(/^all$/,@sections)) {
                   4046:                 if (grep(/^all$/,@groups)) {
                   4047:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4048:                                    $stu_status,$submission_status);
                   4049:                 } elsif (grep(/^none$/,@groups)) {
                   4050:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4051:                                    $stu_status,$submission_status);
                   4052:                 } else {
                   4053:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4054:                                    $group_display,$stu_status,$submission_status);
                   4055:                 }
                   4056:             } elsif (grep(/^none$/,@sections)) {
                   4057:                 if (grep(/^all$/,@groups)) {
                   4058:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4059:                                    $stu_status,$submission_status);
                   4060:                 } elsif (grep(/^none$/,@groups)) {
                   4061:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4062:                                    $stu_status,$submission_status);
                   4063:                 } else {
                   4064:                     $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.',
                   4065:                                    $group_display,$stu_status,$submission_status);
                   4066:                 }
                   4067:             } else {
                   4068:                 if (grep(/^all$/,@groups)) {
                   4069: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4070: 	                           $section_display,$stu_status,$submission_status);
                   4071:                 } elsif (grep(/^none$/,@groups)) {
                   4072:                     $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.',
                   4073:                                    $section_display,$stu_status,$submission_status);
                   4074:                 } else {
                   4075:                     $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.',
                   4076:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4077:                 }
                   4078:             }
                   4079:         }
                   4080: 	$result .= '</span><br />';
1.96      albertel 4081:     }
1.41      ng       4082:     return $result;
                   4083: }
                   4084: 
1.738     raeburn  4085: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4086: sub viewstudentgrade {
1.745     raeburn  4087:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4088:     my ($uname,$udom) = split(/:/,$student);
                   4089:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4090:     my $submitonly = $env{'form.submitonly'};
                   4091:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4092:         my %partstatus = ();
                   4093:         if (ref($parts) eq 'ARRAY') {
                   4094:             foreach my $apart (@{$parts}) {
                   4095:                 my ($part,$type) = &split_part_type($apart);
                   4096:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4097:                 $status = 'nothing' if ($status eq '');
                   4098:                 $partstatus{$part}      = $status;
                   4099:                 my $subkey = "resource.$part.submitted_by";
                   4100:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4101:             }
                   4102:             my $submitted = 0;
                   4103:             my $graded = 0;
                   4104:             my $incorrect = 0;
                   4105:             foreach my $key (keys(%partstatus)) {
                   4106:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4107:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4108:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4109: 
                   4110:                 my $partid = (split(/\./,$key))[1];
                   4111:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4112:                     $submitted = 0;
                   4113:                 }
                   4114:             }
                   4115:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4116:                                        $submitonly eq 'incorrect' ||
                   4117:                                        $submitonly eq 'graded'));
                   4118:             return if (!$graded && ($submitonly eq 'graded'));
                   4119:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4120:         }
                   4121:     }
                   4122:     if ($submitonly eq 'queued') {
                   4123:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4124:         my %queue_status =
                   4125:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4126:                                                     $udom,$uname);
                   4127:         return if (!defined($queue_status{'gradingqueue'}));
                   4128:     }
                   4129:     $$ctr++;
                   4130:     my %aggregates = ();
1.474     albertel 4131:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4132: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4133: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4134: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4135: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4136: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4137:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4138:     foreach my $apart (@$parts) {
                   4139: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4140: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4141:         $result.='<td align="center">';
1.269     raeburn  4142:         my ($aggtries,$totaltries);
                   4143:         unless (exists($aggregates{$part})) {
1.270     albertel 4144: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4145: 	    $aggtries = $totaltries;
1.269     raeburn  4146:             if ($$last_resets{$part}) {  
1.270     albertel 4147:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4148: 					   $part);
                   4149:             }
1.269     raeburn  4150:             $result.='<input type="hidden" name="'.
                   4151:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4152:             $result.='<input type="hidden" name="'.
                   4153:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4154:             $aggregates{$part} = 1;
                   4155:         }
1.41      ng       4156: 	if ($type eq 'awarded') {
1.320     albertel 4157: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4158: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4159: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4160: 	    $result.='<input type="text" name="'.
1.89      albertel 4161: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4162:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4163: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4164: 	} elsif ($type eq 'solved') {
                   4165: 	    my ($status,$foo)=split(/_/,$score,2);
                   4166: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4167: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4168: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4169: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4170: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4171:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4172: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4173: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4174: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4175: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4176: 	} else {
                   4177: 	    $result.='<input type="hidden" name="'.
                   4178: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4179: 		    "\n";
1.233     albertel 4180: 	    $result.='<input type="text" name="'.
1.122     ng       4181: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4182: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4183: 	}
                   4184:     }
1.474     albertel 4185:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4186:     return $result;
1.38      ng       4187: }
                   4188: 
1.44      ng       4189: #--- change scores for all the students in a section/class
                   4190: #    record does not get update if unchanged
1.38      ng       4191: sub editgrades {
1.608     www      4192:     my ($request,$symb) = @_;
1.745     raeburn  4193:     my $toolsymb;
                   4194:     if ($symb =~ /ext\.tool$/) {
                   4195:         $toolsymb = $symb;
                   4196:     }
1.41      ng       4197: 
1.433     banghart 4198:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4199:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 4200:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       4201: 
1.477     albertel 4202:     my $result= &Apache::loncommon::start_data_table().
                   4203: 	&Apache::loncommon::start_data_table_header_row().
                   4204: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4205: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4206:     my %scoreptr = (
                   4207: 		    'correct'  =>'correct_by_override',
                   4208: 		    'incorrect'=>'incorrect_by_override',
                   4209: 		    'excused'  =>'excused',
                   4210: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4211:                     'credited' =>'credit_attempted',
1.43      ng       4212: 		    'nothing'  => '',
                   4213: 		    );
1.257     albertel 4214:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4215: 
1.44      ng       4216:     my (@partid);
                   4217:     my %weight = ();
1.54      albertel 4218:     my %columns = ();
1.44      ng       4219:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4220: 
1.582     raeburn  4221:     my $partserror;
                   4222:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4223:     if ($partserror) {
                   4224:         return &navmap_errormsg();
                   4225:     }
1.54      albertel 4226:     my $header;
1.257     albertel 4227:     while ($ctr < $env{'form.totalparts'}) {
                   4228: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4229: 	push(@partid,$partid);
1.257     albertel 4230: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4231: 	$ctr++;
1.54      albertel 4232:     }
1.324     albertel 4233:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4234:     my $totcolspan = 0;
1.54      albertel 4235:     foreach my $partid (@partid) {
1.478     albertel 4236: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4237: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4238: 	$columns{$partid}=2;
                   4239: 	foreach my $stores (@parts) {
                   4240: 	    my ($part,$type) = &split_part_type($stores);
                   4241: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4242: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4243: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4244: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4245:             my $narrowtext = &mt('Tries');
                   4246: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4247: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4248: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4249: 	    $columns{$partid}+=2;
                   4250: 	}
1.748     raeburn  4251:         $totcolspan += $columns{$partid};
1.54      albertel 4252:     }
                   4253:     foreach my $partid (@partid) {
1.324     albertel 4254: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4255: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4256: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4257: 	    '</th>';
1.54      albertel 4258: 
1.44      ng       4259:     }
1.477     albertel 4260:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4261: 	&Apache::loncommon::start_data_table_header_row().
                   4262: 	$header.
                   4263: 	&Apache::loncommon::end_data_table_header_row();
                   4264:     my @noupdate;
1.126     ng       4265:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4266:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4267: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4268: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4269: 	my %newrecord;
                   4270: 	my $updateflag = 0;
1.108     albertel 4271: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4272: 	my $canmodify = &canmodify($usec);
                   4273: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4274: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4275: 	if (!$canmodify) {
1.477     albertel 4276: 	    push(@noupdate,
1.748     raeburn  4277: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4278: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4279: 	    next;
                   4280: 	}
1.269     raeburn  4281:         my %aggregate = ();
                   4282:         my $aggregateflag = 0;
1.281     albertel 4283: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4284: 	foreach (@partid) {
1.257     albertel 4285: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4286: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4287: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4288: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4289: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4290: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4291: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4292: 	    my $score;
                   4293: 	    if ($partial eq '') {
1.257     albertel 4294: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4295: 	    } elsif ($partial > 0) {
                   4296: 		$score = 'correct_by_override';
                   4297: 	    } elsif ($partial == 0) {
                   4298: 		$score = 'incorrect_by_override';
                   4299: 	    }
1.257     albertel 4300: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4301: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4302: 
1.292     albertel 4303: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4304: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4305: 	    if ($dropMenu eq 'reset status' &&
                   4306: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4307: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4308: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4309: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4310: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4311: 		$updateflag = 1;
1.269     raeburn  4312:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4313:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4314:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4315:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4316:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4317:                     $aggregateflag = 1;
                   4318:                 }
1.139     albertel 4319: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4320: 		$updateflag = 1;
                   4321: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4322: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4323: 		$rec_update++;
1.125     ng       4324: 	    }
                   4325: 
1.93      albertel 4326: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4327: 		'<td align="center">'.$awarded.
                   4328: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4329: 
1.54      albertel 4330: 
                   4331: 	    my $partid=$_;
                   4332: 	    foreach my $stores (@parts) {
                   4333: 		my ($part,$type) = &split_part_type($stores);
                   4334: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4335: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4336: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4337: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4338: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4339: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4340: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4341: 		    $updateflag=1;
                   4342: 		}
1.93      albertel 4343: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4344: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4345: 	    }
1.44      ng       4346: 	}
1.477     albertel 4347: 	$line.="\n";
1.301     albertel 4348: 
                   4349: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4350: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4351: 
1.44      ng       4352: 	if ($updateflag) {
                   4353: 	    $count++;
1.257     albertel 4354: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4355: 				    $udom,$uname);
1.301     albertel 4356: 
                   4357: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4358: 					      $cnum,$udom,$uname)) {
                   4359: 		# need to figure out if should be in queue.
                   4360: 		my %record =  
                   4361: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4362: 					     $udom,$uname);
                   4363: 		my $all_graded = 1;
                   4364: 		my $none_graded = 1;
                   4365: 		foreach my $part (@parts) {
                   4366: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4367: 			$all_graded = 0;
                   4368: 		    } else {
                   4369: 			$none_graded = 0;
                   4370: 		    }
                   4371: 		}
                   4372: 
                   4373: 		if ($all_graded || $none_graded) {
                   4374: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4375: 							   $symb,$cdom,$cnum,
                   4376: 							   $udom,$uname);
                   4377: 		}
                   4378: 	    }
                   4379: 
1.477     albertel 4380: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4381: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4382: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4383: 	    $updateCtr++;
1.93      albertel 4384: 	} else {
1.477     albertel 4385: 	    push(@noupdate,
                   4386: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4387: 	    $noupdateCtr++;
1.44      ng       4388: 	}
1.269     raeburn  4389:         if ($aggregateflag) {
                   4390:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4391: 				  $cdom,$cnum);
1.269     raeburn  4392:         }
1.93      albertel 4393:     }
1.477     albertel 4394:     if (@noupdate) {
1.748     raeburn  4395:         my $numcols=$totcolspan+2;
1.477     albertel 4396: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4397: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4398: 	    &mt('No Changes Occurred For the Students Below').
                   4399: 	    '</td>'.
1.477     albertel 4400: 	    &Apache::loncommon::end_data_table_row();
                   4401: 	foreach my $line (@noupdate) {
                   4402: 	    $result.=
                   4403: 		&Apache::loncommon::start_data_table_row().
                   4404: 		$line.
                   4405: 		&Apache::loncommon::end_data_table_row();
                   4406: 	}
1.44      ng       4407:     }
1.614     www      4408:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4409:     my $msg = '<p><b>'.
                   4410: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4411: 	    $rec_update,$count).'</b><br />'.
                   4412: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4413: 	'</b></p>';
1.44      ng       4414:     return $title.$msg.$result;
1.5       albertel 4415: }
1.54      albertel 4416: 
                   4417: sub split_part_type {
                   4418:     my ($partstr) = @_;
                   4419:     my ($temp,@allparts)=split(/_/,$partstr);
                   4420:     my $type=pop(@allparts);
1.439     albertel 4421:     my $part=join('_',@allparts);
1.54      albertel 4422:     return ($part,$type);
                   4423: }
                   4424: 
1.44      ng       4425: #------------- end of section for handling grading by section/class ---------
                   4426: #
                   4427: #----------------------------------------------------------------------------
                   4428: 
1.5       albertel 4429: 
1.44      ng       4430: #----------------------------------------------------------------------------
                   4431: #
                   4432: #-------------------------- Next few routines handles grading by csv upload
                   4433: #
                   4434: #--- Javascript to handle csv upload
1.27      albertel 4435: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4436:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4437:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4438:   &js_escape(\$error1);
                   4439:   &js_escape(\$error2);
1.27      albertel 4440:   return(<<ENDPICK);
                   4441:   function verify(vf) {
                   4442:     var foundsomething=0;
                   4443:     var founduname=0;
1.243     albertel 4444:     var foundID=0;
1.743     raeburn  4445:     var foundclicker=0;
1.27      albertel 4446:     for (i=0;i<=vf.nfields.value;i++) {
                   4447:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4448:       if (i==0 && tw!=0) { foundID=1; }
                   4449:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4450:       if (i==2 && tw!=0) { foundclicker=1; }
                   4451:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4452:     }
1.743     raeburn  4453:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4454: 	alert('$error1');
                   4455: 	return;
1.27      albertel 4456:     }
                   4457:     if (foundsomething==0) {
1.246     albertel 4458: 	alert('$error2');
                   4459: 	return;
1.27      albertel 4460:     }
                   4461:     vf.submit();
                   4462:   }
                   4463:   function flip(vf,tf) {
                   4464:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4465:     var i;
                   4466:     for (i=0;i<=vf.nfields.value;i++) {
                   4467:       //can not pick the same destination field for both name and domain
                   4468:       if (((i ==0)||(i ==1)) && 
                   4469:           ((tf==0)||(tf==1)) && 
                   4470:           (i!=tf) &&
                   4471:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4472:         eval('vf.f'+i+'.selectedIndex=0;')
                   4473:       }
                   4474:     }
                   4475:   }
                   4476: ENDPICK
                   4477: }
                   4478: 
                   4479: sub csvupload_javascript_forward_associate {
1.743     raeburn  4480:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4481:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4482:   &js_escape(\$error1);
                   4483:   &js_escape(\$error2);
1.27      albertel 4484:   return(<<ENDPICK);
                   4485:   function verify(vf) {
                   4486:     var foundsomething=0;
                   4487:     var founduname=0;
1.243     albertel 4488:     var foundID=0;
1.743     raeburn  4489:     var foundclicker=0;
1.27      albertel 4490:     for (i=0;i<=vf.nfields.value;i++) {
                   4491:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4492:       if (tw==1) { foundID=1; }
                   4493:       if (tw==2) { founduname=1; }
1.745     raeburn  4494:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4495:       if (tw>4) { foundsomething=1; }
1.27      albertel 4496:     }
1.743     raeburn  4497:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4498: 	alert('$error1');
                   4499: 	return;
1.27      albertel 4500:     }
                   4501:     if (foundsomething==0) {
1.246     albertel 4502: 	alert('$error2');
                   4503: 	return;
1.27      albertel 4504:     }
                   4505:     vf.submit();
                   4506:   }
                   4507:   function flip(vf,tf) {
                   4508:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4509:     var i;
                   4510:     //can not pick the same destination field twice
                   4511:     for (i=0;i<=vf.nfields.value;i++) {
                   4512:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4513:         eval('vf.f'+i+'.selectedIndex=0;')
                   4514:       }
                   4515:     }
                   4516:   }
                   4517: ENDPICK
                   4518: }
                   4519: 
1.26      albertel 4520: sub csvuploadmap_header {
1.324     albertel 4521:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4522:     my $javascript;
1.257     albertel 4523:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4524: 	$javascript=&csvupload_javascript_reverse_associate();
                   4525:     } else {
                   4526: 	$javascript=&csvupload_javascript_forward_associate();
                   4527:     }
1.45      ng       4528: 
1.418     albertel 4529:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4530:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4531:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4532:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4533:     my $reverse=&mt("Reverse Association");
1.41      ng       4534:     $request->print(<<ENDPICK);
1.632     www      4535: <br />
                   4536: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4537: <input type="hidden" name="associate"  value="" />
                   4538: <input type="hidden" name="phase"      value="three" />
                   4539: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4540: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4541: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4542: <input type="hidden" name="upfile_associate" 
1.257     albertel 4543:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4544: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4545: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4546: <hr />
                   4547: ENDPICK
1.597     wenzelju 4548:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4549:     return '';
1.26      albertel 4550: 
                   4551: }
                   4552: 
                   4553: sub csvupload_fields {
1.582     raeburn  4554:     my ($symb,$errorref) = @_;
1.745     raeburn  4555:     my $toolsymb;
                   4556:     if ($symb =~ /ext\.tool$/) {
                   4557:         $toolsymb = $symb;
                   4558:     }
1.582     raeburn  4559:     my (@parts) = &getpartlist($symb,$errorref);
                   4560:     if (ref($errorref)) {
                   4561:         if ($$errorref) {
                   4562:             return;
                   4563:         }
                   4564:     }
                   4565: 
1.556     weissno  4566:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4567: 		['username','Student Username'],
1.743     raeburn  4568: 		['clicker','Clicker ID'],
1.243     albertel 4569: 		['domain','Student Domain']);
1.324     albertel 4570:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4571:     foreach my $part (sort(@parts)) {
                   4572: 	my @datum;
1.745     raeburn  4573: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4574: 	my $name=$part;
1.745     raeburn  4575: 	if (!$display) { $display = $name; }
1.41      ng       4576: 	@datum=($name,$display);
1.244     albertel 4577: 	if ($name=~/^stores_(.*)_awarded/) {
                   4578: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4579: 	}
1.41      ng       4580: 	push(@fields,\@datum);
                   4581:     }
                   4582:     return (@fields);
1.26      albertel 4583: }
                   4584: 
                   4585: sub csvuploadmap_footer {
1.41      ng       4586:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4587:     my $buttontext = &mt('Assign Grades');
1.41      ng       4588:     $request->print(<<ENDPICK);
1.26      albertel 4589: </table>
                   4590: <input type="hidden" name="nfields" value="$i" />
                   4591: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4592: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4593: </form>
                   4594: ENDPICK
                   4595: }
                   4596: 
1.283     albertel 4597: sub checkforfile_js {
1.638     www      4598:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4599:     &js_escape(\$alertmsg);
1.597     wenzelju 4600:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4601:     function checkUpload(formname) {
                   4602: 	if (formname.upfile.value == "") {
1.539     riegler  4603: 	    alert("$alertmsg");
1.86      ng       4604: 	    return false;
                   4605: 	}
                   4606: 	formname.submit();
                   4607:     }
                   4608: CSVFORMJS
1.283     albertel 4609:     return $result;
                   4610: }
                   4611: 
                   4612: sub upcsvScores_form {
1.608     www      4613:     my ($request,$symb) = @_;
1.283     albertel 4614:     if (!$symb) {return '';}
                   4615:     my $result=&checkforfile_js();
1.632     www      4616:     $result.=&Apache::loncommon::start_data_table().
                   4617:              &Apache::loncommon::start_data_table_header_row().
                   4618:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4619:              &Apache::loncommon::end_data_table_header_row().
                   4620:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4621:     my $upload=&mt("Upload Scores");
1.86      ng       4622:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4623:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4624:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4625:     $result.=<<ENDUPFORM;
1.106     albertel 4626: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4627: <input type="hidden" name="symb" value="$symb" />
                   4628: <input type="hidden" name="command" value="csvuploadmap" />
                   4629: $upfile_select
1.589     bisitz   4630: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4631: </form>
                   4632: ENDUPFORM
1.370     www      4633:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4634:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4635:              '</td>'.
                   4636:             &Apache::loncommon::end_data_table_row().
                   4637:             &Apache::loncommon::end_data_table();
1.86      ng       4638:     return $result;
                   4639: }
                   4640: 
                   4641: 
1.26      albertel 4642: sub csvuploadmap {
1.608     www      4643:     my ($request,$symb)= @_;
1.41      ng       4644:     if (!$symb) {return '';}
1.72      ng       4645: 
1.41      ng       4646:     my $datatoken;
1.257     albertel 4647:     if (!$env{'form.datatoken'}) {
1.41      ng       4648: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4649:     } else {
1.742     raeburn  4650: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4651:         if ($datatoken ne '') {
                   4652: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4653:         }
1.26      albertel 4654:     }
1.41      ng       4655:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4656:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4657:     my ($i,$keyfields);
                   4658:     if (@records) {
1.582     raeburn  4659:         my $fieldserror;
                   4660: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4661:         if ($fieldserror) {
                   4662:             $request->print(&navmap_errormsg());
                   4663:             return;
                   4664:         }
1.257     albertel 4665: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4666: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4667: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4668: 							  \@fields);
                   4669: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4670: 	    chop($keyfields);
                   4671: 	} else {
                   4672: 	    unshift(@fields,['none','']);
                   4673: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4674: 							    \@fields);
1.311     banghart 4675:             foreach my $rec (@records) {
                   4676:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4677:                 if (%temp) {
                   4678:                     $keyfields=join(',',sort(keys(%temp)));
                   4679:                     last;
                   4680:                 }
                   4681:             }
1.41      ng       4682: 	}
                   4683:     }
                   4684:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4685: 
1.41      ng       4686:     return '';
1.27      albertel 4687: }
                   4688: 
1.246     albertel 4689: sub csvuploadoptions {
1.608     www      4690:     my ($request,$symb)= @_;
1.632     www      4691:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4692:     $request->print(<<ENDPICK);
                   4693: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4694: <input type="hidden" name="command"    value="csvuploadassign" />
                   4695: <p>
                   4696: <label>
                   4697:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4698:    $overwrite
1.246     albertel 4699: </label>
                   4700: </p>
                   4701: ENDPICK
                   4702:     my %fields=&get_fields();
                   4703:     if (!defined($fields{'domain'})) {
1.257     albertel 4704: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4705: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4706:     }
1.257     albertel 4707:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4708: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4709: 	my $cleankey=$1;
                   4710: 	if ($cleankey eq 'command') { next; }
                   4711: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4712: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4713:     }
                   4714:     # FIXME do a check for any duplicated user ids...
                   4715:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4716:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4717: <hr /></form>'."\n");
1.246     albertel 4718:     return '';
                   4719: }
                   4720: 
                   4721: sub get_fields {
                   4722:     my %fields;
1.257     albertel 4723:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4724:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4725: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4726: 	    if ($env{'form.f'.$i} ne 'none') {
                   4727: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4728: 	    }
                   4729: 	} else {
1.257     albertel 4730: 	    if ($env{'form.f'.$i} ne 'none') {
                   4731: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4732: 	    }
                   4733: 	}
1.27      albertel 4734:     }
1.246     albertel 4735:     return %fields;
                   4736: }
                   4737: 
                   4738: sub csvuploadassign {
1.608     www      4739:     my ($request,$symb)= @_;
1.246     albertel 4740:     if (!$symb) {return '';}
1.345     bowersj2 4741:     my $error_msg = '';
1.742     raeburn  4742:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4743:     if ($datatoken ne '') { 
                   4744:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4745:     }
1.246     albertel 4746:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4747:     my %fields=&get_fields();
1.257     albertel 4748:     my $courseid=$env{'request.course.id'};
1.97      albertel 4749:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4750:     my @notallowed;
1.41      ng       4751:     my @skipped;
1.657     raeburn  4752:     my @warnings;
1.41      ng       4753:     my $countdone=0;
                   4754:     foreach my $grade (@gradedata) {
                   4755: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4756: 	my $domain;
                   4757: 	if ($entries{$fields{'domain'}}) {
                   4758: 	    $domain=$entries{$fields{'domain'}};
                   4759: 	} else {
1.257     albertel 4760: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4761: 	}
1.243     albertel 4762: 	$domain=~s/\s//g;
1.41      ng       4763: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4764: 	$username=~s/\s//g;
1.243     albertel 4765: 	if (!$username) {
                   4766: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4767: 	    $id=~s/\s//g;
1.737     raeburn  4768:             if ($id ne '') {
                   4769: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4770: 	        $username=$ids{$id};
                   4771:             } else {
                   4772:                 if ($entries{$fields{'clicker'}}) {
                   4773:                     my $clicker = $entries{$fields{'clicker'}};
                   4774:                     $clicker=~s/\s//g;
                   4775:                     if ($clicker ne '') {
                   4776:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4777:                         if ($clickers{$clicker} ne '') {  
                   4778:                             my $match = 0;
                   4779:                             my @inclass;
                   4780:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4781:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4782:                                     $username = $poss;
                   4783:                                     push(@inclass,$poss);
                   4784:                                     $match ++;
                   4785:                                     
                   4786:                                 }
                   4787:                             }
                   4788:                             if ($match > 1) {
                   4789:                                 undef($username); 
                   4790:                                 $request->print('<p class="LC_warning">'.
                   4791:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4792:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4793:                             }
                   4794:                         }
                   4795:                     }
                   4796:                 }
                   4797:             }
1.243     albertel 4798: 	}
1.41      ng       4799: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4800: 	    my $id=$entries{$fields{'ID'}};
                   4801: 	    $id=~s/\s//g;
1.737     raeburn  4802:             my $clicker = $entries{$fields{'clicker'}};
                   4803:             $clicker=~s/\s//g;
                   4804:             if ($clicker) {
                   4805:                 push(@skipped,"$clicker:$domain");
                   4806: 	    } elsif ($id) {
1.247     albertel 4807: 		push(@skipped,"$id:$domain");
                   4808: 	    } else {
                   4809: 		push(@skipped,"$username:$domain");
                   4810: 	    }
1.41      ng       4811: 	    next;
                   4812: 	}
1.108     albertel 4813: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4814: 	if (!&canmodify($usec)) {
                   4815: 	    push(@notallowed,"$username:$domain");
                   4816: 	    next;
                   4817: 	}
1.244     albertel 4818: 	my %points;
1.41      ng       4819: 	my %grades;
                   4820: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4821: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4822: 		$dest eq 'domain') { next; }
                   4823: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4824: 	    if ($dest=~/stores_(.*)_points/) {
                   4825: 		my $part=$1;
                   4826: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4827: 					      $symb,$domain,$username);
1.345     bowersj2 4828:                 if ($wgt) {
                   4829:                     $entries{$fields{$dest}}=~s/\s//g;
                   4830:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4831:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4832:                                           : 'correct_by_override';
1.638     www      4833:                     if ($pcr>1) {
1.657     raeburn  4834:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4835:                     }
1.345     bowersj2 4836:                     $grades{"resource.$part.awarded"}=$pcr;
                   4837:                     $grades{"resource.$part.solved"}=$award;
                   4838:                     $points{$part}=1;
                   4839:                 } else {
                   4840:                     $error_msg = "<br />" .
                   4841:                         &mt("Some point values were assigned"
                   4842:                             ." for problems with a weight "
                   4843:                             ."of zero. These values were "
                   4844:                             ."ignored.");
                   4845:                 }
1.244     albertel 4846: 	    } else {
                   4847: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4848: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4849: 		my $store_key=$dest;
                   4850: 		$store_key=~s/^stores/resource/;
                   4851: 		$store_key=~s/_/\./g;
                   4852: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4853: 	    }
1.41      ng       4854: 	}
1.508     www      4855: 	if (! %grades) { 
                   4856:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4857:         } else {
                   4858: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4859: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4860: 					   $env{'request.course.id'},
                   4861: 					   $domain,$username);
1.508     www      4862: 	   if ($result eq 'ok') {
1.627     www      4863: # Successfully stored
1.508     www      4864: 	      $request->print('.');
1.627     www      4865: # Remove from grading queue
                   4866:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4867:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4868:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4869:                                              $domain,$username);
                   4870:               $countdone++;
                   4871:            } else {
1.508     www      4872: 	      $request->print("<p><span class=\"LC_error\">".
                   4873:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4874:                                   "$username:$domain",$result)."</span></p>");
                   4875: 	   }
                   4876: 	   $request->rflush();
                   4877:         }
1.41      ng       4878:     }
1.570     www      4879:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4880:     if (@warnings) {
                   4881:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4882:         $request->print(join(', ',@warnings));
                   4883:     }
1.41      ng       4884:     if (@skipped) {
1.571     www      4885: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4886:         $request->print(join(', ',@skipped));
1.106     albertel 4887:     }
                   4888:     if (@notallowed) {
1.571     www      4889: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4890: 	$request->print(join(', ',@notallowed));
1.41      ng       4891:     }
1.106     albertel 4892:     $request->print("<br />\n");
1.345     bowersj2 4893:     return $error_msg;
1.26      albertel 4894: }
1.44      ng       4895: #------------- end of section for handling csv file upload ---------
                   4896: #
                   4897: #-------------------------------------------------------------------
                   4898: #
1.122     ng       4899: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4900: #
                   4901: #--- Select a page/sequence and a student to grade
1.68      ng       4902: sub pickStudentPage {
1.608     www      4903:     my ($request,$symb) = @_;
1.68      ng       4904: 
1.539     riegler  4905:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4906:     &js_escape(\$alertmsg);
1.597     wenzelju 4907:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4908: 
                   4909: function checkPickOne(formname) {
1.76      ng       4910:     if (radioSelection(formname.student) == null) {
1.539     riegler  4911: 	alert("$alertmsg");
1.68      ng       4912: 	return;
                   4913:     }
1.125     ng       4914:     ptr = pullDownSelection(formname.selectpage);
                   4915:     formname.page.value = formname["page"+ptr].value;
                   4916:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4917:     formname.submit();
                   4918: }
                   4919: 
                   4920: LISTJAVASCRIPT
1.118     ng       4921:     &commonJSfunctions($request);
1.608     www      4922: 
1.257     albertel 4923:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4924:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4925:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4926: 
1.398     albertel 4927:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4928: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4929: 
1.80      ng       4930:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4931:     my $map_error;
                   4932:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4933:     if ($map_error) {
                   4934:         $request->print(&navmap_errormsg());
                   4935:         return; 
                   4936:     }
1.137     albertel 4937:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4938: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4939: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4940: 
                   4941:     # Collection of hidden fields
1.70      ng       4942:     my $ctr=0;
1.68      ng       4943:     foreach (@$titles) {
1.700     bisitz   4944:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4945:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4946:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4947:         $ctr++;
1.68      ng       4948:     }
1.700     bisitz   4949:     $result.='<input type="hidden" name="page" />'."\n".
                   4950:         '<input type="hidden" name="title" />'."\n";
                   4951: 
                   4952:     $result.=&build_section_inputs();
                   4953:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4954:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4955: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4956: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4957: 
1.700     bisitz   4958:     # Show grading options
                   4959:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4960:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4961:     $ctr=0;
                   4962:     foreach (@$titles) {
                   4963: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4964: 	$select.='<option value="'.$ctr.'"'.
                   4965: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4966: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4967: 	$ctr++;
                   4968:     }
1.700     bisitz   4969:     $select.= '</select>';
1.68      ng       4970: 
1.700     bisitz   4971:     $result.=
                   4972:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4973:        .$select
                   4974:        .&Apache::lonhtmlcommon::row_closure();
                   4975: 
                   4976:     $result.=
                   4977:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4978:        .'<label><input type="radio" name="vProb" value="no"'
                   4979:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4980:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4981:            .&mt('yes').'</label>'."\n"
                   4982:        .&Apache::lonhtmlcommon::row_closure();
                   4983: 
                   4984:     $result.=
                   4985:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4986:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4987:            .&mt('none').' </label>'."\n"
                   4988:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4989:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4990:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4991:            .&mt('all submissions with details').' </label>'
                   4992:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4993:     
1.700     bisitz   4994:     $result.=
                   4995:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4996:        .'<input type="text" name="CODE" value="" />'
                   4997:        .&Apache::lonhtmlcommon::row_closure(1)
                   4998:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4999: 
1.700     bisitz   5000:     # Show list of students to select for grading
                   5001:     $result.='<br /><input type="button" '.
1.589     bisitz   5002:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5003: 
1.68      ng       5004:     $request->print($result);
                   5005: 
1.485     albertel 5006:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5007: 	&Apache::loncommon::start_data_table().
                   5008: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5009: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5010: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5011: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5012: 	'<th>'.&nameUserString('header').'</th>'.
                   5013: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5014:  
1.76      ng       5015:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       5016:     my $ptr = 1;
1.294     albertel 5017:     foreach my $student (sort 
                   5018: 			 {
                   5019: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5020: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5021: 			     }
                   5022: 			     return $a cmp $b;
                   5023: 			 } (keys(%$fullname))) {
1.68      ng       5024: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5025: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5026:                                   : '</td>');
1.126     ng       5027: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5028: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5029: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5030: 	$studentTable.=
                   5031: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5032:                          : '');
1.68      ng       5033: 	$ptr++;
                   5034:     }
1.484     albertel 5035:     if ($ptr%2 == 0) {
                   5036: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5037: 	    &Apache::loncommon::end_data_table_row();
                   5038:     }
                   5039:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5040:     $studentTable.='<input type="button" '.
1.589     bisitz   5041:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5042: 
                   5043:     $request->print($studentTable);
                   5044: 
                   5045:     return '';
                   5046: }
                   5047: 
                   5048: sub getSymbMap {
1.582     raeburn  5049:     my ($map_error) = @_;
1.132     bowersj2 5050:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5051:     unless (ref($navmap)) {
                   5052:         if (ref($map_error)) {
                   5053:             $$map_error = 'navmap';
                   5054:         }
                   5055:         return;
                   5056:     }
1.68      ng       5057:     my %symbx = ();
                   5058:     my @titles = ();
1.117     bowersj2 5059:     my $minder = 0;
                   5060: 
                   5061:     # Gather every sequence that has problems.
1.240     albertel 5062:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5063: 					       1,0,1);
1.117     bowersj2 5064:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5065: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5066: 	    my $title = $minder.'.'.
                   5067: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5068: 	    push(@titles, $title); # minder in case two titles are identical
                   5069: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5070: 	    $minder++;
1.241     albertel 5071: 	}
1.68      ng       5072:     }
                   5073:     return \@titles,\%symbx;
                   5074: }
                   5075: 
1.72      ng       5076: #
                   5077: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5078: sub displayPage {
1.608     www      5079:     my ($request,$symb) = @_;
1.257     albertel 5080:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5081:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5082:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5083:     my $pageTitle = $env{'form.page'};
1.103     albertel 5084:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5085:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5086:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5087: 
                   5088:     #need to make sure we have the correct data for later EXT calls, 
                   5089:     #thus invalidate the cache
                   5090:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5091:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5092:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5093:     &Apache::lonnet::clear_EXT_cache_status();
                   5094: 
1.103     albertel 5095:     if (!&canview($usec)) {
1.712     bisitz   5096:         $request->print(
                   5097:             '<span class="LC_warning">'.
                   5098:             &mt('Unable to view requested student. ([_1])',
                   5099:                     $env{'form.student'}).
                   5100:             '</span>');
                   5101:         return;
1.103     albertel 5102:     }
1.398     albertel 5103:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5104:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5105: 	'</h3>'."\n";
1.500     albertel 5106:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5107:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5108: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5109:     } else {
                   5110: 	delete($env{'form.CODE'});
                   5111:     }
1.71      ng       5112:     &sub_page_js($request);
                   5113:     $request->print($result);
                   5114: 
1.132     bowersj2 5115:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5116:     unless (ref($navmap)) {
                   5117:         $request->print(&navmap_errormsg());
                   5118:         return;
                   5119:     }
1.257     albertel 5120:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5121:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5122:     if (!$map) {
1.485     albertel 5123: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5124: 	return; 
                   5125:     }
1.68      ng       5126:     my $iterator = $navmap->getIterator($map->map_start(),
                   5127: 					$map->map_finish());
                   5128: 
1.71      ng       5129:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5130: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5131: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5132: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5133: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5134: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5135: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5136: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5137: 
1.382     albertel 5138:     if (defined($env{'form.CODE'})) {
                   5139: 	$studentTable.=
                   5140: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5141:     }
1.381     albertel 5142:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5143: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5144: 
1.594     bisitz   5145:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5146:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5147:         '</span>'."\n".
1.484     albertel 5148: 	&Apache::loncommon::start_data_table().
                   5149: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5150: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5151: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5152: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5153: 
1.329     albertel 5154:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5155:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5156:     $iterator->next(); # skip the first BEGIN_MAP
                   5157:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5158:     while ($depth > 0) {
1.68      ng       5159:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5160:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5161: 
1.745     raeburn  5162:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5163: 	    my $parts = $curRes->parts();
1.68      ng       5164:             my $title = $curRes->compTitle();
1.71      ng       5165: 	    my $symbx = $curRes->symb();
1.746     raeburn  5166:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5167: 	    $studentTable.=
                   5168: 		&Apache::loncommon::start_data_table_row().
                   5169: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5170: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5171: 		                        : '<br />('.&mt('[_1]parts',
                   5172: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5173: 		 ).
                   5174: 		 '</td>';
1.71      ng       5175: 	    $studentTable.='<td valign="top">';
1.382     albertel 5176: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5177:             if ($is_tool) {
                   5178:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5179:             } else {
1.745     raeburn  5180: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5181: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5182: 					         undef,'both',\%form);
                   5183: 	        } else {
                   5184: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5185: 		    $companswer =~ s|<form(.*?)>||g;
                   5186: 		    $companswer =~ s|</form>||g;
                   5187: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5188: #		        $companswer =~ s/$1/ /ms;
                   5189: #		        $request->print('match='.$1."<br />\n");
                   5190: #		    }
                   5191: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5192: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5193: 		}
1.71      ng       5194: 	    }
                   5195: 
1.257     albertel 5196: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5197: 
1.257     albertel 5198: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5199: 		if ($record{'version'} eq '') {
1.745     raeburn  5200:                     my $msg = &mt('No recorded submission for this problem.');
                   5201:                     if ($is_tool) {
                   5202:                         $msg = &mt('No recorded transactions for this external tool');
                   5203:                     }
                   5204: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5205: 		} else {
1.116     ng       5206: 		    my %responseType = ();
                   5207: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5208: 			my @responseIds =$curRes->responseIds($partid);
                   5209: 			my @responseType =$curRes->responseType($partid);
                   5210: 			my %responseIds;
                   5211: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5212: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5213: 			}
                   5214: 			$responseType{$partid} = \%responseIds;
1.116     ng       5215: 		    }
1.148     albertel 5216: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5217: 		}
1.257     albertel 5218: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5219: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5220:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5221: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5222: 									$env{'request.course.id'},
1.726     raeburn  5223: 									'','.submission',undef,
                   5224:                                                                         $usec,$identifier);
1.71      ng       5225:  
                   5226: 	    }
1.103     albertel 5227: 	    if (&canmodify($usec)) {
1.585     bisitz   5228:             $studentTable.=&gradeBox_start();
1.103     albertel 5229: 		foreach my $partid (@{$parts}) {
                   5230: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5231: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5232: 		    $question++;
                   5233: 		}
1.585     bisitz   5234:             $studentTable.=&gradeBox_end();
1.196     albertel 5235: 		$prob++;
1.71      ng       5236: 	    }
                   5237: 	    $studentTable.='</td></tr>';
1.68      ng       5238: 
1.103     albertel 5239: 	}
1.68      ng       5240:         $curRes = $iterator->next();
                   5241:     }
                   5242: 
1.589     bisitz   5243:     $studentTable.=
                   5244:         '</table>'."\n".
                   5245:         '<input type="button" value="'.&mt('Save').'" '.
                   5246:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5247:         '</form>'."\n";
1.71      ng       5248:     $request->print($studentTable);
                   5249: 
                   5250:     return '';
1.119     ng       5251: }
                   5252: 
                   5253: sub displaySubByDates {
1.148     albertel 5254:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5255:     my $isCODE=0;
1.335     albertel 5256:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5257:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5258:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5259:     my $studentTable=&Apache::loncommon::start_data_table().
                   5260: 	&Apache::loncommon::start_data_table_header_row().
                   5261: 	'<th>'.&mt('Date/Time').'</th>'.
                   5262: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5263:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5264: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5265: 	'<th>'.&mt('Status').'</th>'.
                   5266: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5267:     my ($version);
                   5268:     my %mark;
1.148     albertel 5269:     my %orders;
1.119     ng       5270:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5271:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5272:         if ($is_tool) {
                   5273:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5274:         } else {
                   5275:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5276:         }
1.147     albertel 5277:     }
1.335     albertel 5278: 
                   5279:     my $interaction;
1.525     raeburn  5280:     my $no_increment = 1;
1.735     raeburn  5281:     my (%lastrndseed,%lasttype);
1.119     ng       5282:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5283: 	my $timestamp = 
                   5284: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5285: 	if (exists($$record{$version.':resource.0.version'})) {
                   5286: 	    $interaction = $$record{$version.':resource.0.version'};
                   5287: 	}
1.671     raeburn  5288:         if ($isTask && $env{'form.previousversion'}) {
                   5289:             next unless ($interaction == $env{'form.previousversion'});
                   5290:         }
1.335     albertel 5291: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5292: 		             : "$version:resource");
1.467     albertel 5293: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5294: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5295: 	if ($isCODE) {
                   5296: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5297: 	}
1.671     raeburn  5298:         if ($isTask) {
                   5299:             $studentTable.='<td>'.$interaction.'</td>';
                   5300:         }
1.119     ng       5301: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5302: 	my @displaySub = ();
                   5303: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5304:             my ($hidden,$type);
                   5305:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5306:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5307:                 $hidden = 1;
                   5308:             }
1.749     raeburn  5309:             my @matchKey;
                   5310:             if ($isTask) {
                   5311:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
                   5312:             } elsif ($is_tool) {
                   5313:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
                   5314:             } else {
                   5315:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
                   5316:             }
1.122     ng       5317: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5318: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5319: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5320: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5321: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5322:                     if ($is_tool) {
                   5323:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5324:                     } else {
1.749     raeburn  5325: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5326: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5327:                         $displaySub[0].='<span class="LC_nobreak">';
                   5328:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5329:                                        .' <span class="LC_internal_info">'
                   5330:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5331:                                        .'</span>'
                   5332:                                        .' <b>';
                   5333:                         if ($hidden) {
                   5334:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5335:                         } else {
                   5336:                             my ($trial,$rndseed,$newvariation);
                   5337:                             if ($type eq 'randomizetry') {
                   5338:                                 $trial = $$record{"$where.$partid.tries"};
                   5339:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5340:                             }
                   5341: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5342: 			        $displaySub[0].=&mt('Trial not counted');
                   5343: 		            } else {
                   5344: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5345: 					        $$record{"$where.$partid.tries"});
                   5346:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5347:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5348:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5349:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5350:                                     }
1.640     raeburn  5351:                                 }
1.749     raeburn  5352:                                 $lastrndseed{$partid} = $rndseed;
                   5353:                                 $lasttype{$partid} = $type;
                   5354: 		            }
                   5355: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5356:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5357: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5358: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5359: 			        $orders{$partid}->{$responseId}=
                   5360: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5361:                                                $no_increment,$type,$trial,$rndseed);
                   5362: 		            }
                   5363: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5364: 		            $displaySub[0].='&nbsp; '.
                   5365: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5366:                         }
1.596     raeburn  5367:                     }
1.147     albertel 5368: 		}
                   5369: 	    }
1.335     albertel 5370: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5371: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5372: 				    $$record{"$where.$partid.checkedin"},
                   5373: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5374: 					'<br />';
1.335     albertel 5375: 	    }
                   5376: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5377: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5378: 		    lc($$record{"$where.$partid.award"}).' '.
                   5379: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5380: 		    '<br />';
1.749     raeburn  5381: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5382: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5383: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5384: 		}
1.147     albertel 5385: 	    }
1.335     albertel 5386: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5387: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5388: 		unless ($is_tool) {
                   5389: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5390: 		}
1.335     albertel 5391: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5392: 		$displaySub[2].=
1.749     raeburn  5393: 		    $$record{"$version:resource.$partid.regrader"};
                   5394:                 unless ($is_tool) {
                   5395: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5396:                 }
1.147     albertel 5397: 	    }
                   5398: 	}
                   5399: 	# needed because old essay regrader has not parts info
                   5400: 	if (exists $$record{"$version:resource.regrader"}) {
                   5401: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5402: 	}
                   5403: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5404: 	if ($displaySub[2]) {
1.467     albertel 5405: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5406: 	}
1.467     albertel 5407: 	$studentTable.='&nbsp;</td>'.
                   5408: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5409:     }
1.467     albertel 5410:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5411:     return $studentTable;
1.71      ng       5412: }
                   5413: 
                   5414: sub updateGradeByPage {
1.608     www      5415:     my ($request,$symb) = @_;
1.71      ng       5416: 
1.257     albertel 5417:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5418:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5419:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5420:     my $pageTitle = $env{'form.page'};
1.103     albertel 5421:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5422:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5423:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5424:     if (!&canmodify($usec)) {
1.526     raeburn  5425: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5426: 	return;
                   5427:     }
1.398     albertel 5428:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5429:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5430: 	'</h3>'."\n";
1.70      ng       5431: 
1.68      ng       5432:     $request->print($result);
                   5433: 
1.582     raeburn  5434: 
1.132     bowersj2 5435:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5436:     unless (ref($navmap)) {
                   5437:         $request->print(&navmap_errormsg());
                   5438:         return;
                   5439:     }
1.257     albertel 5440:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5441:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5442:     if (!$map) {
1.527     raeburn  5443: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5444: 	return; 
                   5445:     }
1.71      ng       5446:     my $iterator = $navmap->getIterator($map->map_start(),
                   5447: 					$map->map_finish());
1.70      ng       5448: 
1.484     albertel 5449:     my $studentTable=
                   5450: 	&Apache::loncommon::start_data_table().
                   5451: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5452: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5453: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5454: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5455: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5456: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5457: 
                   5458:     $iterator->next(); # skip the first BEGIN_MAP
                   5459:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5460:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5461:     while ($depth > 0) {
1.71      ng       5462:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5463:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5464: 
1.385     albertel 5465:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5466: 	    my $parts = $curRes->parts();
1.71      ng       5467:             my $title = $curRes->compTitle();
                   5468: 	    my $symbx = $curRes->symb();
1.484     albertel 5469: 	    $studentTable.=
                   5470: 		&Apache::loncommon::start_data_table_row().
                   5471: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5472: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5473:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5474: 		.')').'</td>';
1.71      ng       5475: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5476: 
                   5477: 	    my %newrecord=();
                   5478: 	    my @displayPts=();
1.269     raeburn  5479:             my %aggregate = ();
                   5480:             my $aggregateflag = 0;
1.726     raeburn  5481:             if ($env{'form.HIDE'.$prob}) {
                   5482:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5483:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5484:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5485:                 $hideflag += $numchgs;
                   5486:             }
1.71      ng       5487: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5488: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5489: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5490: 
1.257     albertel 5491: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5492: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5493: 		my $partial = $newpts/$wgt;
                   5494: 		my $score;
                   5495: 		if ($partial > 0) {
                   5496: 		    $score = 'correct_by_override';
1.125     ng       5497: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5498: 		    $score = 'incorrect_by_override';
                   5499: 		}
1.257     albertel 5500: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5501: 		if ($dropMenu eq 'excused') {
1.71      ng       5502: 		    $partial = '';
                   5503: 		    $score = 'excused';
1.125     ng       5504: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5505: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5506: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5507: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5508: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5509: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5510: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5511: 		    $changeflag++;
                   5512: 		    $newpts = '';
1.269     raeburn  5513:                     
                   5514:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5515:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5516:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5517:                     if ($aggtries > 0) {
                   5518:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5519:                         $aggregateflag = 1;
                   5520:                     }
1.71      ng       5521: 		}
1.324     albertel 5522: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5523: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5524: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5525: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5526: 		    '&nbsp;<br />';
1.526     raeburn  5527: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5528: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5529: 		    '&nbsp;<br />';
1.71      ng       5530: 		$question++;
1.380     albertel 5531: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5532: 
1.71      ng       5533: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5534: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5535: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5536: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5537: 
                   5538: 		$changeflag++;
                   5539: 	    }
                   5540: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5541: 		my %record = 
                   5542: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5543: 					     $udom,$uname);
                   5544: 
                   5545: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5546: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5547: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5548: 		    $newrecord{'resource.CODE'} = '';
                   5549: 		}
1.257     albertel 5550: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5551: 					$udom,$uname);
1.382     albertel 5552: 		%record = &Apache::lonnet::restore($symbx,
                   5553: 						   $env{'request.course.id'},
                   5554: 						   $udom,$uname);
1.380     albertel 5555: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5556: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5557: 	    }
1.380     albertel 5558: 	    
1.269     raeburn  5559:             if ($aggregateflag) {
                   5560:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5561:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5562:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5563:             }
1.125     ng       5564: 
1.71      ng       5565: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5566: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5567: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5568: 
1.196     albertel 5569: 	    $prob++;
1.68      ng       5570: 	}
1.71      ng       5571:         $curRes = $iterator->next();
1.68      ng       5572:     }
1.98      albertel 5573: 
1.484     albertel 5574:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5575:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5576: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5577: 		  $changeflag).'<br />');
                   5578:     my $hidemsg=($hideflag == 0 ? '' :
                   5579:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5580:                      $hideflag).'<br />');
                   5581:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5582: 
1.70      ng       5583:     return '';
                   5584: }
                   5585: 
1.72      ng       5586: #-------- end of section for handling grading by page/sequence ---------
                   5587: #
                   5588: #-------------------------------------------------------------------
                   5589: 
1.581     www      5590: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5591: #
                   5592: #------ start of section for handling grading by page/sequence ---------
                   5593: 
1.423     albertel 5594: =pod
                   5595: 
                   5596: =head1 Bubble sheet grading routines
                   5597: 
1.424     albertel 5598:   For this documentation:
                   5599: 
                   5600:    'scanline' refers to the full line of characters
                   5601:    from the file that we are parsing that represents one entire sheet
                   5602: 
                   5603:    'bubble line' refers to the data
1.659     raeburn  5604:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5605: 
                   5606: 
1.659     raeburn  5607: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5608: into a course. When a user wants to grade, they select a
1.659     raeburn  5609: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5610: one of the predefined configurations for what each scanline looks
                   5611: like.
                   5612: 
                   5613: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5614: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5615: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5616: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5617: invalid student/employee ID
1.424     albertel 5618: 
                   5619: If the CODE option is used that determines the randomization of the
1.556     weissno  5620: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5621: username:domain.
                   5622: 
                   5623: During the validation phase the instructor can choose to skip scanlines. 
                   5624: 
1.659     raeburn  5625: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5626: 
                   5627:   scantron_original_filename (unmodified original file)
                   5628:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5629:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5630: 
                   5631: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5632: correction information that isn't representable in the bubblesheet
1.424     albertel 5633: file (see &scantron_getfile() for more information)
                   5634: 
                   5635: After all scanlines are either valid, marked as valid or skipped, then
                   5636: foreach line foreach problem in the picked sequence, an ssi request is
                   5637: made that simulates a user submitting their selected letter(s) against
                   5638: the homework problem.
1.423     albertel 5639: 
                   5640: =over 4
                   5641: 
                   5642: 
                   5643: 
                   5644: =item defaultFormData
                   5645: 
                   5646:   Returns html hidden inputs used to hold context/default values.
                   5647: 
                   5648:  Arguments:
                   5649:   $symb - $symb of the current resource 
                   5650: 
                   5651: =cut
1.422     foxr     5652: 
1.81      albertel 5653: sub defaultFormData {
1.324     albertel 5654:     my ($symb)=@_;
1.613     www      5655:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5656: }
                   5657: 
1.447     foxr     5658: 
1.423     albertel 5659: =pod 
                   5660: 
                   5661: =item getSequenceDropDown
                   5662: 
                   5663:    Return html dropdown of possible sequences to grade
                   5664:  
                   5665:  Arguments:
1.582     raeburn  5666:    $symb - $symb of the current resource
                   5667:    $map_error - ref to scalar which will container error if
                   5668:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5669: 
                   5670: =cut
1.422     foxr     5671: 
1.75      albertel 5672: sub getSequenceDropDown {
1.582     raeburn  5673:     my ($symb,$map_error)=@_;
1.75      albertel 5674:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5675:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5676:     if (ref($map_error)) {
                   5677:         return if ($$map_error);
                   5678:     }
1.137     albertel 5679:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5680:     my $ctr=0;
                   5681:     foreach (@$titles) {
                   5682: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5683: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5684: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5685: 	    '>'.$showtitle.'</option>'."\n";
                   5686: 	$ctr++;
                   5687:     }
                   5688:     $result.= '</select>';
                   5689:     return $result;
                   5690: }
                   5691: 
1.495     albertel 5692: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5693:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5694: 
                   5695: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5696: 
1.509     raeburn  5697: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5698:                                    # matchresponse or rankresponse, where 
                   5699:                                    # an individual response can have multiple 
                   5700:                                    # lines
1.503     raeburn  5701: 
                   5702: my %responsetype_per_response;     # responsetype for each response
                   5703: 
1.691     raeburn  5704: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5705:                                    # numbered response. Needed when randomorder
                   5706:                                    # or randompick are in use. Key is ID, value 
                   5707:                                    # is response number.
                   5708: 
1.495     albertel 5709: # Save and restore the bubble lines array to the form env.
                   5710: 
                   5711: 
                   5712: sub save_bubble_lines {
                   5713:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5714: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5715: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5716: 	    $first_bubble_line{$line};
1.503     raeburn  5717:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5718:             $subdivided_bubble_lines{$line};
                   5719:         $env{"form.scantron.responsetype.$line"} =
                   5720:             $responsetype_per_response{$line};
1.495     albertel 5721:     }
1.691     raeburn  5722:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5723:         my $line = $masterseq_id_responsenum{$resid};
                   5724:         $env{"form.scantron.residpart.$line"} = $resid;
                   5725:     }
1.495     albertel 5726: }
                   5727: 
                   5728: 
                   5729: sub restore_bubble_lines {
                   5730:     my $line = 0;
                   5731:     %bubble_lines_per_response = ();
1.691     raeburn  5732:     %masterseq_id_responsenum = ();
1.495     albertel 5733:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5734: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5735: 	$bubble_lines_per_response{$line} = $value;
                   5736: 	$first_bubble_line{$line}  =
                   5737: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5738:         $subdivided_bubble_lines{$line} =
                   5739:             $env{"form.scantron.sub_bubblelines.$line"};
                   5740:         $responsetype_per_response{$line} =
                   5741:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5742:         my $id = $env{"form.scantron.residpart.$line"};
                   5743:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5744: 	$line++;
                   5745:     }
                   5746: }
                   5747: 
1.423     albertel 5748: =pod 
                   5749: 
                   5750: =item scantron_filenames
                   5751: 
                   5752:    Returns a list of the scantron files in the current course 
                   5753: 
                   5754: =cut
1.422     foxr     5755: 
1.202     albertel 5756: sub scantron_filenames {
1.257     albertel 5757:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5758:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5759:     my $getpropath = 1;
1.662     raeburn  5760:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5761:                                                         $cname,$getpropath);
1.202     albertel 5762:     my @possiblenames;
1.662     raeburn  5763:     if (ref($dirlist) eq 'ARRAY') {
                   5764:         foreach my $filename (sort(@{$dirlist})) {
                   5765: 	    ($filename)=split(/&/,$filename);
                   5766: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5767: 	    $filename=~s/^scantron_orig_//;
                   5768: 	    push(@possiblenames,$filename);
                   5769:         }
1.202     albertel 5770:     }
                   5771:     return @possiblenames;
                   5772: }
                   5773: 
1.423     albertel 5774: =pod 
                   5775: 
                   5776: =item scantron_uploads
                   5777: 
                   5778:    Returns  html drop-down list of scantron files in current course.
                   5779: 
                   5780:  Arguments:
                   5781:    $file2grade - filename to set as selected in the dropdown
                   5782: 
                   5783: =cut
1.422     foxr     5784: 
1.202     albertel 5785: sub scantron_uploads {
1.209     ng       5786:     my ($file2grade) = @_;
1.202     albertel 5787:     my $result=	'<select name="scantron_selectfile">';
                   5788:     $result.="<option></option>";
                   5789:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5790: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5791:     }
                   5792:     $result.="</select>";
                   5793:     return $result;
                   5794: }
                   5795: 
1.423     albertel 5796: =pod 
                   5797: 
                   5798: =item scantron_scantab
                   5799: 
                   5800:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5801:   file.
                   5802: 
                   5803: =cut
1.422     foxr     5804: 
1.82      albertel 5805: sub scantron_scantab {
                   5806:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5807:     $result.='<option></option>'."\n";
1.754     raeburn  5808:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5809:     if (@lines > 0) {
                   5810:         foreach my $line (@lines) {
                   5811:             next if (($line =~ /^\#/) || ($line eq ''));
                   5812: 	    my ($name,$descrip)=split(/:/,$line);
                   5813: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5814:         }
1.82      albertel 5815:     }
                   5816:     $result.='</select>'."\n";
1.518     raeburn  5817:     return $result;
                   5818: }
                   5819: 
1.423     albertel 5820: =pod 
                   5821: 
                   5822: =item scantron_CODElist
                   5823: 
                   5824:   Returns html drop down of the saved CODE lists from current course,
                   5825:   generated from earlier printings.
                   5826: 
                   5827: =cut
1.422     foxr     5828: 
1.186     albertel 5829: sub scantron_CODElist {
1.257     albertel 5830:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5831:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5832:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5833:     my $namechoice='<option></option>';
1.225     albertel 5834:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5835: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5836: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5837: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5838:     }
                   5839:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5840:     return $namechoice;
                   5841: }
                   5842: 
1.423     albertel 5843: =pod 
                   5844: 
                   5845: =item scantron_CODEunique
                   5846: 
                   5847:   Returns the html for "Each CODE to be used once" radio.
                   5848: 
                   5849: =cut
1.422     foxr     5850: 
1.186     albertel 5851: sub scantron_CODEunique {
1.532     bisitz   5852:     my $result='<span class="LC_nobreak">
1.272     albertel 5853:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5854:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5855:                 </span>
1.532     bisitz   5856:                 <span class="LC_nobreak">
1.272     albertel 5857:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5858:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5859:                 </span>';
1.186     albertel 5860:     return $result;
                   5861: }
1.423     albertel 5862: 
                   5863: =pod 
                   5864: 
                   5865: =item scantron_selectphase
                   5866: 
1.659     raeburn  5867:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5868:   Allows for - starting a grading run.
1.424     albertel 5869:              - downloading existing scan data (original, corrected
1.423     albertel 5870:                                                 or skipped info)
                   5871: 
                   5872:              - uploading new scan data
                   5873: 
                   5874:  Arguments:
                   5875:   $r          - The Apache request object
                   5876:   $file2grade - name of the file that contain the scanned data to score
                   5877: 
                   5878: =cut
1.186     albertel 5879: 
1.75      albertel 5880: sub scantron_selectphase {
1.608     www      5881:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5882:     if (!$symb) {return '';}
1.582     raeburn  5883:     my $map_error;
                   5884:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5885:     if ($map_error) {
                   5886:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5887:         return;
                   5888:     }
1.324     albertel 5889:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5890:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5891:     my $format_selector=&scantron_scantab();
1.186     albertel 5892:     my $CODE_selector=&scantron_CODElist();
                   5893:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5894:     my $result;
1.422     foxr     5895: 
1.513     foxr     5896:     $ssi_error = 0;
                   5897: 
1.606     wenzelju 5898:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5899:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5900: 
                   5901: 	# Chunk of form to prompt for a scantron file upload.
                   5902: 
                   5903:         $r->print('
1.754     raeburn  5904:     <br />');
1.608     www      5905:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5906:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5907:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5908:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5909:     &js_escape(\$alertmsg);
1.754     raeburn  5910:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 5911:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5912:     function checkUpload(formname) {
                   5913: 	if (formname.upfile.value == "") {
1.736     damieng  5914: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5915: 	    return false;
                   5916: 	}
                   5917: 	formname.submit();
1.756   ! raeburn  5918:     }'."\n".$formatjs));
1.606     wenzelju 5919:     $r->print('
                   5920:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5921:                 '.$default_form_data.'
                   5922:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5923:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5924:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  5925:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5926:               '.&Apache::loncommon::start_data_table_header_row().'
                   5927:                 <th>
                   5928:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5929:                 </th>
                   5930:               '.&Apache::loncommon::end_data_table_header_row().'
                   5931:               '.&Apache::loncommon::start_data_table_row().'
                   5932:             <td>
                   5933:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   5934:     if ($formatoptions) {
                   5935:         $r->print('</td>
                   5936:                  '.&Apache::loncommon::end_data_table_row().'
                   5937:                  '.&Apache::loncommon::start_data_table_row().'
                   5938:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   5939:                  </td>
                   5940:                  '.&Apache::loncommon::end_data_table_row().'
                   5941:                  '.&Apache::loncommon::start_data_table_row().'
                   5942:                  <td>'
                   5943:         );
                   5944:     } else {
                   5945:         $r->print(' <br />');
                   5946:     }
                   5947:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5948:               </td>
                   5949:              '.&Apache::loncommon::end_data_table_row().'
                   5950:              '.&Apache::loncommon::end_data_table().'
                   5951:              </form>'
                   5952:     );
1.606     wenzelju 5953: 
                   5954:     }
                   5955: 
1.422     foxr     5956:     # Chunk of form to prompt for a file to grade and how:
                   5957: 
1.489     albertel 5958:     $result.= '
                   5959:     <br />
                   5960:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5961:     <input type="hidden" name="command" value="scantron_warning" />
                   5962:     '.$default_form_data.'
                   5963:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5964:        '.&Apache::loncommon::start_data_table_header_row().'
                   5965:             <th colspan="2">
1.492     albertel 5966:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5967:             </th>
                   5968:        '.&Apache::loncommon::end_data_table_header_row().'
                   5969:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5970:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5971:        '.&Apache::loncommon::end_data_table_row().'
                   5972:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5973:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5974:        '.&Apache::loncommon::end_data_table_row().'
                   5975:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5976:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5977:        '.&Apache::loncommon::end_data_table_row().'
                   5978:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5979:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5980:        '.&Apache::loncommon::end_data_table_row().'
                   5981:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5982:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5983:        '.&Apache::loncommon::end_data_table_row().'
                   5984:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5985: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5986:             <td>
1.492     albertel 5987: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5988:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5989:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5990: 	    </td>
1.489     albertel 5991:        '.&Apache::loncommon::end_data_table_row().'
                   5992:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5993:             <td colspan="2">
1.572     www      5994:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5995:             </td>
1.489     albertel 5996:        '.&Apache::loncommon::end_data_table_row().'
                   5997:     '.&Apache::loncommon::end_data_table().'
                   5998:     </form>
                   5999: ';
1.162     albertel 6000:    
                   6001:     $r->print($result);
                   6002: 
1.422     foxr     6003: 
                   6004: 
                   6005:     # Chunk of the form that prompts to view a scoring office file,
                   6006:     # corrected file, skipped records in a file.
                   6007: 
1.489     albertel 6008:     $r->print('
                   6009:    <br />
                   6010:    <form action="/adm/grades" name="scantron_download">
                   6011:      '.$default_form_data.'
                   6012:      <input type="hidden" name="command" value="scantron_download" />
                   6013:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6014:        '.&Apache::loncommon::start_data_table_header_row().'
                   6015:               <th>
1.492     albertel 6016:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6017:               </th>
                   6018:        '.&Apache::loncommon::end_data_table_header_row().'
                   6019:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6020:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6021:                 <br />
1.492     albertel 6022:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6023:        '.&Apache::loncommon::end_data_table_row().'
                   6024:      '.&Apache::loncommon::end_data_table().'
                   6025:    </form>
                   6026:    <br />
                   6027: ');
1.162     albertel 6028: 
1.457     banghart 6029:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6030: 
1.694     bisitz   6031:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6032:              $default_form_data."\n".
                   6033:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6034:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6035:              '<th colspan="2">
1.572     www      6036:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6037:              '</th>'."\n".
                   6038:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6039:               &Apache::loncommon::start_data_table_row()."\n".
                   6040:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6041:               '<td> '.$sequence_selector.' </td>'.
                   6042:               &Apache::loncommon::end_data_table_row()."\n".
                   6043:               &Apache::loncommon::start_data_table_row()."\n".
                   6044:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6045:               '<td> '.$file_selector.' </td>'."\n".
                   6046:               &Apache::loncommon::end_data_table_row()."\n".
                   6047:               &Apache::loncommon::start_data_table_row()."\n".
                   6048:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6049:               '<td> '.$format_selector.' </td>'."\n".
                   6050:               &Apache::loncommon::end_data_table_row()."\n".
                   6051:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6052:               '<td> '.&mt('Options').' </td>'."\n".
                   6053:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6054:               &Apache::loncommon::end_data_table_row()."\n".
                   6055:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6056:               '<td colspan="2">'."\n".
                   6057:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6058:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6059:               '</td>'."\n".
                   6060:               &Apache::loncommon::end_data_table_row()."\n".
                   6061:               &Apache::loncommon::end_data_table()."\n".
                   6062:               '</form><br />');
                   6063:     return;
1.75      albertel 6064: }
                   6065: 
1.423     albertel 6066: =pod 
                   6067: 
                   6068: =item username_to_idmap
                   6069: 
1.556     weissno  6070:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6071:     student username:domain. If a single ID occurs for more than one student,
                   6072:     the status of the student is checked, and if Active, the value in the hash
                   6073:     will be set to the Active student.
1.423     albertel 6074: 
                   6075:   Arguments:
                   6076: 
                   6077:     $classlist - reference to the class list hash. This is a hash
                   6078:                  keyed by student name:domain  whose elements are references
1.424     albertel 6079:                  to arrays containing various chunks of information
1.423     albertel 6080:                  about the student. (See loncoursedata for more info).
                   6081: 
                   6082:   Returns
                   6083:     %idmap - the constructed hash
                   6084: 
                   6085: =cut
                   6086: 
1.82      albertel 6087: sub username_to_idmap {
                   6088:     my ($classlist)= @_;
                   6089:     my %idmap;
                   6090:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6091:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6092:         unless ($id eq '') {
                   6093:             if (!exists($idmap{$id})) {
                   6094:                 $idmap{$id} = $student;
                   6095:             } else {
                   6096:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6097:                 if ($status eq 'Active') {
                   6098:                     $idmap{$id} = $student;
                   6099:                 }
                   6100:             }
                   6101:         }
1.82      albertel 6102:     }
                   6103:     return %idmap;
                   6104: }
1.423     albertel 6105: 
                   6106: =pod
                   6107: 
1.424     albertel 6108: =item scantron_fixup_scanline
1.423     albertel 6109: 
                   6110:    Process a requested correction to a scanline.
                   6111: 
                   6112:   Arguments:
1.754     raeburn  6113:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6114:     $scan_data         - hash of correction information 
                   6115:                           (see &scantron_getfile())
                   6116:     $line              - existing scanline
                   6117:     $whichline         - line number of the passed in scanline
                   6118:     $field             - type of change to process 
                   6119:                          (either 
1.573     bisitz   6120:                           'ID'     -> correct the student/employee ID
1.423     albertel 6121:                           'CODE'   -> correct the CODE
                   6122:                           'answer' -> fixup the submitted answers)
                   6123:     
                   6124:    $args               - hash of additional info,
                   6125:                           - 'ID' 
                   6126:                                'newid' -> studentID to use in replacement
1.424     albertel 6127:                                           of existing one
1.423     albertel 6128:                           - 'CODE' 
                   6129:                                'CODE_ignore_dup' - set to true if duplicates
                   6130:                                                    should be ignored.
                   6131: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6132:                                         if the existing unfound code should
1.423     albertel 6133:                                         be used as is
                   6134:                           - 'answer'
                   6135:                                'response' - new answer or 'none' if blank
                   6136:                                'question' - the bubble line to change
1.503     raeburn  6137:                                'questionnum' - the question identifier,
                   6138:                                                may include subquestion. 
1.423     albertel 6139: 
                   6140:   Returns:
                   6141:     $line - the modified scanline
                   6142: 
                   6143:   Side effects: 
                   6144:     $scan_data - may be updated
                   6145: 
                   6146: =cut
                   6147: 
1.82      albertel 6148: 
1.157     albertel 6149: sub scantron_fixup_scanline {
                   6150:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6151:     if ($field eq 'ID') {
                   6152: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6153: 	    return ($line,1,'New value too large');
1.157     albertel 6154: 	}
                   6155: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6156: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6157: 				     $args->{'newid'});
                   6158: 	}
                   6159: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6160: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6161: 	if ($args->{'newid'}=~/^\s*$/) {
                   6162: 	    &scan_data($scan_data,"$whichline.user",
                   6163: 		       $args->{'username'}.':'.$args->{'domain'});
                   6164: 	}
1.186     albertel 6165:     } elsif ($field eq 'CODE') {
1.192     albertel 6166: 	if ($args->{'CODE_ignore_dup'}) {
                   6167: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6168: 	}
                   6169: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6170: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6171: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6172: 		return ($line,1,'New CODE value too large');
                   6173: 	    }
                   6174: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6175: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6176: 	    }
                   6177: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6178: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6179: 	}
1.157     albertel 6180:     } elsif ($field eq 'answer') {
1.497     foxr     6181: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6182: 	my $off=$scantron_config->{'Qoff'};
                   6183: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6184: 	my $answer=${off}x$length;
                   6185: 	if ($args->{'response'} eq 'none') {
                   6186: 	    &scan_data($scan_data,
1.503     raeburn  6187: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6188: 	} else {
                   6189: 	    if ($on eq 'letter') {
                   6190: 		my @alphabet=('A'..'Z');
                   6191: 		$answer=$alphabet[$args->{'response'}];
                   6192: 	    } elsif ($on eq 'number') {
                   6193: 		$answer=$args->{'response'}+1;
                   6194: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6195: 	    } else {
1.497     foxr     6196: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6197: 	    }
1.497     foxr     6198: 	    &scan_data($scan_data,
1.503     raeburn  6199: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6200: 	}
1.497     foxr     6201: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6202: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6203:     }
                   6204:     return $line;
                   6205: }
1.423     albertel 6206: 
                   6207: =pod
                   6208: 
                   6209: =item scan_data
                   6210: 
                   6211:     Edit or look up  an item in the scan_data hash.
                   6212: 
                   6213:   Arguments:
                   6214:     $scan_data  - The hash (see scantron_getfile)
                   6215:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6216:                   scantronfilename_key).
1.423     albertel 6217:     $data        - New value of the hash entry.
                   6218:     $delete      - If true, the entry is removed from the hash.
                   6219: 
                   6220:   Returns:
                   6221:     The new value of the hash table field (undefined if deleted).
                   6222: 
                   6223: =cut
                   6224: 
                   6225: 
1.157     albertel 6226: sub scan_data {
                   6227:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6228:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6229:     if (defined($value)) {
                   6230: 	$scan_data->{$filename.'_'.$key} = $value;
                   6231:     }
                   6232:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6233:     return $scan_data->{$filename.'_'.$key};
                   6234: }
1.423     albertel 6235: 
1.495     albertel 6236: # ----- These first few routines are general use routines.----
                   6237: 
                   6238: # Return the number of occurences of a pattern in a string.
                   6239: 
                   6240: sub occurence_count {
                   6241:     my ($string, $pattern) = @_;
                   6242: 
                   6243:     my @matches = ($string =~ /$pattern/g);
                   6244: 
                   6245:     return scalar(@matches);
                   6246: }
                   6247: 
                   6248: 
                   6249: # Take a string known to have digits and convert all the
                   6250: # digits into letters in the range J,A..I.
                   6251: 
                   6252: sub digits_to_letters {
                   6253:     my ($input) = @_;
                   6254: 
                   6255:     my @alphabet = ('J', 'A'..'I');
                   6256: 
                   6257:     my @input    = split(//, $input);
                   6258:     my $output ='';
                   6259:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6260: 	if ($input[$i] =~ /\d/) {
                   6261: 	    $output .= $alphabet[$input[$i]];
                   6262: 	} else {
                   6263: 	    $output .= $input[$i];
                   6264: 	}
                   6265:     }
                   6266:     return $output;
                   6267: }
                   6268: 
1.423     albertel 6269: =pod 
                   6270: 
                   6271: =item scantron_parse_scanline
                   6272: 
1.711     bisitz   6273:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6274: 
                   6275:  Arguments:
1.711     bisitz   6276:     line             - The text of the bubblesheet file line to process
1.423     albertel 6277:     whichline        - Line number
1.711     bisitz   6278:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6279:     scan_data        - Hash of extra information about the scanline
                   6280:                        (see scantron_getfile for more information)
                   6281:     just_header      - True if should not process question answers but only
                   6282:                        the stuff to the left of the answers.
1.691     raeburn  6283:     randomorder      - True if randomorder in use
                   6284:     randompick       - True if randompick in use
                   6285:     sequence         - Exam folder URL
                   6286:     master_seq       - Ref to array containing symbs in exam folder
                   6287:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6288:                        (corresponding values are resource objects)
                   6289:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6290:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6291:                        are refs to an array of resource objects, ordered
                   6292:                        according to order used for CODE, when randomorder
                   6293:                        and or randompick are in use.
                   6294:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6295:                        for current line to question number used for same question
                   6296:                         in "Master Sequence" (as seen by Course Coordinator).
                   6297:     startline        - Ref to hash where key is question number (0 is first)
                   6298:                        and value is number of first bubble line for current 
                   6299:                        student or code-based randompick and/or randomorder.
                   6300:     totalref         - Ref of scalar used to score total number of bubble
                   6301:                        lines needed for responses in a scan line (used when
                   6302:                        randompick in use. 
                   6303:     
1.423     albertel 6304:  Returns:
                   6305:    Hash containing the result of parsing the scanline
                   6306: 
                   6307:    Keys are all proceeded by the string 'scantron.'
                   6308: 
                   6309:        CODE    - the CODE in use for this scanline
                   6310:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6311:                  by the operator
                   6312:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6313:                             CODEs were selected, but the usage has been
                   6314:                             forced by the operator
1.556     weissno  6315:        ID  - student/employee ID
1.423     albertel 6316:        PaperID - if used, the ID number printed on the sheet when the 
                   6317:                  paper was scanned
                   6318:        FirstName - first name from the sheet
                   6319:        LastName  - last name from the sheet
                   6320: 
                   6321:      if just_header was not true these key may also exist
                   6322: 
1.447     foxr     6323:        missingerror - a list of bubble ranges that are considered to be answers
                   6324:                       to a single question that don't have any bubbles filled in.
                   6325:                       Of the form questionnumber:firstbubblenumber:count.
                   6326:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6327:                       to a single question that have more than one bubble filled in.
                   6328:                       Of the form questionnumber::firstbubblenumber:count
                   6329:    
                   6330:                 In the above, count is the number of bubble responses in the
                   6331:                 input line needed to represent the possible answers to the question.
                   6332:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6333:                 per line would have count = 2.
                   6334: 
1.423     albertel 6335:        maxquest     - the number of the last bubble line that was parsed
                   6336: 
                   6337:        (<number> starts at 1)
                   6338:        <number>.answer - zero or more letters representing the selected
                   6339:                          letters from the scanline for the bubble line 
                   6340:                          <number>.
                   6341:                          if blank there was either no bubble or there where
                   6342:                          multiple bubbles, (consult the keys missingerror and
                   6343:                          doubleerror if this is an error condition)
                   6344: 
                   6345: =cut
                   6346: 
1.82      albertel 6347: sub scantron_parse_scanline {
1.691     raeburn  6348:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6349:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6350:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6351: 
1.82      albertel 6352:     my %record;
1.691     raeburn  6353:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6354:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6355: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6356: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6357: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6358: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6359: 	    $record{'scantron.CODE'}=substr($data,
                   6360: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6361: 					    $$scantron_config{'CODElength'});
1.191     albertel 6362: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6363: 		$record{'scantron.useCODE'}=1;
                   6364: 	    }
1.192     albertel 6365: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6366: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6367: 	    }
1.82      albertel 6368: 	} else {
                   6369: 	    #FIXME interpret first N questions
                   6370: 	}
                   6371:     }
1.83      albertel 6372:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6373: 				  $$scantron_config{'IDlength'});
1.157     albertel 6374:     $record{'scantron.PaperID'}=
                   6375: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6376: 	       $$scantron_config{'PaperIDlength'});
                   6377:     $record{'scantron.FirstName'}=
                   6378: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6379: 	       $$scantron_config{'FirstNamelength'});
                   6380:     $record{'scantron.LastName'}=
                   6381: 	substr($data,$$scantron_config{'LastName'}-1,
                   6382: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6383:     if ($just_header) { return \%record; }
1.194     albertel 6384: 
1.82      albertel 6385:     my @alphabet=('A'..'Z');
                   6386:     my $questnum=0;
1.447     foxr     6387:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6388: 
1.691     raeburn  6389:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6390:     if ($randompick || $randomorder) {
                   6391:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6392:                                          $master_seq,$symb_to_resource,
                   6393:                                          $partids_by_symb,$orderedforcode,
                   6394:                                          $respnumlookup,$startline);
                   6395:         if ($total) {
                   6396:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6397:         }
                   6398:         if (ref($totalref)) {
                   6399:             $$totalref = $total;
                   6400:         }
                   6401:     }
                   6402:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6403:     chomp($questions);		# Get rid of any trailing \n.
                   6404:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6405:     while (length($questions)) {
1.691     raeburn  6406:         my $answers_needed;
                   6407:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6408:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6409:         } else {
                   6410: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6411:         }
1.503     raeburn  6412:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6413:                              || 1;
                   6414:         $questnum++;
                   6415:         my $quest_id = $questnum;
                   6416:         my $currentquest = substr($questions,0,$answer_length);
                   6417:         $questions       = substr($questions,$answer_length);
                   6418:         if (length($currentquest) < $answer_length) { next; }
                   6419: 
1.691     raeburn  6420:         my $subdivided;
                   6421:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6422:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6423:         } else {
                   6424:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6425:         }
                   6426:         if ($subdivided =~ /,/) {
1.503     raeburn  6427:             my $subquestnum = 1;
                   6428:             my $subquestions = $currentquest;
1.691     raeburn  6429:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6430:             foreach my $subans (@subanswers_needed) {
                   6431:                 my $subans_length =
                   6432:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6433:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6434:                 $subquestions   = substr($subquestions,$subans_length);
                   6435:                 $quest_id = "$questnum.$subquestnum";
                   6436:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6437:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6438:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6439:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6440:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6441:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6442:                 } else {
                   6443:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6444:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6445:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6446:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6447:                 }
                   6448:                 $subquestnum ++;
                   6449:             }
                   6450:         } else {
                   6451:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6452:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6453:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6454:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6455:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6456:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6457:             } else {
                   6458:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6459:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6460:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6461:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6462:             }
                   6463:         }
                   6464:     }
                   6465:     $record{'scantron.maxquest'}=$questnum;
                   6466:     return \%record;
                   6467: }
1.447     foxr     6468: 
1.691     raeburn  6469: sub get_master_seq {
                   6470:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6471:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6472:                    (ref($symb_to_resource) eq 'HASH'));
                   6473:     my $resource_error;
                   6474:     foreach my $resource (@{$resources}) {
                   6475:         my $ressymb;
                   6476:         if (ref($resource)) {
                   6477:             $ressymb = $resource->symb();
                   6478:             push(@{$master_seq},$ressymb);
                   6479:             $symb_to_resource->{$ressymb} = $resource;
                   6480:         } else {
                   6481:             $resource_error = 1;
                   6482:             last;
                   6483:         }
                   6484:     }
                   6485:     return $resource_error;
                   6486: }
                   6487: 
                   6488: sub get_respnum_lookups {
                   6489:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6490:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6491:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6492:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6493:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6494:                    (ref($startline) eq 'HASH'));
                   6495:     my ($user,$scancode);
                   6496:     if ((exists($record->{'scantron.CODE'})) &&
                   6497:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6498:         $scancode = $record->{'scantron.CODE'};
                   6499:     } else {
                   6500:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6501:     }
                   6502:     my @mapresources =
                   6503:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6504:                      $orderedforcode);
                   6505:     my $total = 0;
                   6506:     my $count = 0;
                   6507:     foreach my $resource (@mapresources) {
                   6508:         my $id = $resource->id();
                   6509:         my $symb = $resource->symb();
                   6510:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6511:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6512:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6513:                 if ($respnum ne '') {
                   6514:                     $respnumlookup->{$count} = $respnum;
                   6515:                     $startline->{$count} = $total;
                   6516:                     $total += $bubble_lines_per_response{$respnum};
                   6517:                     $count ++;
                   6518:                 }
                   6519:             }
                   6520:         }
                   6521:     }
                   6522:     return $total;
                   6523: }
                   6524: 
1.503     raeburn  6525: sub scantron_validator_lettnum {
                   6526:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6527:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6528:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6529: 
                   6530:     # Qon 'letter' implies for each slot in currquest we have:
                   6531:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6532:     #    about anything else (esp. a value of Qoff) for missing
                   6533:     #    bubbles.
                   6534:     #
                   6535:     # Qon 'number' implies each slot gives a digit that indexes the
                   6536:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6537:     #    and * or ? for double bubbles on a single line.
                   6538:     #
1.447     foxr     6539: 
1.503     raeburn  6540:     my $matchon;
                   6541:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6542:         $matchon = '[A-Z]';
                   6543:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6544:         $matchon = '\d';
                   6545:     }
                   6546:     my $occurrences = 0;
1.691     raeburn  6547:     my $responsenum = $questnum-1;
                   6548:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6549:        $responsenum = $respnumlookup->{$questnum-1} 
                   6550:     }
                   6551:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6552:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6553:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6554:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6555:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6556:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6557:         my @singlelines = split('',$currquest);
                   6558:         foreach my $entry (@singlelines) {
                   6559:             $occurrences = &occurence_count($entry,$matchon);
                   6560:             if ($occurrences > 1) {
                   6561:                 last;
                   6562:             }
1.691     raeburn  6563:         }
1.503     raeburn  6564:     } else {
                   6565:         $occurrences = &occurence_count($currquest,$matchon); 
                   6566:     }
                   6567:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6568:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6569:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6570:             my $bubble = substr($currquest,$ans,1);
                   6571:             if ($bubble =~ /$matchon/ ) {
                   6572:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6573:                     if ($bubble == 0) {
                   6574:                         $bubble = 10; 
                   6575:                     }
                   6576:                     $record->{"scantron.$ansnum.answer"} = 
                   6577:                         $alphabet->[$bubble-1];
                   6578:                 } else {
                   6579:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6580:                 }
                   6581:             } else {
                   6582:                 $record->{"scantron.$ansnum.answer"}='';
                   6583:             }
                   6584:             $ansnum++;
                   6585:         }
                   6586:     } elsif (!defined($currquest)
                   6587:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6588:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6589:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6590:             $record->{"scantron.$ansnum.answer"}='';
                   6591:             $ansnum++;
                   6592:         }
                   6593:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6594:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6595:         }
                   6596:     } else {
                   6597:         if ($$scantron_config{'Qon'} eq 'number') {
                   6598:             $currquest = &digits_to_letters($currquest);            
                   6599:         }
                   6600:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6601:             my $bubble = substr($currquest,$ans,1);
                   6602:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6603:             $ansnum++;
                   6604:         }
                   6605:     }
                   6606:     return $ansnum;
                   6607: }
1.447     foxr     6608: 
1.503     raeburn  6609: sub scantron_validator_positional {
                   6610:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6611:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6612:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6613: 
1.503     raeburn  6614:     # Otherwise there's a positional notation;
                   6615:     # each bubble line requires Qlength items, and there are filled in
                   6616:     # bubbles for each case where there 'Qon' characters.
                   6617:     #
1.447     foxr     6618: 
1.503     raeburn  6619:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6620: 
1.503     raeburn  6621:     # If the split only gives us one element.. the full length of the
                   6622:     # answer string, no bubbles are filled in:
1.447     foxr     6623: 
1.507     raeburn  6624:     if ($answers_needed eq '') {
                   6625:         return;
                   6626:     }
                   6627: 
1.503     raeburn  6628:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6629:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6630:             $record->{"scantron.$ansnum.answer"}='';
                   6631:             $ansnum++;
                   6632:         }
                   6633:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6634:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6635:         }
                   6636:     } elsif (scalar(@array) == 2) {
                   6637:         my $location = length($array[0]);
                   6638:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6639:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6640:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6641:             if ($ans eq $line_num) {
                   6642:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6643:             } else {
                   6644:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6645:             }
                   6646:             $ansnum++;
                   6647:          }
                   6648:     } else {
                   6649:         #  If there's more than one instance of a bubble character
                   6650:         #  That's a double bubble; with positional notation we can
                   6651:         #  record all the bubbles filled in as well as the
                   6652:         #  fact this response consists of multiple bubbles.
                   6653:         #
1.691     raeburn  6654:         my $responsenum = $questnum-1;
                   6655:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6656:             $responsenum = $respnumlookup->{$questnum-1}
                   6657:         }
                   6658:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6659:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6660:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6661:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6662:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6663:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6664:             my $doubleerror = 0;
                   6665:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6666:                    (!$doubleerror)) {
                   6667:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6668:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6669:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6670:                if (length(@currarray) > 2) {
                   6671:                    $doubleerror = 1;
                   6672:                } 
                   6673:             }
                   6674:             if ($doubleerror) {
                   6675:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6676:             }
                   6677:         } else {
                   6678:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6679:         }
                   6680:         my $item = $ansnum;
                   6681:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6682:             $record->{"scantron.$item.answer"} = '';
                   6683:             $item ++;
                   6684:         }
1.447     foxr     6685: 
1.503     raeburn  6686:         my @ans=@array;
                   6687:         my $i=0;
                   6688:         my $increment = 0;
                   6689:         while ($#ans) {
                   6690:             $i+=length($ans[0]) + $increment;
                   6691:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6692:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6693:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6694:             shift(@ans);
                   6695:             $increment = 1;
                   6696:         }
                   6697:         $ansnum += $answers_needed;
1.82      albertel 6698:     }
1.503     raeburn  6699:     return $ansnum;
1.82      albertel 6700: }
                   6701: 
1.423     albertel 6702: =pod
                   6703: 
                   6704: =item scantron_add_delay
                   6705: 
                   6706:    Adds an error message that occurred during the grading phase to a
                   6707:    queue of messages to be shown after grading pass is complete
                   6708: 
                   6709:  Arguments:
1.424     albertel 6710:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6711:    $scanline    - the scanline that caused the error
                   6712:    $errormesage - the error message
                   6713:    $errorcode   - a numeric code for the error
                   6714: 
                   6715:  Side Effects:
1.424     albertel 6716:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6717: 
                   6718: =cut
                   6719: 
1.82      albertel 6720: sub scantron_add_delay {
1.140     albertel 6721:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6722:     push(@$delayqueue,
                   6723: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6724: 	  'ecode' => $errorcode }
                   6725: 	 );
1.82      albertel 6726: }
                   6727: 
1.423     albertel 6728: =pod
                   6729: 
                   6730: =item scantron_find_student
                   6731: 
1.424     albertel 6732:    Finds the username for the current scanline
                   6733: 
                   6734:   Arguments:
                   6735:    $scantron_record - hash result from scantron_parse_scanline
                   6736:    $scan_data       - hash of correction information 
                   6737:                       (see &scantron_getfile() form more information)
                   6738:    $idmap           - hash from &username_to_idmap()
                   6739:    $line            - number of current scanline
                   6740:  
                   6741:   Returns:
                   6742:    Either 'username:domain' or undef if unknown
                   6743: 
1.423     albertel 6744: =cut
                   6745: 
1.82      albertel 6746: sub scantron_find_student {
1.157     albertel 6747:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6748:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6749:     if ($scanID =~ /^\s*$/) {
                   6750:  	return &scan_data($scan_data,"$line.user");
                   6751:     }
1.83      albertel 6752:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6753:  	if (lc($id) eq lc($scanID)) {
                   6754:  	    return $$idmap{$id};
                   6755:  	}
1.83      albertel 6756:     }
                   6757:     return undef;
                   6758: }
                   6759: 
1.423     albertel 6760: =pod
                   6761: 
                   6762: =item scantron_filter
                   6763: 
1.424     albertel 6764:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6765:    hidden resources was selected
                   6766: 
1.423     albertel 6767: =cut
                   6768: 
1.83      albertel 6769: sub scantron_filter {
                   6770:     my ($curres)=@_;
1.331     albertel 6771: 
                   6772:     if (ref($curres) && $curres->is_problem()) {
                   6773: 	# if the user has asked to not have either hidden
                   6774: 	# or 'randomout' controlled resources to be graded
                   6775: 	# don't include them
                   6776: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6777: 	    && $curres->randomout) {
                   6778: 	    return 0;
                   6779: 	}
1.83      albertel 6780: 	return 1;
                   6781:     }
                   6782:     return 0;
1.82      albertel 6783: }
                   6784: 
1.423     albertel 6785: =pod
                   6786: 
                   6787: =item scantron_process_corrections
                   6788: 
1.424     albertel 6789:    Gets correction information out of submitted form data and corrects
                   6790:    the scanline
                   6791: 
1.423     albertel 6792: =cut
                   6793: 
1.157     albertel 6794: sub scantron_process_corrections {
                   6795:     my ($r) = @_;
1.754     raeburn  6796:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6797:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6798:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6799:     my $which=$env{'form.scantron_line'};
1.200     albertel 6800:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6801:     my ($skip,$err,$errmsg);
1.257     albertel 6802:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6803: 	$skip=1;
1.257     albertel 6804:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6805: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6806: 	    $env{'form.scantron_domain'};
1.157     albertel 6807: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6808: 	($line,$err,$errmsg)=
                   6809: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6810: 				     'ID',{'newid'=>$newid,
1.257     albertel 6811: 				    'username'=>$env{'form.scantron_username'},
                   6812: 				    'domain'=>$env{'form.scantron_domain'}});
                   6813:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6814: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6815: 	my $newCODE;
1.192     albertel 6816: 	my %args;
1.190     albertel 6817: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6818: 	    $newCODE='use_unfound';
1.190     albertel 6819: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6820: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6821: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6822: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6823: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6824: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6825: 	}
1.257     albertel 6826: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6827: 	    $args{'CODE_ignore_dup'}=1;
                   6828: 	}
                   6829: 	$args{'CODE'}=$newCODE;
1.186     albertel 6830: 	($line,$err,$errmsg)=
                   6831: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6832: 				     'CODE',\%args);
1.257     albertel 6833:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6834: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6835: 	    ($line,$err,$errmsg)=
                   6836: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6837: 					 $which,'answer',
                   6838: 					 { 'question'=>$question,
1.503     raeburn  6839: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6840:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6841: 	    if ($err) { last; }
                   6842: 	}
                   6843:     }
                   6844:     if ($err) {
1.703     bisitz   6845:         $r->print(
                   6846:             '<p class="LC_error">'
                   6847:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6848:                 $errmsg)
1.704     raeburn  6849:            .'</p>');
1.157     albertel 6850:     } else {
1.200     albertel 6851: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6852: 	&scantron_putfile($scanlines,$scan_data);
                   6853:     }
                   6854: }
                   6855: 
1.423     albertel 6856: =pod
                   6857: 
                   6858: =item reset_skipping_status
                   6859: 
1.424     albertel 6860:    Forgets the current set of remember skipped scanlines (and thus
                   6861:    reverts back to considering all lines in the
                   6862:    scantron_skipped_<filename> file)
                   6863: 
1.423     albertel 6864: =cut
                   6865: 
1.200     albertel 6866: sub reset_skipping_status {
                   6867:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6868:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6869:     &scantron_putfile(undef,$scan_data);
                   6870: }
                   6871: 
1.423     albertel 6872: =pod
                   6873: 
                   6874: =item start_skipping
                   6875: 
1.424     albertel 6876:    Marks a scanline to be skipped. 
                   6877: 
1.423     albertel 6878: =cut
                   6879: 
1.376     albertel 6880: sub start_skipping {
1.200     albertel 6881:     my ($scan_data,$i)=@_;
                   6882:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6883:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6884: 	$remembered{$i}=2;
                   6885:     } else {
                   6886: 	$remembered{$i}=1;
                   6887:     }
1.200     albertel 6888:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6889: }
                   6890: 
1.423     albertel 6891: =pod
                   6892: 
                   6893: =item should_be_skipped
                   6894: 
1.424     albertel 6895:    Checks whether a scanline should be skipped.
                   6896: 
1.423     albertel 6897: =cut
                   6898: 
1.200     albertel 6899: sub should_be_skipped {
1.376     albertel 6900:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6901:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6902: 	# not redoing old skips
1.376     albertel 6903: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6904: 	return 0;
                   6905:     }
                   6906:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6907: 
                   6908:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6909: 	return 0;
                   6910:     }
1.200     albertel 6911:     return 1;
                   6912: }
                   6913: 
1.423     albertel 6914: =pod
                   6915: 
                   6916: =item remember_current_skipped
                   6917: 
1.424     albertel 6918:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6919:    file and remembers them into scan_data for later use.
                   6920: 
1.423     albertel 6921: =cut
                   6922: 
1.200     albertel 6923: sub remember_current_skipped {
                   6924:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6925:     my %to_remember;
                   6926:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6927: 	if ($scanlines->{'skipped'}[$i]) {
                   6928: 	    $to_remember{$i}=1;
                   6929: 	}
                   6930:     }
1.376     albertel 6931: 
1.200     albertel 6932:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6933:     &scantron_putfile(undef,$scan_data);
                   6934: }
                   6935: 
1.423     albertel 6936: =pod
                   6937: 
                   6938: =item check_for_error
                   6939: 
1.424     albertel 6940:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6941:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6942:     something went wrong.
                   6943: 
1.423     albertel 6944: =cut
                   6945: 
1.200     albertel 6946: sub check_for_error {
                   6947:     my ($r,$result)=@_;
                   6948:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6949: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6950:     }
                   6951: }
1.157     albertel 6952: 
1.423     albertel 6953: =pod
                   6954: 
                   6955: =item scantron_warning_screen
                   6956: 
1.424     albertel 6957:    Interstitial screen to make sure the operator has selected the
                   6958:    correct options before we start the validation phase.
                   6959: 
1.423     albertel 6960: =cut
                   6961: 
1.203     albertel 6962: sub scantron_warning_screen {
1.650     raeburn  6963:     my ($button_text,$symb)=@_;
1.257     albertel 6964:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  6965:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6966:     my $CODElist;
1.284     albertel 6967:     if ($scantron_config{'CODElocation'} &&
                   6968: 	$scantron_config{'CODEstart'} &&
                   6969: 	$scantron_config{'CODElength'}) {
                   6970: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6971: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6972: 	$CODElist=
1.492     albertel 6973: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6974: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6975:     }
1.663     raeburn  6976:     my $lastbubblepoints;
                   6977:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6978:         $lastbubblepoints =
                   6979:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6980:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6981:     }
1.492     albertel 6982:     return ('
1.203     albertel 6983: <p>
1.492     albertel 6984: <span class="LC_warning">
1.705     raeburn  6985: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6986: </p>
                   6987: <table>
1.492     albertel 6988: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6989: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6990: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6991: </table>
1.680     raeburn  6992: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6993: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
1.203     albertel 6994: 
                   6995: <br />
1.492     albertel 6996: ');
1.203     albertel 6997: }
                   6998: 
1.423     albertel 6999: =pod
                   7000: 
                   7001: =item scantron_do_warning
                   7002: 
1.424     albertel 7003:    Check if the operator has picked something for all required
                   7004:    fields. Error out if something is missing.
                   7005: 
1.423     albertel 7006: =cut
                   7007: 
1.203     albertel 7008: sub scantron_do_warning {
1.608     www      7009:     my ($r,$symb)=@_;
1.203     albertel 7010:     if (!$symb) {return '';}
1.324     albertel 7011:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7012:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7013:     if ( $env{'form.selectpage'} eq '' ||
                   7014: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7015: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7016: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7017: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7018: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7019: 	} 
1.257     albertel 7020: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7021: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.237     albertel 7022: 	} 
1.257     albertel 7023: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7024: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 7025: 	} 
                   7026:     } else {
1.650     raeburn  7027: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  7028:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7029: 	$r->print('
1.663     raeburn  7030: '.$warning.$bubbledbyhand.'
1.492     albertel 7031: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7032: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7033: ');
1.237     albertel 7034:     }
1.614     www      7035:     $r->print("</form><br />");
1.203     albertel 7036:     return '';
                   7037: }
                   7038: 
1.423     albertel 7039: =pod
                   7040: 
                   7041: =item scantron_form_start
                   7042: 
1.424     albertel 7043:     html hidden input for remembering all selected grading options
                   7044: 
1.423     albertel 7045: =cut
                   7046: 
1.203     albertel 7047: sub scantron_form_start {
                   7048:     my ($max_bubble)=@_;
                   7049:     my $result= <<SCANTRONFORM;
                   7050: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7051:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7052:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7053:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7054:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7055:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7056:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7057:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7058:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7059:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7060: SCANTRONFORM
1.447     foxr     7061: 
                   7062:   my $line = 0;
                   7063:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7064:        my $chunk =
                   7065: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7066:        $chunk .=
                   7067: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7068:        $chunk .= 
                   7069:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7070:        $chunk .=
                   7071:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7072:        $chunk .=
                   7073:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7074:        $result .= $chunk;
                   7075:        $line++;
1.691     raeburn  7076:     }
1.203     albertel 7077:     return $result;
                   7078: }
                   7079: 
1.423     albertel 7080: =pod
                   7081: 
                   7082: =item scantron_validate_file
                   7083: 
1.659     raeburn  7084:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7085: 
                   7086:     Also processes any necessary information resets that need to
                   7087:     occur before validation begins (ignore previous corrections,
                   7088:     restarting the skipped records processing)
                   7089: 
1.423     albertel 7090: =cut
                   7091: 
1.157     albertel 7092: sub scantron_validate_file {
1.608     www      7093:     my ($r,$symb) = @_;
1.157     albertel 7094:     if (!$symb) {return '';}
1.324     albertel 7095:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7096:     
1.703     bisitz   7097:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7098:     # them when doing the corrections reset
1.257     albertel 7099:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7100: 	&reset_skipping_status();
                   7101:     }
1.257     albertel 7102:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7103: 	&remember_current_skipped();
1.257     albertel 7104: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7105:     }
                   7106: 
1.257     albertel 7107:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7108: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7109: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7110: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7111: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7112:     }
1.200     albertel 7113: 
1.257     albertel 7114:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7115: 	&scantron_process_corrections($r);
                   7116:     }
1.503     raeburn  7117:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7118:     #get the student pick code ready
                   7119:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7120:     my $nav_error;
1.754     raeburn  7121:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7122:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7123:     if ($nav_error) {
                   7124:         $r->print(&navmap_errormsg());
                   7125:         return '';
                   7126:     }
1.203     albertel 7127:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7128:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7129:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7130:     }
1.157     albertel 7131:     $r->print($result);
                   7132:     
1.334     albertel 7133:     my @validate_phases=( 'sequence',
                   7134: 			  'ID',
1.157     albertel 7135: 			  'CODE',
                   7136: 			  'doublebubble',
                   7137: 			  'missingbubbles');
1.257     albertel 7138:     if (!$env{'form.validatepass'}) {
                   7139: 	$env{'form.validatepass'} = 0;
1.157     albertel 7140:     }
1.257     albertel 7141:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7142: 
1.448     foxr     7143: 
1.157     albertel 7144:     my $stop=0;
                   7145:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7146: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7147: 	$r->rflush();
1.691     raeburn  7148:      
1.157     albertel 7149: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7150: 	{
                   7151: 	    no strict 'refs';
                   7152: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7153: 	}
                   7154:     }
                   7155:     if (!$stop) {
1.650     raeburn  7156: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7157: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7158:                   $warning.
                   7159:                   &mt('Perform verification for each student after storage of submissions?').
                   7160:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7161:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7162:                   ('&nbsp;'x3).'<label>'.
                   7163:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7164:                   '</label></span><br />'.
                   7165:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7166:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7167:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7168:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7169:     } else {
                   7170: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7171: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7172:     }
                   7173:     if ($stop) {
1.334     albertel 7174: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7175: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7176: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7177: 
1.650     raeburn  7178: 	    $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 7179: 	} else {
1.503     raeburn  7180:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7181: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7182:             } else {
1.539     riegler  7183:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7184:             }
1.492     albertel 7185: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7186: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7187: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7188: 	}
1.157     albertel 7189:     }
1.614     www      7190:     $r->print(" </form><br />");
1.157     albertel 7191:     return '';
                   7192: }
                   7193: 
1.423     albertel 7194: 
                   7195: =pod
                   7196: 
                   7197: =item scantron_remove_file
                   7198: 
1.659     raeburn  7199:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7200:    scantron_original_<filename> is never removed
                   7201: 
                   7202: 
1.423     albertel 7203: =cut
                   7204: 
1.200     albertel 7205: sub scantron_remove_file {
1.192     albertel 7206:     my ($which)=@_;
1.257     albertel 7207:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7208:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7209:     my $file='scantron_';
1.200     albertel 7210:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7211: 	$file.=$which.'_';
1.192     albertel 7212:     } else {
                   7213: 	return 'refused';
                   7214:     }
1.257     albertel 7215:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7216:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7217: }
                   7218: 
1.423     albertel 7219: 
                   7220: =pod
                   7221: 
                   7222: =item scantron_remove_scan_data
                   7223: 
1.659     raeburn  7224:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7225:    data file.  (In the case that both the are doing skipped records we need
                   7226:    to remember the old skipped lines for the time being so that element
                   7227:    persists for a while.)
                   7228: 
1.423     albertel 7229: =cut
                   7230: 
1.200     albertel 7231: sub scantron_remove_scan_data {
1.257     albertel 7232:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7233:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7234:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7235:     my @todelete;
1.257     albertel 7236:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7237:     foreach my $key (@keys) {
                   7238: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7239: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7240: 		$key=~/remember_skipping/) {
                   7241: 		next;
                   7242: 	    }
1.192     albertel 7243: 	    push(@todelete,$key);
                   7244: 	}
                   7245:     }
1.200     albertel 7246:     my $result;
1.192     albertel 7247:     if (@todelete) {
1.491     albertel 7248: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7249: 				       \@todelete,$cdom,$cname);
                   7250:     } else {
                   7251: 	$result = 'ok';
1.192     albertel 7252:     }
                   7253:     return $result;
                   7254: }
                   7255: 
1.423     albertel 7256: 
                   7257: =pod
                   7258: 
                   7259: =item scantron_getfile
                   7260: 
1.659     raeburn  7261:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7262:     the scan_data hash
                   7263:   
                   7264:   Arguments:
                   7265:     None
                   7266: 
                   7267:   Returns:
                   7268:     2 hash references
                   7269: 
                   7270:      - first one has 
                   7271:          orig      -
                   7272:          corrected -
                   7273:          skipped   -  each of which points to an array ref of the specified
                   7274:                       file broken up into individual lines
                   7275:          count     - number of scanlines
                   7276:  
                   7277:      - second is the scan_data hash possible keys are
1.425     albertel 7278:        ($number refers to scanline numbered $number and thus the key affects
                   7279:         only that scanline
                   7280:         $bubline refers to the specific bubble line element and the aspects
                   7281:         refers to that specific bubble line element)
                   7282: 
                   7283:        $number.user - username:domain to use
                   7284:        $number.CODE_ignore_dup 
                   7285:                     - ignore the duplicate CODE error 
                   7286:        $number.useCODE
                   7287:                     - use the CODE in the scanline as is
                   7288:        $number.no_bubble.$bubline
                   7289:                     - it is valid that there is no bubbled in bubble
                   7290:                       at $number $bubline
                   7291:        remember_skipping
                   7292:                     - a frozen hash containing keys of $number and values
                   7293:                       of either 
                   7294:                         1 - we are on a 'do skipped records pass' and plan
                   7295:                             on processing this line
                   7296:                         2 - we are on a 'do skipped records pass' and this
                   7297:                             scanline has been marked to skip yet again
1.424     albertel 7298: 
1.423     albertel 7299: =cut
                   7300: 
1.157     albertel 7301: sub scantron_getfile {
1.200     albertel 7302:     #FIXME really would prefer a scantron directory
1.257     albertel 7303:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7304:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7305:     my $lines;
                   7306:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7307: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7308:     my %scanlines;
                   7309:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7310:     my $temp=$scanlines{'orig'};
                   7311:     $scanlines{'count'}=$#$temp;
                   7312: 
                   7313:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7314: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7315:     if ($lines eq '-1') {
                   7316: 	$scanlines{'corrected'}=[];
                   7317:     } else {
                   7318: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7319:     }
                   7320:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7321: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7322:     if ($lines eq '-1') {
                   7323: 	$scanlines{'skipped'}=[];
                   7324:     } else {
                   7325: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7326:     }
1.175     albertel 7327:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7328:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7329:     my %scan_data = @tmp;
                   7330:     return (\%scanlines,\%scan_data);
                   7331: }
                   7332: 
1.423     albertel 7333: =pod
                   7334: 
                   7335: =item lonnet_putfile
                   7336: 
1.424     albertel 7337:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7338: 
                   7339:  Arguments:
                   7340:    $contents - data to store
                   7341:    $filename - filename to store $contents into
                   7342: 
                   7343:  Returns:
                   7344:    result value from &Apache::lonnet::finishuserfileupload
                   7345: 
1.423     albertel 7346: =cut
                   7347: 
1.157     albertel 7348: sub lonnet_putfile {
                   7349:     my ($contents,$filename)=@_;
1.257     albertel 7350:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7351:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7352:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7353:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7354: 
                   7355: }
                   7356: 
1.423     albertel 7357: =pod
                   7358: 
                   7359: =item scantron_putfile
                   7360: 
1.659     raeburn  7361:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7362:     scan_data hash. (Does not modify the original version only the
                   7363:     corrected and skipped versions.
                   7364: 
                   7365:  Arguments:
                   7366:     $scanlines - hash ref that looks like the first return value from
                   7367:                  &scantron_getfile()
                   7368:     $scan_data - hash ref that looks like the second return value from
                   7369:                  &scantron_getfile()
                   7370: 
1.423     albertel 7371: =cut
                   7372: 
1.157     albertel 7373: sub scantron_putfile {
                   7374:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7375:     #FIXME really would prefer a scantron directory
1.257     albertel 7376:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7377:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7378:     if ($scanlines) {
                   7379: 	my $prefix='scantron_';
1.157     albertel 7380: # no need to update orig, shouldn't change
                   7381: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7382: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7383: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7384: 			$prefix.'corrected_'.
1.257     albertel 7385: 			$env{'form.scantron_selectfile'});
1.200     albertel 7386: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7387: 			$prefix.'skipped_'.
1.257     albertel 7388: 			$env{'form.scantron_selectfile'});
1.200     albertel 7389:     }
1.175     albertel 7390:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7391: }
                   7392: 
1.423     albertel 7393: =pod
                   7394: 
                   7395: =item scantron_get_line
                   7396: 
1.424     albertel 7397:    Returns the correct version of the scanline
                   7398: 
                   7399:  Arguments:
                   7400:     $scanlines - hash ref that looks like the first return value from
                   7401:                  &scantron_getfile()
                   7402:     $scan_data - hash ref that looks like the second return value from
                   7403:                  &scantron_getfile()
                   7404:     $i         - number of the requested line (starts at 0)
                   7405: 
                   7406:  Returns:
                   7407:    A scanline, (either the original or the corrected one if it
                   7408:    exists), or undef if the requested scanline should be
                   7409:    skipped. (Either because it's an skipped scanline, or it's an
                   7410:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7411:    pass.
                   7412: 
1.423     albertel 7413: =cut
                   7414: 
1.157     albertel 7415: sub scantron_get_line {
1.200     albertel 7416:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7417:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7418:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7419:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7420:     return $scanlines->{'orig'}[$i]; 
                   7421: }
                   7422: 
1.423     albertel 7423: =pod
                   7424: 
                   7425: =item scantron_todo_count
                   7426: 
1.424     albertel 7427:     Counts the number of scanlines that need processing.
                   7428: 
                   7429:  Arguments:
                   7430:     $scanlines - hash ref that looks like the first return value from
                   7431:                  &scantron_getfile()
                   7432:     $scan_data - hash ref that looks like the second return value from
                   7433:                  &scantron_getfile()
                   7434: 
                   7435:  Returns:
                   7436:     $count - number of scanlines to process
                   7437: 
1.423     albertel 7438: =cut
                   7439: 
1.200     albertel 7440: sub get_todo_count {
                   7441:     my ($scanlines,$scan_data)=@_;
                   7442:     my $count=0;
                   7443:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7444: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7445: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7446: 	$count++;
                   7447:     }
                   7448:     return $count;
                   7449: }
                   7450: 
1.423     albertel 7451: =pod
                   7452: 
                   7453: =item scantron_put_line
                   7454: 
1.659     raeburn  7455:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7456:     data file.
                   7457: 
                   7458:  Arguments:
                   7459:     $scanlines - hash ref that looks like the first return value from
                   7460:                  &scantron_getfile()
                   7461:     $scan_data - hash ref that looks like the second return value from
                   7462:                  &scantron_getfile()
                   7463:     $i         - line number to update
                   7464:     $newline   - contents of the updated scanline
                   7465:     $skip      - if true make the line for skipping and update the
                   7466:                  'skipped' file
                   7467: 
1.423     albertel 7468: =cut
                   7469: 
1.157     albertel 7470: sub scantron_put_line {
1.200     albertel 7471:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7472:     if ($skip) {
                   7473: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7474: 	&start_skipping($scan_data,$i);
1.157     albertel 7475: 	return;
                   7476:     }
                   7477:     $scanlines->{'corrected'}[$i]=$newline;
                   7478: }
                   7479: 
1.423     albertel 7480: =pod
                   7481: 
                   7482: =item scantron_clear_skip
                   7483: 
1.424     albertel 7484:    Remove a line from the 'skipped' file
                   7485: 
                   7486:  Arguments:
                   7487:     $scanlines - hash ref that looks like the first return value from
                   7488:                  &scantron_getfile()
                   7489:     $scan_data - hash ref that looks like the second return value from
                   7490:                  &scantron_getfile()
                   7491:     $i         - line number to update
                   7492: 
1.423     albertel 7493: =cut
                   7494: 
1.376     albertel 7495: sub scantron_clear_skip {
                   7496:     my ($scanlines,$scan_data,$i)=@_;
                   7497:     if (exists($scanlines->{'skipped'}[$i])) {
                   7498: 	undef($scanlines->{'skipped'}[$i]);
                   7499: 	return 1;
                   7500:     }
                   7501:     return 0;
                   7502: }
                   7503: 
1.423     albertel 7504: =pod
                   7505: 
                   7506: =item scantron_filter_not_exam
                   7507: 
1.424     albertel 7508:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7509:    filter out resources that are not marked as 'exam' mode
                   7510: 
1.423     albertel 7511: =cut
                   7512: 
1.334     albertel 7513: sub scantron_filter_not_exam {
                   7514:     my ($curres)=@_;
                   7515:     
                   7516:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7517: 	# if the user has asked to not have either hidden
                   7518: 	# or 'randomout' controlled resources to be graded
                   7519: 	# don't include them
                   7520: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7521: 	    && $curres->randomout) {
                   7522: 	    return 0;
                   7523: 	}
                   7524: 	return 1;
                   7525:     }
                   7526:     return 0;
                   7527: }
                   7528: 
1.423     albertel 7529: =pod
                   7530: 
                   7531: =item scantron_validate_sequence
                   7532: 
1.424     albertel 7533:     Validates the selected sequence, checking for resource that are
                   7534:     not set to exam mode.
                   7535: 
1.423     albertel 7536: =cut
                   7537: 
1.334     albertel 7538: sub scantron_validate_sequence {
                   7539:     my ($r,$currentphase) = @_;
                   7540: 
                   7541:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7542:     unless (ref($navmap)) {
                   7543:         $r->print(&navmap_errormsg());
                   7544:         return (1,$currentphase);
                   7545:     }
1.334     albertel 7546:     my (undef,undef,$sequence)=
                   7547: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7548: 
                   7549:     my $map=$navmap->getResourceByUrl($sequence);
                   7550: 
                   7551:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7552:                                     value="ignore" />');
                   7553:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7554: 	my @resources=
                   7555: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7556: 	if (@resources) {
1.675     bisitz   7557: 	    $r->print(
                   7558:                 '<p class="LC_warning">'
                   7559:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7560:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7561:                    .' work correctly.')
                   7562:                .'</p>'
                   7563:             );
1.334     albertel 7564: 	    return (1,$currentphase);
                   7565: 	}
                   7566:     }
                   7567: 
                   7568:     return (0,$currentphase+1);
                   7569: }
                   7570: 
1.423     albertel 7571: 
                   7572: 
1.157     albertel 7573: sub scantron_validate_ID {
                   7574:     my ($r,$currentphase) = @_;
                   7575:     
                   7576:     #get student info
                   7577:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7578:     my %idmap=&username_to_idmap($classlist);
                   7579: 
                   7580:     #get scantron line setup
1.754     raeburn  7581:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7582:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7583: 
                   7584:     my $nav_error;
1.649     raeburn  7585:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7586:     if ($nav_error) {
                   7587:         $r->print(&navmap_errormsg());
                   7588:         return(1,$currentphase);
                   7589:     }
1.157     albertel 7590: 
                   7591:     my %found=('ids'=>{},'usernames'=>{});
                   7592:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7593: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7594: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7595: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7596: 						 $scan_data);
                   7597: 	my $id=$$scan_record{'scantron.ID'};
                   7598: 	my $found;
                   7599: 	foreach my $checkid (keys(%idmap)) {
                   7600: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7601: 	}
                   7602: 	if ($found) {
                   7603: 	    my $username=$idmap{$found};
                   7604: 	    if ($found{'ids'}{$found}) {
                   7605: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7606: 					 $line,'duplicateID',$found);
1.194     albertel 7607: 		return(1,$currentphase);
1.157     albertel 7608: 	    } elsif ($found{'usernames'}{$username}) {
                   7609: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7610: 					 $line,'duplicateID',$username);
1.194     albertel 7611: 		return(1,$currentphase);
1.157     albertel 7612: 	    }
1.186     albertel 7613: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7614: 	    $found{'ids'}{$found}++;
                   7615: 	    $found{'usernames'}{$username}++;
                   7616: 	} else {
                   7617: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7618: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7619: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7620: 		    &scantron_get_correction($r,$i,$scan_record,
                   7621: 					     \%scantron_config,
                   7622: 					     $line,'duplicateID',$username);
1.194     albertel 7623: 		    return(1,$currentphase);
1.157     albertel 7624: 		} elsif (!defined($username)) {
                   7625: 		    &scantron_get_correction($r,$i,$scan_record,
                   7626: 					     \%scantron_config,
                   7627: 					     $line,'incorrectID');
1.194     albertel 7628: 		    return(1,$currentphase);
1.157     albertel 7629: 		}
                   7630: 		$found{'usernames'}{$username}++;
                   7631: 	    } else {
                   7632: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7633: 					 $line,'incorrectID');
1.194     albertel 7634: 		return(1,$currentphase);
1.157     albertel 7635: 	    }
                   7636: 	}
                   7637:     }
                   7638: 
                   7639:     return (0,$currentphase+1);
                   7640: }
                   7641: 
1.423     albertel 7642: 
1.157     albertel 7643: sub scantron_get_correction {
1.691     raeburn  7644:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7645:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7646: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7647: #to show both the current line and the previous one and allow skipping
                   7648: #the previous one or the current one
                   7649: 
1.333     albertel 7650:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7651:         $r->print(
                   7652:             '<p class="LC_warning">'
                   7653:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7654:                 "<b>$error</b>",
                   7655:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7656:            ."</p> \n");
1.157     albertel 7657:     } else {
1.658     bisitz   7658:         $r->print(
                   7659:             '<p class="LC_warning">'
                   7660:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7661:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7662:            ."</p> \n");
                   7663:     }
                   7664:     my $message =
                   7665:         '<p>'
                   7666:        .&mt('The ID on the form is [_1]',
                   7667:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7668:        .'<br />'
1.665     raeburn  7669:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7670:             $$scan_record{'scantron.LastName'},
                   7671:             $$scan_record{'scantron.FirstName'})
                   7672:        .'</p>';
1.242     albertel 7673: 
1.157     albertel 7674:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7675:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7676:                            # Array populated for doublebubble or
                   7677:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7678:                            # to validate radio button checking   
                   7679: 
1.157     albertel 7680:     if ($error =~ /ID$/) {
1.186     albertel 7681: 	if ($error eq 'incorrectID') {
1.658     bisitz   7682:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7683: 		      "</p>\n");
1.157     albertel 7684: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7685:             $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 7686: 	}
1.242     albertel 7687: 	$r->print($message);
1.492     albertel 7688: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7689: 	$r->print("\n<ul><li> ");
                   7690: 	#FIXME it would be nice if this sent back the user ID and
                   7691: 	#could do partial userID matches
                   7692: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7693: 				       'scantron_username','scantron_domain'));
                   7694: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7695: 	$r->print("\n:\n".
1.257     albertel 7696: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7697: 
                   7698: 	$r->print('</li>');
1.186     albertel 7699:     } elsif ($error =~ /CODE$/) {
                   7700: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7701: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7702: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7703: 	    $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 7704: 	}
1.658     bisitz   7705: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7706: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7707:                  ."</p>\n");
1.242     albertel 7708: 	$r->print($message);
1.658     bisitz   7709: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7710: 	$r->print("\n<br /> ");
1.194     albertel 7711: 	my $i=0;
1.273     albertel 7712: 	if ($error eq 'incorrectCODE' 
                   7713: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7714: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7715: 	    if ($closest > 0) {
                   7716: 		foreach my $testcode (@{$closest}) {
                   7717: 		    my $checked='';
1.569     bisitz   7718: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7719: 		    $r->print("
                   7720:    <label>
1.569     bisitz   7721:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7722:        ".&mt("Use the similar CODE [_1] instead.",
                   7723: 	    "<b><tt>".$testcode."</tt></b>")."
                   7724:     </label>
                   7725:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7726: 		    $r->print("\n<br />");
                   7727: 		    $i++;
                   7728: 		}
1.194     albertel 7729: 	    }
                   7730: 	}
1.273     albertel 7731: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7732: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7733: 	    $r->print("
                   7734:     <label>
1.569     bisitz   7735:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7736:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7737: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7738:     </label>");
1.273     albertel 7739: 	    $r->print("\n<br />");
                   7740: 	}
1.194     albertel 7741: 
1.597     wenzelju 7742: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7743: function change_radio(field) {
1.190     albertel 7744:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7745:     var i;
                   7746:     for (i=0;i<slct.length;i++) {
                   7747:         if (slct[i].value==field) { slct[i].checked=true; }
                   7748:     }
                   7749: }
                   7750: ENDSCRIPT
1.187     albertel 7751: 	my $href="/adm/pickcode?".
1.359     www      7752: 	   "form=".&escape("scantronupload").
                   7753: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7754: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7755: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7756: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7757: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7758: 	    $r->print("
                   7759:     <label>
                   7760:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7761:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7762: 	     "<a target='_blank' href='$href'>","</a>")."
                   7763:     </label> 
1.558     bisitz   7764:     ".&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 7765: 	    $r->print("\n<br />");
                   7766: 	}
1.492     albertel 7767: 	$r->print("
                   7768:     <label>
                   7769:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7770:        ".&mt("Use [_1] as the CODE.",
                   7771: 	     "</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 7772: 	$r->print("\n<br /><br />");
1.157     albertel 7773:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7774: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7775: 
                   7776: 	# The form field scantron_questions is acutally a list of line numbers.
                   7777: 	# represented by this form so:
                   7778: 
1.691     raeburn  7779: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7780:                                                 $respnumlookup,$startline);
1.497     foxr     7781: 
1.157     albertel 7782: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7783: 		  $line_list.'" />');
1.242     albertel 7784: 	$r->print($message);
1.492     albertel 7785: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7786: 	foreach my $question (@{$arg}) {
1.503     raeburn  7787: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7788:                                                    $scan_record, $error,
                   7789:                                                    $randomorder,$randompick,
                   7790:                                                    $respnumlookup,$startline);
1.524     raeburn  7791:             push(@lines_to_correct,@linenums);
1.157     albertel 7792: 	}
1.503     raeburn  7793:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7794:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7795: 	$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 7796: 	$r->print($message);
1.492     albertel 7797: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7798: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7799: 
1.503     raeburn  7800: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7801: 	# a list of question numbers. Therefore:
                   7802: 	#
1.691     raeburn  7803: 
                   7804: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7805:                                                 $respnumlookup,$startline);
1.497     foxr     7806: 
1.157     albertel 7807: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7808: 		  $line_list.'" />');
1.157     albertel 7809: 	foreach my $question (@{$arg}) {
1.503     raeburn  7810: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7811:                                                    $scan_record, $error,
                   7812:                                                    $randomorder,$randompick,
                   7813:                                                    $respnumlookup,$startline);
1.524     raeburn  7814:             push(@lines_to_correct,@linenums);
1.157     albertel 7815: 	}
1.503     raeburn  7816:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7817:     } else {
                   7818: 	$r->print("\n<ul>");
                   7819:     }
                   7820:     $r->print("\n</li></ul>");
1.497     foxr     7821: }
                   7822: 
1.503     raeburn  7823: sub verify_bubbles_checked {
                   7824:     my (@ansnums) = @_;
                   7825:     my $ansnumstr = join('","',@ansnums);
                   7826:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7827:     &js_escape(\$warning);
1.597     wenzelju 7828:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7829: function verify_bubble_radio(form) {
                   7830:     var ansnumArray = new Array ("$ansnumstr");
                   7831:     var need_bubble_count = 0;
                   7832:     for (var i=0; i<ansnumArray.length; i++) {
                   7833:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7834:             var bubble_picked = 0; 
                   7835:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7836:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7837:                     bubble_picked = 1;
                   7838:                 }
                   7839:             }
                   7840:             if (bubble_picked == 0) {
                   7841:                 need_bubble_count ++;
                   7842:             }
                   7843:         }
                   7844:     }
                   7845:     if (need_bubble_count) {
                   7846:         alert("$warning");
                   7847:         return;
                   7848:     }
                   7849:     form.submit(); 
                   7850: }
                   7851: ENDSCRIPT
                   7852:     return $output;
                   7853: }
                   7854: 
1.497     foxr     7855: =pod
                   7856: 
                   7857: =item  questions_to_line_list
1.157     albertel 7858: 
1.497     foxr     7859: Converts a list of questions into a string of comma separated
                   7860: line numbers in the answer sheet used by the questions.  This is
                   7861: used to fill in the scantron_questions form field.
                   7862: 
                   7863:   Arguments:
                   7864:      questions    - Reference to an array of questions.
1.691     raeburn  7865:      randomorder  - True if randomorder in use.
                   7866:      randompick   - True if randompick in use.
                   7867:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7868:                      for current line to question number used for same question
                   7869:                      in "Master Seqence" (as seen by Course Coordinator).
                   7870:      startline    - Reference to hash where key is question number (0 is first)
                   7871:                     and key is number of first bubble line for current student
                   7872:                     or code-based randompick and/or randomorder.
1.693     raeburn  7873: 
1.497     foxr     7874: =cut
                   7875: 
                   7876: 
                   7877: sub questions_to_line_list {
1.691     raeburn  7878:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7879:     my @lines;
                   7880: 
1.503     raeburn  7881:     foreach my $item (@{$questions}) {
                   7882:         my $question = $item;
                   7883:         my ($first,$count,$last);
                   7884:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7885:             $question = $1;
                   7886:             my $subquestion = $2;
1.691     raeburn  7887:             my $responsenum = $question-1;
                   7888:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7889:                 $responsenum = $respnumlookup->{$question-1};
                   7890:                 if (ref($startline) eq 'HASH') {
                   7891:                     $first = $startline->{$question-1} + 1;
                   7892:                 }
                   7893:             } else {
                   7894:                 $first = $first_bubble_line{$responsenum} + 1;
                   7895:             }
                   7896:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7897:             my $subcount = 1;
                   7898:             while ($subcount<$subquestion) {
                   7899:                 $first += $subans[$subcount-1];
                   7900:                 $subcount ++;
                   7901:             }
                   7902:             $count = $subans[$subquestion-1];
                   7903:         } else {
1.691     raeburn  7904:             my $responsenum = $question-1;
                   7905:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7906:                 $responsenum = $respnumlookup->{$question-1};
                   7907:                 if (ref($startline) eq 'HASH') {
                   7908:                     $first = $startline->{$question-1} + 1;
                   7909:                 }
                   7910:             } else {
                   7911:                 $first = $first_bubble_line{$responsenum} + 1;
                   7912:             }
                   7913: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7914:         }
1.506     raeburn  7915:         $last = $first+$count-1;
1.503     raeburn  7916:         push(@lines, ($first..$last));
1.497     foxr     7917:     }
                   7918:     return join(',', @lines);
                   7919: }
                   7920: 
                   7921: =pod 
                   7922: 
                   7923: =item prompt_for_corrections
                   7924: 
                   7925: Prompts for a potentially multiline correction to the
                   7926: user's bubbling (factors out common code from scantron_get_correction
                   7927: for multi and missing bubble cases).
                   7928: 
                   7929:  Arguments:
                   7930:    $r           - Apache request object.
                   7931:    $question    - The question number to prompt for.
                   7932:    $scan_config - The scantron file configuration hash.
                   7933:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7934:    $error       - Type of error
1.691     raeburn  7935:    $randomorder - True if randomorder in use.
                   7936:    $randompick  - True if randompick in use.
                   7937:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7938:                     for current line to question number used for same question
                   7939:                     in "Master Seqence" (as seen by Course Coordinator).
                   7940:    $startline   - Reference to hash where key is question number (0 is first)
                   7941:                   and value is number of first bubble line for current student
                   7942:                   or code-based randompick and/or randomorder.
                   7943: 
1.497     foxr     7944: 
                   7945:  Implicit inputs:
                   7946:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7947:                                   Numbered from 0 (but question numbers are from
                   7948:                                   1.
                   7949:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7950:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7951:                                   type problems render as separate sub-questions, 
1.503     raeburn  7952:                                   in exam mode. This hash contains a 
                   7953:                                   comma-separated list of the lines per 
                   7954:                                   sub-question.
1.510     raeburn  7955:    %responsetype_per_response   - essayresponse, formularesponse,
                   7956:                                   stringresponse, imageresponse, reactionresponse,
                   7957:                                   and organicresponse type problem parts can have
1.503     raeburn  7958:                                   multiple lines per response if the weight
                   7959:                                   assigned exceeds 10.  In this case, only
                   7960:                                   one bubble per line is permitted, but more 
                   7961:                                   than one line might contain bubbles, e.g.
                   7962:                                   bubbling of: line 1 - J, line 2 - J, 
                   7963:                                   line 3 - B would assign 22 points.  
1.497     foxr     7964: 
                   7965: =cut
                   7966: 
                   7967: sub prompt_for_corrections {
1.691     raeburn  7968:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7969:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7970:     my ($current_line,$lines);
                   7971:     my @linenums;
                   7972:     my $questionnum = $question;
1.691     raeburn  7973:     my ($first,$responsenum);
1.503     raeburn  7974:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7975:         $question = $1;
                   7976:         my $subquestion = $2;
1.691     raeburn  7977:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7978:             $responsenum = $respnumlookup->{$question-1};
                   7979:             if (ref($startline) eq 'HASH') {
                   7980:                 $first = $startline->{$question-1};
                   7981:             }
                   7982:         } else {
                   7983:             $responsenum = $question-1;
1.714     raeburn  7984:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7985:         }
                   7986:         $current_line = $first + 1 ;
                   7987:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7988:         my $subcount = 1;
                   7989:         while ($subcount<$subquestion) {
                   7990:             $current_line += $subans[$subcount-1];
                   7991:             $subcount ++;
                   7992:         }
                   7993:         $lines = $subans[$subquestion-1];
                   7994:     } else {
1.691     raeburn  7995:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7996:             $responsenum = $respnumlookup->{$question-1};
                   7997:             if (ref($startline) eq 'HASH') { 
                   7998:                 $first = $startline->{$question-1};
                   7999:             }
                   8000:         } else {
                   8001:             $responsenum = $question-1;
                   8002:             $first = $first_bubble_line{$responsenum};
                   8003:         }
                   8004:         $current_line = $first + 1;
                   8005:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8006:     }
1.497     foxr     8007:     if ($lines > 1) {
1.503     raeburn  8008:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8009:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8010:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8011:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8012:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8013:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8014:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8015:             $r->print(
                   8016:                 &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)
                   8017:                .'<br /><br />'
                   8018:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8019:                .'<br />'
                   8020:                .&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.')
                   8021:                .'<br />'
                   8022:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8023:                .'<br /><br />'
                   8024:             );
1.503     raeburn  8025:         } else {
                   8026:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8027:         }
1.497     foxr     8028:     }
                   8029:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8030:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8031: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8032: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8033:         push(@linenums,$current_line);
1.497     foxr     8034: 	$current_line++;
                   8035:     }
                   8036:     if ($lines > 1) {
                   8037: 	$r->print("<hr /><br />");
                   8038:     }
1.503     raeburn  8039:     return @linenums;
1.157     albertel 8040: }
1.423     albertel 8041: 
                   8042: =pod
                   8043: 
                   8044: =item scantron_bubble_selector
                   8045:   
                   8046:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8047:    possibly showing the existing the selected bubbles if known
1.423     albertel 8048: 
                   8049:  Arguments:
                   8050:     $r           - Apache request object
1.754     raeburn  8051:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8052:     $line        - Number of the line being displayed.
1.503     raeburn  8053:     $questionnum - Question number (may include subquestion)
                   8054:     $error       - Type of error.
1.497     foxr     8055:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8056: 
                   8057: =cut
                   8058: 
1.157     albertel 8059: sub scantron_bubble_selector {
1.503     raeburn  8060:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8061:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8062: 
                   8063:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8064:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8065:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8066:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8067:             $max=$$scan_config{'BubblesPerRow'};
                   8068:             if (($scmode eq 'number') && ($max > 10)) {
                   8069:                 $max = 10;
                   8070:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8071:                 $max = 26;
                   8072:             }
                   8073:         } else {
                   8074:             $max = 10;
                   8075:         }
                   8076:     }
1.274     albertel 8077: 
1.157     albertel 8078:     my @alphabet=('A'..'Z');
1.503     raeburn  8079:     $r->print(&Apache::loncommon::start_data_table().
                   8080:               &Apache::loncommon::start_data_table_row());
                   8081:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8082:     for (my $i=0;$i<$max+1;$i++) {
                   8083: 	$r->print("\n".'<td align="center">');
                   8084: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8085: 	else { $r->print('&nbsp;'); }
                   8086: 	$r->print('</td>');
                   8087:     }
1.503     raeburn  8088:     $r->print(&Apache::loncommon::end_data_table_row().
                   8089:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8090:     for (my $i=0;$i<$max;$i++) {
                   8091: 	$r->print("\n".
                   8092: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8093: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8094:     }
1.503     raeburn  8095:     my $nobub_checked = ' ';
                   8096:     if ($error eq 'missingbubble') {
                   8097:         $nobub_checked = ' checked = "checked" ';
                   8098:     }
                   8099:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8100: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8101:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8102:               $line.'" value="'.$questionnum.'" /></td>');
                   8103:     $r->print(&Apache::loncommon::end_data_table_row().
                   8104:               &Apache::loncommon::end_data_table());
1.157     albertel 8105: }
                   8106: 
1.423     albertel 8107: =pod
                   8108: 
                   8109: =item num_matches
                   8110: 
1.424     albertel 8111:    Counts the number of characters that are the same between the two arguments.
                   8112: 
                   8113:  Arguments:
                   8114:    $orig - CODE from the scanline
                   8115:    $code - CODE to match against
                   8116: 
                   8117:  Returns:
                   8118:    $count - integer count of the number of same characters between the
                   8119:             two arguments
                   8120: 
1.423     albertel 8121: =cut
                   8122: 
1.194     albertel 8123: sub num_matches {
                   8124:     my ($orig,$code) = @_;
                   8125:     my @code=split(//,$code);
                   8126:     my @orig=split(//,$orig);
                   8127:     my $same=0;
                   8128:     for (my $i=0;$i<scalar(@code);$i++) {
                   8129: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8130:     }
                   8131:     return $same;
                   8132: }
                   8133: 
1.423     albertel 8134: =pod
                   8135: 
                   8136: =item scantron_get_closely_matching_CODEs
                   8137: 
1.424     albertel 8138:    Cycles through all CODEs and finds the set that has the greatest
                   8139:    number of same characters as the provided CODE
                   8140: 
                   8141:  Arguments:
                   8142:    $allcodes - hash ref returned by &get_codes()
                   8143:    $CODE     - CODE from the current scanline
                   8144: 
                   8145:  Returns:
                   8146:    2 element list
                   8147:     - first elements is number of how closely matching the best fit is 
                   8148:       (5 means best set has 5 matching characters)
                   8149:     - second element is an arrary ref containing the set of valid CODEs
                   8150:       that best fit the passed in CODE
                   8151: 
1.423     albertel 8152: =cut
                   8153: 
1.194     albertel 8154: sub scantron_get_closely_matching_CODEs {
                   8155:     my ($allcodes,$CODE)=@_;
                   8156:     my @CODEs;
                   8157:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8158: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8159:     }
                   8160: 
                   8161:     return ($#CODEs,$CODEs[-1]);
                   8162: }
                   8163: 
1.423     albertel 8164: =pod
                   8165: 
                   8166: =item get_codes
                   8167: 
1.424     albertel 8168:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8169:    set of remembered CODEs.
                   8170: 
                   8171:  Arguments:
                   8172:   $old_name - name of the set of remembered CODEs
                   8173:   $cdom     - domain of the course
                   8174:   $cnum     - internal course name
                   8175: 
                   8176:  Returns:
                   8177:   %allcodes - keys are the valid CODEs, values are all 1
                   8178: 
1.423     albertel 8179: =cut
                   8180: 
1.194     albertel 8181: sub get_codes {
1.280     foxr     8182:     my ($old_name, $cdom, $cnum) = @_;
                   8183:     if (!$old_name) {
                   8184: 	$old_name=$env{'form.scantron_CODElist'};
                   8185:     }
                   8186:     if (!$cdom) {
                   8187: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8188:     }
                   8189:     if (!$cnum) {
                   8190: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8191:     }
1.278     albertel 8192:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8193: 				    $cdom,$cnum);
                   8194:     my %allcodes;
                   8195:     if ($result{"type\0$old_name"} eq 'number') {
                   8196: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8197:     } else {
                   8198: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8199:     }
1.194     albertel 8200:     return %allcodes;
                   8201: }
                   8202: 
1.423     albertel 8203: =pod
                   8204: 
                   8205: =item scantron_validate_CODE
                   8206: 
1.424     albertel 8207:    Validates all scanlines in the selected file to not have any
                   8208:    invalid or underspecified CODEs and that none of the codes are
                   8209:    duplicated if this was requested.
                   8210: 
1.423     albertel 8211: =cut
                   8212: 
1.157     albertel 8213: sub scantron_validate_CODE {
                   8214:     my ($r,$currentphase) = @_;
1.754     raeburn  8215:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8216:     if ($scantron_config{'CODElocation'} &&
                   8217: 	$scantron_config{'CODEstart'} &&
                   8218: 	$scantron_config{'CODElength'}) {
1.257     albertel 8219: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8220: 	    &FIXME_blow_up()
                   8221: 	}
                   8222:     } else {
                   8223: 	return (0,$currentphase+1);
                   8224:     }
                   8225:     
                   8226:     my %usedCODEs;
                   8227: 
1.194     albertel 8228:     my %allcodes=&get_codes();
1.186     albertel 8229: 
1.582     raeburn  8230:     my $nav_error;
1.649     raeburn  8231:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8232:     if ($nav_error) {
                   8233:         $r->print(&navmap_errormsg());
                   8234:         return(1,$currentphase);
                   8235:     }
1.447     foxr     8236: 
1.186     albertel 8237:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8238:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8239: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8240: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8241: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8242: 						 $scan_data);
                   8243: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8244: 	my $error=0;
1.224     albertel 8245: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8246: 	    &scantron_get_correction($r,$i,$scan_record,
                   8247: 				     \%scantron_config,
                   8248: 				     $line,'incorrectCODE',\%allcodes);
                   8249: 	    return(1,$currentphase);
                   8250: 	}
1.221     albertel 8251: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8252: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8253: 	    &scantron_get_correction($r,$i,$scan_record,
                   8254: 				     \%scantron_config,
1.194     albertel 8255: 				     $line,'incorrectCODE',\%allcodes);
                   8256: 	    return(1,$currentphase);
1.186     albertel 8257: 	}
1.214     albertel 8258: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8259: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8260: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8261: 	    &scantron_get_correction($r,$i,$scan_record,
                   8262: 				     \%scantron_config,
1.194     albertel 8263: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8264: 	    return(1,$currentphase);
1.186     albertel 8265: 	}
1.524     raeburn  8266: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8267:     }
1.157     albertel 8268:     return (0,$currentphase+1);
                   8269: }
                   8270: 
1.423     albertel 8271: =pod
                   8272: 
                   8273: =item scantron_validate_doublebubble
                   8274: 
1.424     albertel 8275:    Validates all scanlines in the selected file to not have any
                   8276:    bubble lines with multiple bubbles marked.
                   8277: 
1.423     albertel 8278: =cut
                   8279: 
1.157     albertel 8280: sub scantron_validate_doublebubble {
                   8281:     my ($r,$currentphase) = @_;
                   8282:     #get student info
                   8283:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8284:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8285:     my (undef,undef,$sequence)=
                   8286:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8287: 
                   8288:     #get scantron line setup
1.754     raeburn  8289:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8290:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8291: 
                   8292:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8293:     unless (ref($navmap)) {
                   8294:         $r->print(&navmap_errormsg());
                   8295:         return(1,$currentphase);
                   8296:     }
                   8297:     my $map=$navmap->getResourceByUrl($sequence);
                   8298:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8299:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8300:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8301:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8302: 
1.583     raeburn  8303:     my $nav_error;
1.691     raeburn  8304:     if (ref($map)) {
                   8305:         $randomorder = $map->randomorder();
                   8306:         $randompick = $map->randompick();
                   8307:         if ($randomorder || $randompick) {
                   8308:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8309:             if ($nav_error) {
                   8310:                 $r->print(&navmap_errormsg());
                   8311:                 return(1,$currentphase);
                   8312:             }
                   8313:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8314:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8315:         }
                   8316:     } else {
                   8317:         $r->print(&navmap_errormsg());
                   8318:         return(1,$currentphase);
                   8319:     }
                   8320: 
1.649     raeburn  8321:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8322:     if ($nav_error) {
                   8323:         $r->print(&navmap_errormsg());
                   8324:         return(1,$currentphase);
                   8325:     }
1.447     foxr     8326: 
1.157     albertel 8327:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8328: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8329: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8330: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8331: 						 $scan_data,undef,\%idmap,$randomorder,
                   8332:                                                  $randompick,$sequence,\@master_seq,
                   8333:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8334:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8335: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8336: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8337: 				 'doublebubble',
1.691     raeburn  8338: 				 $$scan_record{'scantron.doubleerror'},
                   8339:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8340:     	return (1,$currentphase);
                   8341:     }
                   8342:     return (0,$currentphase+1);
                   8343: }
                   8344: 
1.423     albertel 8345: 
1.503     raeburn  8346: sub scantron_get_maxbubble {
1.649     raeburn  8347:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8348:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8349: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8350: 	&restore_bubble_lines();
1.257     albertel 8351: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8352:     }
1.330     albertel 8353: 
1.447     foxr     8354:     my (undef, undef, $sequence) =
1.257     albertel 8355: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8356: 
1.447     foxr     8357:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8358:     unless (ref($navmap)) {
                   8359:         if (ref($nav_error)) {
                   8360:             $$nav_error = 1;
                   8361:         }
1.591     raeburn  8362:         return;
1.582     raeburn  8363:     }
1.191     albertel 8364:     my $map=$navmap->getResourceByUrl($sequence);
                   8365:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8366:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8367: 
                   8368:     &Apache::lonxml::clear_problem_counter();
                   8369: 
1.557     raeburn  8370:     my $uname       = $env{'user.name'};
                   8371:     my $udom        = $env{'user.domain'};
1.435     foxr     8372:     my $cid         = $env{'request.course.id'};
                   8373:     my $total_lines = 0;
                   8374:     %bubble_lines_per_response = ();
1.447     foxr     8375:     %first_bubble_line         = ();
1.503     raeburn  8376:     %subdivided_bubble_lines   = ();
                   8377:     %responsetype_per_response = ();
1.691     raeburn  8378:     %masterseq_id_responsenum  = ();
1.554     raeburn  8379: 
1.447     foxr     8380:     my $response_number = 0;
                   8381:     my $bubble_line     = 0;
1.191     albertel 8382:     foreach my $resource (@resources) {
1.691     raeburn  8383:         my $resid = $resource->id(); 
1.672     raeburn  8384:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8385:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8386:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8387: 	    foreach my $part_id (@{$parts}) {
                   8388:                 my $lines;
                   8389: 
                   8390: 	        # TODO - make this a persistent hash not an array.
                   8391: 
                   8392:                 # optionresponse, matchresponse and rankresponse type items 
                   8393:                 # render as separate sub-questions in exam mode.
                   8394:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8395:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8396:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8397:                     my ($numbub,$numshown);
                   8398:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8399:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8400:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8401:                         }
                   8402:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8403:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8404:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8405:                         }
                   8406:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8407:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8408:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8409:                         }
                   8410:                     }
                   8411:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8412:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8413:                     }
1.649     raeburn  8414:                     my $bubbles_per_row =
                   8415:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8416:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8417:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8418:                         $inner_bubble_lines++;
                   8419:                     }
                   8420:                     for (my $i=0; $i<$numshown; $i++) {
                   8421:                         $subdivided_bubble_lines{$response_number} .= 
                   8422:                             $inner_bubble_lines.',';
                   8423:                     }
                   8424:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8425:                     $lines = $numshown * $inner_bubble_lines;
                   8426:                 } else {
                   8427:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8428:                 }
1.542     raeburn  8429: 
                   8430:                 $first_bubble_line{$response_number} = $bubble_line;
                   8431: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8432:                 $responsetype_per_response{$response_number} = 
                   8433:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8434:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8435: 	        $response_number++;
                   8436: 
                   8437: 	        $bubble_line +=  $lines;
                   8438: 	        $total_lines +=  $lines;
                   8439: 	    }
                   8440:         }
                   8441:     }
1.552     raeburn  8442:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8443: 
                   8444:     &save_bubble_lines();
                   8445:     $env{'form.scantron_maxbubble'} =
                   8446: 	$total_lines;
                   8447:     return $env{'form.scantron_maxbubble'};
                   8448: }
1.523     raeburn  8449: 
1.649     raeburn  8450: sub bubblesheet_bubbles_per_row {
                   8451:     my ($scantron_config) = @_;
                   8452:     my $bubbles_per_row;
                   8453:     if (ref($scantron_config) eq 'HASH') {
                   8454:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8455:     }
                   8456:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8457:         $bubbles_per_row = 10;
                   8458:     }
                   8459:     return $bubbles_per_row;
                   8460: }
                   8461: 
1.157     albertel 8462: sub scantron_validate_missingbubbles {
                   8463:     my ($r,$currentphase) = @_;
                   8464:     #get student info
                   8465:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8466:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8467:     my (undef,undef,$sequence)=
                   8468:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8469: 
                   8470:     #get scantron line setup
1.754     raeburn  8471:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8472:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8473: 
                   8474:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8475:     unless (ref($navmap)) {
                   8476:         $r->print(&navmap_errormsg());
                   8477:         return(1,$currentphase);
                   8478:     }
                   8479: 
                   8480:     my $map=$navmap->getResourceByUrl($sequence);
                   8481:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8482:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8483:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8484:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8485: 
1.582     raeburn  8486:     my $nav_error;
1.691     raeburn  8487:     if (ref($map)) {
                   8488:         $randomorder = $map->randomorder();
                   8489:         $randompick = $map->randompick();
                   8490:         if ($randomorder || $randompick) {
                   8491:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8492:             if ($nav_error) {
                   8493:                 $r->print(&navmap_errormsg());
                   8494:                 return(1,$currentphase);
                   8495:             }
                   8496:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8497:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8498:         }
                   8499:     } else {
                   8500:         $r->print(&navmap_errormsg());
                   8501:         return(1,$currentphase);
                   8502:     }
                   8503: 
                   8504: 
1.649     raeburn  8505:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8506:     if ($nav_error) {
1.691     raeburn  8507:         $r->print(&navmap_errormsg());
1.693     raeburn  8508:         return(1,$currentphase);
1.582     raeburn  8509:     }
1.691     raeburn  8510: 
1.157     albertel 8511:     if (!$max_bubble) { $max_bubble=2**31; }
                   8512:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8513: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8514: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8515: 	my $scan_record =
                   8516:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8517: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8518:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8519:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8520: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8521: 	my @to_correct;
1.470     foxr     8522: 	
                   8523: 	# Probably here's where the error is...
                   8524: 
1.157     albertel 8525: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8526:             my $lastbubble;
                   8527:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8528:                my $question = $1;
                   8529:                my $subquestion = $2;
1.691     raeburn  8530:                my ($first,$responsenum);
                   8531:                if ($randomorder || $randompick) {
                   8532:                    $responsenum = $respnumlookup{$question-1};
                   8533:                    $first = $startline{$question-1};
                   8534:                } else {
                   8535:                    $responsenum = $question-1; 
                   8536:                    $first = $first_bubble_line{$responsenum};
                   8537:                }
                   8538:                if (!defined($first)) { next; }
                   8539:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8540:                my $subcount = 1;
                   8541:                while ($subcount<$subquestion) {
                   8542:                    $first += $subans[$subcount-1];
                   8543:                    $subcount ++;
                   8544:                }
                   8545:                my $count = $subans[$subquestion-1];
                   8546:                $lastbubble = $first + $count;
                   8547:             } else {
1.691     raeburn  8548:                my ($first,$responsenum);
                   8549:                if ($randomorder || $randompick) {
                   8550:                    $responsenum = $respnumlookup{$missing-1};
                   8551:                    $first = $startline{$missing-1};
                   8552:                } else {
                   8553:                    $responsenum = $missing-1;
                   8554:                    $first = $first_bubble_line{$responsenum};
                   8555:                }
                   8556:                if (!defined($first)) { next; }
                   8557:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8558:             }
                   8559:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8560: 	    push(@to_correct,$missing);
                   8561: 	}
                   8562: 	if (@to_correct) {
                   8563: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8564: 				     $line,'missingbubble',\@to_correct,
                   8565:                                      $randomorder,$randompick,\%respnumlookup,
                   8566:                                      \%startline);
1.157     albertel 8567: 	    return (1,$currentphase);
                   8568: 	}
                   8569: 
                   8570:     }
                   8571:     return (0,$currentphase+1);
                   8572: }
                   8573: 
1.663     raeburn  8574: sub hand_bubble_option {
                   8575:     my (undef, undef, $sequence) =
                   8576:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8577:     return if ($sequence eq '');
                   8578:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8579:     unless (ref($navmap)) {
                   8580:         return;
                   8581:     }
                   8582:     my $needs_hand_bubbles;
                   8583:     my $map=$navmap->getResourceByUrl($sequence);
                   8584:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8585:     foreach my $res (@resources) {
                   8586:         if (ref($res)) {
                   8587:             if ($res->is_problem()) {
                   8588:                 my $partlist = $res->parts();
                   8589:                 foreach my $part (@{ $partlist }) {
                   8590:                     my @types = $res->responseType($part);
                   8591:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8592:                         $needs_hand_bubbles = 1;
                   8593:                         last;
                   8594:                     }
                   8595:                 }
                   8596:             }
                   8597:         }
                   8598:     }
                   8599:     if ($needs_hand_bubbles) {
1.754     raeburn  8600:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8601:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8602:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8603:                &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 />').
                   8604:                '<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  8605:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8606:     }
                   8607:     return;
                   8608: }
1.423     albertel 8609: 
1.82      albertel 8610: sub scantron_process_students {
1.608     www      8611:     my ($r,$symb) = @_;
1.513     foxr     8612: 
1.257     albertel 8613:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8614:     if (!$symb) {
                   8615: 	return '';
                   8616:     }
1.324     albertel 8617:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8618: 
1.754     raeburn  8619:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8620:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8621:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8622:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8623:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8624:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8625:     unless (ref($navmap)) {
                   8626:         $r->print(&navmap_errormsg());
                   8627:         return '';
1.691     raeburn  8628:     }
1.83      albertel 8629:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8630:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8631:         %grader_randomlists_by_symb);
1.677     raeburn  8632:     if (ref($map)) {
                   8633:         $randomorder = $map->randomorder();
1.689     raeburn  8634:         $randompick = $map->randompick();
1.691     raeburn  8635:     } else {
                   8636:         $r->print(&navmap_errormsg());
                   8637:         return '';
1.677     raeburn  8638:     }
1.691     raeburn  8639:     my $nav_error;
1.83      albertel 8640:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8641:     if ($randomorder || $randompick) {
                   8642:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8643:         if ($nav_error) {
                   8644:             $r->print(&navmap_errormsg());
                   8645:             return '';
                   8646:         }
                   8647:     }
1.557     raeburn  8648:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8649:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8650: 
1.554     raeburn  8651:     my ($uname,$udom);
1.82      albertel 8652:     my $result= <<SCANTRONFORM;
1.81      albertel 8653: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8654:   <input type="hidden" name="command" value="scantron_configphase" />
                   8655:   $default_form_data
                   8656: SCANTRONFORM
1.82      albertel 8657:     $r->print($result);
                   8658: 
                   8659:     my @delayqueue;
1.542     raeburn  8660:     my (%completedstudents,%scandata);
1.140     albertel 8661:     
1.520     www      8662:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8663:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8664:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8665:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8666:     $r->print('<br />');
1.140     albertel 8667:     my $start=&Time::HiRes::time();
1.158     albertel 8668:     my $i=-1;
1.542     raeburn  8669:     my $started;
1.447     foxr     8670: 
1.649     raeburn  8671:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8672:     if ($nav_error) {
                   8673:         $r->print(&navmap_errormsg());
                   8674:         return '';
                   8675:     }
                   8676: 
1.513     foxr     8677:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8678:     # the user and return.
                   8679: 
                   8680:     if ($ssi_error) {
                   8681: 	$r->print("</form>");
                   8682: 	&ssi_print_error($r);
1.520     www      8683:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8684: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8685:     }
1.447     foxr     8686: 
1.755     raeburn  8687:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8688:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8689:     my %orderedforcode;
1.542     raeburn  8690: 
1.157     albertel 8691:     while ($i<$scanlines->{'count'}) {
                   8692:  	($uname,$udom)=('','');
                   8693:  	$i++;
1.200     albertel 8694:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8695:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8696: 	if ($started) {
1.667     www      8697: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8698: 	}
                   8699: 	$started=1;
1.691     raeburn  8700:         my %respnumlookup = ();
                   8701:         my %startline = ();
                   8702:         my $total;
1.157     albertel 8703:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8704:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8705:                                                  $randompick,$sequence,\@master_seq,
                   8706:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8707:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8708:                                                  \$total);
1.157     albertel 8709:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8710:  					      \%idmap,$i)) {
                   8711:   	    &scantron_add_delay(\@delayqueue,$line,
                   8712:  				'Unable to find a student that matches',1);
                   8713:  	    next;
                   8714:   	}
                   8715:  	if (exists $completedstudents{$uname}) {
                   8716:  	    &scantron_add_delay(\@delayqueue,$line,
                   8717:  				'Student '.$uname.' has multiple sheets',2);
                   8718:  	    next;
                   8719:  	}
1.677     raeburn  8720:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8721:         my $user = $uname.':'.$usec;
1.157     albertel 8722:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8723: 
1.677     raeburn  8724:         my $scancode;
                   8725:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8726:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8727:             $scancode = $scan_record->{'scantron.CODE'};
                   8728:         } else {
                   8729:             $scancode = '';
                   8730:         }
                   8731: 
                   8732:         my @mapresources = @resources;
1.689     raeburn  8733:         if ($randomorder || $randompick) {
1.678     raeburn  8734:             @mapresources = 
1.691     raeburn  8735:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8736:                              \%orderedforcode);
1.677     raeburn  8737:         }
1.586     raeburn  8738:         my (%partids_by_symb,$res_error);
1.677     raeburn  8739:         foreach my $resource (@mapresources) {
1.586     raeburn  8740:             my $ressymb;
                   8741:             if (ref($resource)) {
                   8742:                 $ressymb = $resource->symb();
                   8743:             } else {
                   8744:                 $res_error = 1;
                   8745:                 last;
                   8746:             }
1.557     raeburn  8747:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8748:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8749:                 my $currcode;
                   8750:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8751:                     $currcode = $scancode;
                   8752:                 }
1.557     raeburn  8753:                 my ($analysis,$parts) =
1.672     raeburn  8754:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8755:                                               $uname,$udom,undef,$bubbles_per_row,
                   8756:                                               $currcode);
1.557     raeburn  8757:                 $partids_by_symb{$ressymb} = $parts;
                   8758:             } else {
                   8759:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8760:             }
1.554     raeburn  8761:         }
                   8762: 
1.586     raeburn  8763:         if ($res_error) {
                   8764:             &scantron_add_delay(\@delayqueue,$line,
                   8765:                                 'An error occurred while grading student '.$uname,2);
                   8766:             next;
                   8767:         }
                   8768: 
1.330     albertel 8769: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8770:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8771: 
                   8772: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8773: 	    &scantron_putfile($scanlines,$scan_data);
                   8774: 	}
1.161     albertel 8775: 	
1.542     raeburn  8776:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8777:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8778:                                    $bubbles_per_row,$randomorder,$randompick,
                   8779:                                    \%respnumlookup,\%startline) 
                   8780:             eq 'ssi_error') {
1.542     raeburn  8781:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8782:             $r->print("</form>");
                   8783:             &ssi_print_error($r);
                   8784:             &Apache::lonnet::remove_lock($lock);
                   8785:             return '';      # Why return ''?  Beats me.
                   8786:         }
1.513     foxr     8787: 
1.692     raeburn  8788:         if (($scancode) && ($randomorder || $randompick)) {
                   8789:             my $parmresult =
                   8790:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8791:                                                        '0_examcode',2,$scancode,
                   8792:                                                        'string_examcode',$uname,
                   8793:                                                        $udom);
                   8794:         }
1.140     albertel 8795: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8796:         if ($env{'form.verifyrecord'}) {
                   8797:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8798:             if ($randompick) {
                   8799:                 if ($total) {
                   8800:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8801:                 }
                   8802:             }
                   8803: 
1.542     raeburn  8804:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8805:             chomp($studentdata);
                   8806:             $studentdata =~ s/\r$//;
                   8807:             my $studentrecord = '';
                   8808:             my $counter = -1;
1.677     raeburn  8809:             foreach my $resource (@mapresources) {
1.554     raeburn  8810:                 my $ressymb = $resource->symb();
1.542     raeburn  8811:                 ($counter,my $recording) =
                   8812:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8813:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8814:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8815:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8816:                 $studentrecord .= $recording;
                   8817:             }
                   8818:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8819:                 &Apache::lonxml::clear_problem_counter();
                   8820:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8821:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8822:                                            $bubbles_per_row,$randomorder,$randompick,
                   8823:                                            \%respnumlookup,\%startline) 
                   8824:                     eq 'ssi_error') {
1.554     raeburn  8825:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8826:                     $r->print("</form>");
                   8827:                     &ssi_print_error($r);
                   8828:                     &Apache::lonnet::remove_lock($lock);
                   8829:                     delete($completedstudents{$uname});
                   8830:                     return '';
                   8831:                 }
1.542     raeburn  8832:                 $counter = -1;
                   8833:                 $studentrecord = '';
1.677     raeburn  8834:                 foreach my $resource (@mapresources) {
1.554     raeburn  8835:                     my $ressymb = $resource->symb();
1.542     raeburn  8836:                     ($counter,my $recording) =
                   8837:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8838:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8839:                                                  \%scantron_config,\%lettdig,$numletts,
                   8840:                                                  $randomorder,$randompick,\%respnumlookup,
                   8841:                                                  \%startline);
1.542     raeburn  8842:                     $studentrecord .= $recording;
                   8843:                 }
                   8844:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8845:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8846:                     if ($scancode eq '') {
1.658     bisitz   8847:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8848:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8849:                     } else {
1.658     bisitz   8850:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8851:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8852:                     }
                   8853:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8854:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8855:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8856:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8857:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8858:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8859:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8860:                               &Apache::loncommon::end_data_table_row().
                   8861:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8862:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8863:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8864:                               &Apache::loncommon::end_data_table_row().
                   8865:                               &Apache::loncommon::end_data_table().'</p>');
                   8866:                 } else {
                   8867:                     $r->print('<br /><span class="LC_warning">'.
                   8868:                              &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 />'.
                   8869:                              &mt("As a consequence, this user's submission history records two tries.").
                   8870:                                  '</span><br />');
                   8871:                 }
                   8872:             }
                   8873:         }
1.543     raeburn  8874:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8875:     } continue {
1.330     albertel 8876: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8877: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8878:     }
1.140     albertel 8879:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8880:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8881: #    my $lasttime = &Time::HiRes::time()-$start;
                   8882: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8883: 
1.200     albertel 8884:     $r->print("</form>");
1.157     albertel 8885:     return '';
1.75      albertel 8886: }
1.157     albertel 8887: 
1.557     raeburn  8888: sub graders_resources_pass {
1.649     raeburn  8889:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8890:         $bubbles_per_row) = @_;
1.557     raeburn  8891:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8892:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8893:         foreach my $resource (@{$resources}) {
                   8894:             my $ressymb = $resource->symb();
                   8895:             my ($analysis,$parts) =
                   8896:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8897:                                           $env{'user.name'},$env{'user.domain'},
                   8898:                                           1,$bubbles_per_row);
1.557     raeburn  8899:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8900:             if (ref($analysis) eq 'HASH') {
                   8901:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8902:                     $grader_randomlists_by_symb->{$ressymb} =
                   8903:                         $analysis->{'parts_withrandomlist'};
                   8904:                 }
                   8905:             }
                   8906:         }
                   8907:     }
                   8908:     return;
                   8909: }
                   8910: 
1.678     raeburn  8911: =pod
                   8912: 
                   8913: =item users_order
                   8914: 
                   8915:   Returns array of resources in current map, ordered based on either CODE,
                   8916:   if this is a CODEd exam, or based on student's identity if this is a 
                   8917:   "NAMEd" exam.
                   8918: 
1.691     raeburn  8919:   Should be used when randomorder and/or randompick applied when the 
                   8920:   corresponding exam was printed, prior to students completing bubblesheets 
                   8921:   for the version of the exam the student received.
1.678     raeburn  8922: 
                   8923: =cut
                   8924: 
                   8925: sub users_order  {
1.691     raeburn  8926:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8927:     my @mapresources;
1.691     raeburn  8928:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8929:         return @mapresources;
1.691     raeburn  8930:     }
                   8931:     if ($scancode) {
                   8932:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8933:             @mapresources = @{$orderedforcode->{$scancode}};
                   8934:         } else {
                   8935:             $env{'form.CODE'} = $scancode;
                   8936:             my $actual_seq =
                   8937:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8938:                                                                $master_seq,
                   8939:                                                                $user,$scancode,1);
                   8940:             if (ref($actual_seq) eq 'ARRAY') {
                   8941:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8942:                 if (ref($orderedforcode) eq 'HASH') {
                   8943:                     if (@mapresources > 0) { 
                   8944:                         $orderedforcode->{$scancode} = \@mapresources;
                   8945:                     }
                   8946:                 }
                   8947:             }
                   8948:             delete($env{'form.CODE'});
1.678     raeburn  8949:         }
                   8950:     } else {
                   8951:         my $actual_seq =
                   8952:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8953:                                                            $master_seq,
1.688     raeburn  8954:                                                            $user,undef,1);
1.678     raeburn  8955:         if (ref($actual_seq) eq 'ARRAY') {
                   8956:             @mapresources = 
                   8957:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8958:         }
1.691     raeburn  8959:     }
                   8960:     return @mapresources;
1.678     raeburn  8961: }
                   8962: 
1.542     raeburn  8963: sub grade_student_bubbles {
1.691     raeburn  8964:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8965:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8966:     my $uselookup = 0;
                   8967:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8968:         (ref($startline) eq 'HASH')) {
                   8969:         $uselookup = 1;
                   8970:     }
                   8971: 
1.554     raeburn  8972:     if (ref($resources) eq 'ARRAY') {
                   8973:         my $count = 0;
                   8974:         foreach my $resource (@{$resources}) {
                   8975:             my $ressymb = $resource->symb();
                   8976:             my %form = ('submitted'      => 'scantron',
                   8977:                         'grade_target'   => 'grade',
                   8978:                         'grade_username' => $uname,
                   8979:                         'grade_domain'   => $udom,
                   8980:                         'grade_courseid' => $env{'request.course.id'},
                   8981:                         'grade_symb'     => $ressymb,
                   8982:                         'CODE'           => $scancode
                   8983:                        );
1.649     raeburn  8984:             if ($bubbles_per_row ne '') {
                   8985:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8986:             }
1.663     raeburn  8987:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8988:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8989:             }
1.554     raeburn  8990:             if (ref($parts) eq 'HASH') {
                   8991:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8992:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8993:                         if ($uselookup) {
                   8994:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8995:                         } else {
                   8996:                             $form{'scantron_questnum_start.'.$part} =
                   8997:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8998:                         }
1.554     raeburn  8999:                         $count++;
                   9000:                     }
                   9001:                 }
                   9002:             }
                   9003:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9004:             return 'ssi_error' if ($ssi_error);
                   9005:             last if (&Apache::loncommon::connection_aborted($r));
                   9006:         }
1.542     raeburn  9007:     }
                   9008:     return;
                   9009: }
                   9010: 
1.157     albertel 9011: sub scantron_upload_scantron_data {
1.608     www      9012:     my ($r,$symb)=@_;
1.565     raeburn  9013:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9014:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9015:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9016:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9017:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9018: 							  'domainid',
1.565     raeburn  9019: 							  'coursename',$dom);
                   9020:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9021:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9022:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9023:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9024:     &js_escape(\$nofile_alert);
1.579     raeburn  9025:     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  9026:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9027:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9028:     function checkUpload(formname) {
                   9029: 	if (formname.upfile.value == "") {
1.579     raeburn  9030: 	    alert("'.$nofile_alert.'");
1.157     albertel 9031: 	    return false;
                   9032: 	}
1.565     raeburn  9033:         if (formname.courseid.value == "") {
1.579     raeburn  9034:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9035:             return false;
                   9036:         }
1.157     albertel 9037: 	formname.submit();
                   9038:     }
1.565     raeburn  9039: 
                   9040:     function ToSyllabus() {
                   9041:         var cdom = '."'$dom'".';
                   9042:         var cnum = document.rules.courseid.value;
                   9043:         if (cdom == "" || cdom == null) {
                   9044:             return;
                   9045:         }
                   9046:         if (cnum == "" || cnum == null) {
                   9047:            return;
                   9048:         }
                   9049:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9050:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9051:         return;
                   9052:     }
                   9053: 
1.754     raeburn  9054:     '.$formatjs.'
1.597     wenzelju 9055: '));
                   9056:     $r->print('
1.648     bisitz   9057: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9058: 
1.492     albertel 9059: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9060: '.$default_form_data.
                   9061:   &Apache::lonhtmlcommon::start_pick_box().
                   9062:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9063:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9064:   &Apache::lonhtmlcommon::row_closure().
                   9065:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9066:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9067:   &Apache::lonhtmlcommon::row_closure().
                   9068:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9069:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9070:   &Apache::lonhtmlcommon::row_closure());
                   9071:     if ($formatoptions) {
                   9072:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9073:                   &Apache::lonhtmlcommon::row_closure());
                   9074:     }
                   9075:     $r->print(
1.565     raeburn  9076:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9077:   '<input type="file" name="upfile" size="50" />'.
                   9078:   &Apache::lonhtmlcommon::row_closure(1).
                   9079:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9080: 
1.492     albertel 9081: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9082: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9083: </form>
1.492     albertel 9084: ');
1.157     albertel 9085:     return '';
                   9086: }
                   9087: 
1.754     raeburn  9088: sub scantron_upload_dataformat {
                   9089:     my ($dom) = @_;
                   9090:     my ($formatoptions,$formattitle,$formatjs);
                   9091:     $formatjs = <<'END';
                   9092: function toggleScantab(form) {
                   9093:    return;
                   9094: }
                   9095: END
                   9096:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9097:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9098:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9099:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9100:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9101:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756   ! raeburn  9102:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
        !          9103:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
        !          9104:                             my ($onclick,$formatextra,$singleline);
        !          9105:                             my @lines = &Apache::lonnet::get_scantronformat_file();
        !          9106:                             my $count = 0;
        !          9107:                             foreach my $line (@lines) {
        !          9108:                                 next if ($line =~ /^#/);
        !          9109:                                 $singleline = $line;
        !          9110:                                 $count ++;
        !          9111:                             }
        !          9112:                             if ($count > 1) {
        !          9113:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
        !          9114:                                                &scantron_scantab().'</div>';
        !          9115:                                 $onclick = ' onclick="toggleScantab(this.form);"';
        !          9116:                                 $formatjs = <<"END";
1.754     raeburn  9117: function toggleScantab(form) {
                   9118:     var divid = 'bubbletype';
                   9119:     if (document.getElementById(divid)) {
                   9120:         var radioname = 'fileformat';
                   9121:         var num = form.elements[radioname].length;
                   9122:         if (num) {
                   9123:             for (var i=0; i<num; i++) {
                   9124:                 if (form.elements[radioname][i].checked) {
                   9125:                     var chosen = form.elements[radioname][i].value;
                   9126:                     if (chosen == 'dat') {
                   9127:                         document.getElementById(divid).style.display = 'none';
                   9128:                     } else if (chosen == 'csv') {
                   9129:                         document.getElementById(divid).style.display = 'inline-block';
                   9130:                     }
                   9131:                 }
                   9132:             }
                   9133:         }
                   9134:     }
                   9135:     return;
                   9136: }
                   9137: 
                   9138: END
1.756   ! raeburn  9139:                             } elsif ($count == 1) {
        !          9140:                                 my $formatname = (split(/:/,$singleline,2))[0];
        !          9141:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
        !          9142:                             }
        !          9143:                             $formattitle = &mt('File format');
        !          9144:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
        !          9145:                                              &mt('Plain Text (no delimiters)').
        !          9146:                                              '</label>'.('&nbsp;'x2).
        !          9147:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
        !          9148:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9149:                         }
                   9150:                     }
                   9151:                 }
                   9152:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756   ! raeburn  9153:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
        !          9154:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
        !          9155:                         $formattitle = &mt('Format of bubblesheet data file:');
        !          9156:                         $formatoptions = &scantron_scantab();
        !          9157:                     }
1.754     raeburn  9158:                 }
                   9159:             }
                   9160:         }
                   9161:     }
                   9162:     return ($formatoptions,$formattitle,$formatjs);
                   9163: }
1.423     albertel 9164: 
1.157     albertel 9165: sub scantron_upload_scantron_data_save {
1.608     www      9166:     my($r,$symb)=@_;
1.182     albertel 9167:     my $doanotherupload=
                   9168: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9169: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9170: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9171: 	'</form>'."\n";
1.257     albertel 9172:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9173: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9174: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9175: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9176: 	unless ($symb) {
1.182     albertel 9177: 	    $r->print($doanotherupload);
                   9178: 	}
1.162     albertel 9179: 	return '';
                   9180:     }
1.257     albertel 9181:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9182:     my $uploadedfile;
1.710     bisitz   9183:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9184:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9185:         $r->print(
                   9186:             &Apache::lonhtmlcommon::confirm_success(
                   9187:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9188:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9189:     } else {
1.754     raeburn  9190:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9191:         my $parser;
                   9192:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9193:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9194:                 my $is_csv;
                   9195:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9196:                 if (@possibles > 1) {
                   9197:                     if ($env{'form.fileformat'} eq 'csv') {
                   9198:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756   ! raeburn  9199:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
        !          9200:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
        !          9201:                                     $is_csv = 1;
        !          9202:                                 }
1.754     raeburn  9203:                             }
                   9204:                         }
                   9205:                     }
                   9206:                 } elsif (@possibles == 1) {
                   9207:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756   ! raeburn  9208:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
        !          9209:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
        !          9210:                                 $is_csv = 1;
        !          9211:                             }
1.754     raeburn  9212:                         }
                   9213:                     }
                   9214:                 }
                   9215:                 if ($is_csv) {
                   9216:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9217:                 }
                   9218:             }
                   9219:         }
                   9220:         my $result =
                   9221:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9222:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9223:         if ($result =~ m{^/uploaded/}) {
                   9224:             $r->print(
                   9225:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9226:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9227:                         (length($env{'form.upfile'})-1),
                   9228:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9229:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9230:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9231:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   9232:         } else {
                   9233:             $r->print(
                   9234:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9235:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9236:                           $result,
1.568     raeburn  9237: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9238: 	}
                   9239:     }
1.174     albertel 9240:     if ($symb) {
1.612     www      9241: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9242:     } else {
1.182     albertel 9243: 	$r->print($doanotherupload);
1.174     albertel 9244:     }
1.157     albertel 9245:     return '';
                   9246: }
                   9247: 
1.567     raeburn  9248: sub validate_uploaded_scantron_file {
                   9249:     my ($cdom,$cname,$fname) = @_;
                   9250:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9251:     my @lines;
                   9252:     if ($scanlines ne '-1') {
                   9253:         @lines=split("\n",$scanlines,-1);
                   9254:     }
                   9255:     my $output;
                   9256:     if (@lines) {
                   9257:         my (%counts,$max_match_format);
1.710     bisitz   9258:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9259:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9260:         my %idmap = &username_to_idmap($classlist);
                   9261:         foreach my $key (keys(%idmap)) {
                   9262:             my $lckey = lc($key);
                   9263:             $idmap{$lckey} = $idmap{$key};
                   9264:         }
                   9265:         my %unique_formats;
1.754     raeburn  9266:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9267:         foreach my $line (@formatlines) {
                   9268:             chomp($line);
                   9269:             my @config = split(/:/,$line);
                   9270:             my $idstart = $config[5];
                   9271:             my $idlength = $config[6];
                   9272:             if (($idstart ne '') && ($idlength > 0)) {
                   9273:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9274:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9275:                 } else {
                   9276:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9277:                 }
                   9278:             }
                   9279:         }
                   9280:         foreach my $key (keys(%unique_formats)) {
                   9281:             my ($idstart,$idlength) = split(':',$key);
                   9282:             %{$counts{$key}} = (
                   9283:                                'found'   => 0,
                   9284:                                'total'   => 0,
                   9285:                               );
                   9286:             foreach my $line (@lines) {
                   9287:                 next if ($line =~ /^#/);
                   9288:                 next if ($line =~ /^[\s\cz]*$/);
                   9289:                 my $id = substr($line,$idstart-1,$idlength);
                   9290:                 $id = lc($id);
                   9291:                 if (exists($idmap{$id})) {
                   9292:                     $counts{$key}{'found'} ++;
                   9293:                 }
                   9294:                 $counts{$key}{'total'} ++;
                   9295:             }
                   9296:             if ($counts{$key}{'total'}) {
                   9297:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9298:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9299:                     $max_match_pct = $percent_match;
                   9300:                     $max_match_format = $key;
1.710     bisitz   9301:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9302:                     $max_match_count = $counts{$key}{'total'};
                   9303:                 }
                   9304:             }
                   9305:         }
                   9306:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9307:             my $format_descs;
                   9308:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9309:             for (my $i=0; $i<$numwithformat; $i++) {
                   9310:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9311:                 if ($i<$numwithformat-2) {
                   9312:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9313:                 } elsif ($i==$numwithformat-2) {
                   9314:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9315:                 } elsif ($i==$numwithformat-1) {
                   9316:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9317:                 }
                   9318:             }
                   9319:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9320:             $output .= '<br />';
                   9321:             if ($found_match_count == $max_match_count) {
                   9322:                 # 100% matching entries
                   9323:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9324:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9325:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9326:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9327:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9328:                     ' in the file (for the format defined for [_3]).',
                   9329:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9330:             } else {
                   9331:                 # Not all entries matching? -> Show warning and additional info
                   9332:                 $output .=
                   9333:                     &Apache::lonhtmlcommon::confirm_success(
                   9334:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9335:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9336:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9337:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9338:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9339:                         ' in the file (for the format defined for [_3]).',
                   9340:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9341:                     '<p class="LC_info">'.
                   9342:                     &mt('A low percentage of matches results from one of the following:').
                   9343:                     '</p><ul>'.
                   9344:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9345:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9346:                                '<i>'.$cdom.'</i>').'</li>'.
                   9347:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9348:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9349:                     '</ul>';
                   9350:             }
1.567     raeburn  9351:         }
                   9352:     } else {
1.710     bisitz   9353:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9354:     }
                   9355:     return $output;
                   9356: }
                   9357: 
1.202     albertel 9358: sub valid_file {
                   9359:     my ($requested_file)=@_;
                   9360:     foreach my $filename (sort(&scantron_filenames())) {
                   9361: 	if ($requested_file eq $filename) { return 1; }
                   9362:     }
                   9363:     return 0;
                   9364: }
                   9365: 
                   9366: sub scantron_download_scantron_data {
1.608     www      9367:     my ($r,$symb)=@_;
                   9368:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9369:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9370:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9371:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9372:     if (! &valid_file($file)) {
1.492     albertel 9373: 	$r->print('
1.202     albertel 9374: 	<p>
1.686     bisitz   9375: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9376:         </p>
1.492     albertel 9377: ');
1.202     albertel 9378: 	return;
                   9379:     }
                   9380:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9381:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9382:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9383:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9384:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9385:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9386:     $r->print('
1.202     albertel 9387:     <p>
1.723     raeburn  9388: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9389: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9390:     </p>
                   9391:     <p>
1.492     albertel 9392: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9393: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9394:     </p>
                   9395:     <p>
1.492     albertel 9396: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9397: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9398:     </p>
1.492     albertel 9399: ');
1.202     albertel 9400:     return '';
                   9401: }
1.157     albertel 9402: 
1.523     raeburn  9403: sub checkscantron_results {
1.608     www      9404:     my ($r,$symb) = @_;
1.523     raeburn  9405:     if (!$symb) {return '';}
                   9406:     my $cid = $env{'request.course.id'};
1.755     raeburn  9407:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9408:     my $numletts = scalar(keys(%lettdig));
                   9409:     my $cnum = $env{'course.'.$cid.'.num'};
                   9410:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9411:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9412:     my %record;
                   9413:     my %scantron_config =
1.754     raeburn  9414:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9415:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9416:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9417:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9418:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9419:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9420:     unless (ref($navmap)) {
                   9421:         $r->print(&navmap_errormsg());
                   9422:         return '';
                   9423:     }
1.523     raeburn  9424:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9425:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9426:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9427:     if (ref($map)) { 
                   9428:         $randomorder=$map->randomorder();
1.689     raeburn  9429:         $randompick=$map->randompick();
1.677     raeburn  9430:     }
1.557     raeburn  9431:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9432:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9433:     if ($nav_error) {
                   9434:         $r->print(&navmap_errormsg());
                   9435:         return '';
1.678     raeburn  9436:     }
1.673     raeburn  9437:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9438:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9439:     my ($uname,$udom);
1.523     raeburn  9440:     my (%scandata,%lastname,%bylast);
                   9441:     $r->print('
                   9442: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9443: 
                   9444:     my @delayqueue;
                   9445:     my %completedstudents;
                   9446: 
1.691     raeburn  9447:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9448:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9449:     my ($username,$domain,$started);
1.649     raeburn  9450:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9451:     if ($nav_error) {
                   9452:         $r->print(&navmap_errormsg());
                   9453:         return '';
                   9454:     }
1.523     raeburn  9455: 
1.667     www      9456:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9457:     my $start=&Time::HiRes::time();
                   9458:     my $i=-1;
                   9459: 
                   9460:     while ($i<$scanlines->{'count'}) {
                   9461:         ($username,$domain,$uname)=('','','');
                   9462:         $i++;
                   9463:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9464:         if ($line=~/^[\s\cz]*$/) { next; }
                   9465:         if ($started) {
1.667     www      9466:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9467:         }
                   9468:         $started=1;
                   9469:         my $scan_record=
                   9470:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9471:                                                      $scan_data);
1.693     raeburn  9472:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9473:                                               \%idmap,$i)) {
1.523     raeburn  9474:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9475:                                 'Unable to find a student that matches',1);
                   9476:             next;
                   9477:         }
                   9478:         if (exists $completedstudents{$uname}) {
                   9479:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9480:                                 'Student '.$uname.' has multiple sheets',2);
                   9481:             next;
                   9482:         }
                   9483:         my $pid = $scan_record->{'scantron.ID'};
                   9484:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9485:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9486:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9487:         my $user = $uname.':'.$usec;
1.523     raeburn  9488:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9489: 
1.678     raeburn  9490:         my $scancode;
1.677     raeburn  9491:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9492:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9493:             $scancode = $scan_record->{'scantron.CODE'};
                   9494:         } else {
                   9495:             $scancode = '';
                   9496:         }
                   9497: 
                   9498:         my @mapresources = @resources;
1.691     raeburn  9499:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9500:         my %respnumlookup=();
                   9501:         my %startline=();
1.689     raeburn  9502:         if ($randomorder || $randompick) {
1.678     raeburn  9503:             @mapresources =
1.691     raeburn  9504:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9505:                              \%orderedforcode);
                   9506:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9507:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9508:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9509:                                              \%respnumlookup,\%startline);
                   9510:             if ($randompick && $total) {
                   9511:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9512:             }
1.677     raeburn  9513:         }
1.691     raeburn  9514:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9515:         chomp($scandata{$pid});
                   9516:         $scandata{$pid} =~ s/\r$//;
                   9517: 
1.523     raeburn  9518:         my $counter = -1;
1.677     raeburn  9519:         foreach my $resource (@mapresources) {
1.557     raeburn  9520:             my $parts;
1.554     raeburn  9521:             my $ressymb = $resource->symb();
1.557     raeburn  9522:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9523:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9524:                 my $currcode;
                   9525:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9526:                     $currcode = $scancode;
                   9527:                 }
1.557     raeburn  9528:                 (my $analysis,$parts) =
1.672     raeburn  9529:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9530:                                               $username,$domain,undef,
1.741     raeburn  9531:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9532:             } else {
                   9533:                 $parts = $grader_partids_by_symb{$ressymb};
                   9534:             }
1.542     raeburn  9535:             ($counter,my $recording) =
                   9536:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9537:                                          $scandata{$pid},$parts,
1.691     raeburn  9538:                                          \%scantron_config,\%lettdig,$numletts,
                   9539:                                          $randomorder,$randompick,
                   9540:                                          \%respnumlookup,\%startline);
1.542     raeburn  9541:             $record{$pid} .= $recording;
1.523     raeburn  9542:         }
                   9543:     }
                   9544:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9545:     $r->print('<br />');
                   9546:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9547:     $passed = 0;
                   9548:     $failed = 0;
                   9549:     $numstudents = 0;
                   9550:     foreach my $last (sort(keys(%bylast))) {
                   9551:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9552:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9553:                 my $showscandata = $scandata{$pid};
                   9554:                 my $showrecord = $record{$pid};
                   9555:                 $showscandata =~ s/\s/&nbsp;/g;
                   9556:                 $showrecord =~ s/\s/&nbsp;/g;
                   9557:                 if ($scandata{$pid} eq $record{$pid}) {
                   9558:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9559:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9560: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9561: '</tr>'."\n".
                   9562: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9563: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9564:                     $passed ++;
                   9565:                 } else {
                   9566:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9567:                     $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  9568: '</tr>'."\n".
                   9569: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9570: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9571: '</tr>'."\n";
                   9572:                     $failed ++;
                   9573:                 }
                   9574:                 $numstudents ++;
                   9575:             }
                   9576:         }
                   9577:     }
1.648     bisitz   9578:     $r->print(
                   9579:         '<p>'
                   9580:        .&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).',
                   9581:             '<b>',
                   9582:             $numstudents,
                   9583:             '</b>',
                   9584:             $env{'form.scantron_maxbubble'})
                   9585:        .'</p>'
                   9586:     );
1.682     raeburn  9587:     $r->print('<p>'
1.683     raeburn  9588:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9589:              .'<br />'
                   9590:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9591:              .'</p>'
                   9592:     );
1.523     raeburn  9593:     if ($passed) {
1.572     www      9594:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9595:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9596:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9597:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9598:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9599:                  $okstudents."\n".
                   9600:                  &Apache::loncommon::end_data_table().'<br />');
                   9601:     }
                   9602:     if ($failed) {
1.572     www      9603:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9604:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9605:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9606:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9607:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9608:                  $badstudents."\n".
                   9609:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9610:                  &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  9611:     }
1.614     www      9612:     $r->print('</form><br />');
1.523     raeburn  9613:     return;
                   9614: }
                   9615: 
1.542     raeburn  9616: sub verify_scantron_grading {
1.554     raeburn  9617:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9618:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9619:         $respnumlookup,$startline) = @_;
1.542     raeburn  9620:     my ($record,%expected,%startpos);
                   9621:     return ($counter,$record) if (!ref($resource));
                   9622:     return ($counter,$record) if (!$resource->is_problem());
                   9623:     my $symb = $resource->symb();
1.554     raeburn  9624:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9625:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9626:         $counter ++;
                   9627:         $expected{$part_id} = 0;
1.691     raeburn  9628:         my $respnum = $counter;
                   9629:         if ($randomorder || $randompick) {
                   9630:             $respnum = $respnumlookup->{$counter};
                   9631:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9632:         } else {
                   9633:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9634:         }
                   9635:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9636:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9637:             foreach my $item (@sub_lines) {
                   9638:                 $expected{$part_id} += $item;
                   9639:             }
                   9640:         } else {
1.691     raeburn  9641:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9642:         }
                   9643:     }
                   9644:     if ($symb) {
                   9645:         my %recorded;
                   9646:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9647:         if ($returnhash{'version'}) {
                   9648:             my %lasthash=();
                   9649:             my $version;
                   9650:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9651:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9652:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9653:                 }
                   9654:             }
                   9655:             foreach my $key (keys(%lasthash)) {
                   9656:                 if ($key =~ /\.scantron$/) {
                   9657:                     my $value = &unescape($lasthash{$key});
                   9658:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9659:                     if ($value eq '') {
                   9660:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9661:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9662:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9663:                             }
                   9664:                         }
                   9665:                     } else {
                   9666:                         my @tocheck;
                   9667:                         my @items = split(//,$value);
                   9668:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9669:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9670:                             if (@items < $expected{$part_id}) {
                   9671:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9672:                                 my @singles = split(//,$fragment);
                   9673:                                 foreach my $pos (@singles) {
                   9674:                                     if ($pos eq ' ') {
                   9675:                                         push(@tocheck,$pos);
                   9676:                                     } else {
                   9677:                                         my $next = shift(@items);
                   9678:                                         push(@tocheck,$next);
                   9679:                                     }
                   9680:                                 }
                   9681:                             } else {
                   9682:                                 @tocheck = @items;
                   9683:                             }
                   9684:                             foreach my $letter (@tocheck) {
                   9685:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9686:                                     if ($letter !~ /^[A-J]$/) {
                   9687:                                         $letter = $scantron_config->{'Qoff'};
                   9688:                                     }
                   9689:                                     $recorded{$part_id} .= $letter;
                   9690:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9691:                                     my $digit;
                   9692:                                     if ($letter !~ /^[A-J]$/) {
                   9693:                                         $digit = $scantron_config->{'Qoff'};
                   9694:                                     } else {
                   9695:                                         $digit = $lettdig->{$letter};
                   9696:                                     }
                   9697:                                     $recorded{$part_id} .= $digit;
                   9698:                                 }
                   9699:                             }
                   9700:                         } else {
                   9701:                             @tocheck = @items;
                   9702:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9703:                                 my $curr_sub = shift(@tocheck);
                   9704:                                 my $digit;
                   9705:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9706:                                     $digit = $lettdig->{$curr_sub}-1;
                   9707:                                 }
                   9708:                                 if ($curr_sub eq 'J') {
                   9709:                                     $digit += scalar($numletts);
                   9710:                                 }
                   9711:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9712:                                     if ($j == $digit) {
                   9713:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9714:                                     } else {
                   9715:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9716:                                     }
                   9717:                                 }
                   9718:                             }
                   9719:                         }
                   9720:                     }
                   9721:                 }
                   9722:             }
                   9723:         }
1.554     raeburn  9724:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9725:             if ($recorded{$part_id} eq '') {
                   9726:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9727:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9728:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9729:                     }
                   9730:                 }
                   9731:             }
                   9732:             $record .= $recorded{$part_id};
                   9733:         }
                   9734:     }
                   9735:     return ($counter,$record);
                   9736: }
                   9737: 
1.423     albertel 9738: 
1.75      albertel 9739: #-------- end of section for handling grading scantron forms -------
                   9740: #
                   9741: #-------------------------------------------------------------------
                   9742: 
1.72      ng       9743: #-------------------------- Menu interface -------------------------
                   9744: #
1.614     www      9745: #--- Href with symb and command ---
                   9746: 
                   9747: sub href_symb_cmd {
                   9748:     my ($symb,$cmd)=@_;
1.669     raeburn  9749:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9750: }
                   9751: 
1.443     banghart 9752: sub grading_menu {
1.608     www      9753:     my ($request,$symb) = @_;
1.443     banghart 9754:     if (!$symb) {return '';}
                   9755: 
                   9756:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9757:                   'command'=>'individual');
1.538     schulted 9758:     
1.598     www      9759:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9760: 
                   9761:     $fields{'command'}='ungraded';
                   9762:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9763: 
                   9764:     $fields{'command'}='table';
                   9765:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9766: 
                   9767:     $fields{'command'}='all_for_one';
                   9768:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9769: 
1.621     www      9770:     $fields{'command'}='downloadfilesselect';
                   9771:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9772: 
1.443     banghart 9773:     $fields{'command'} = 'csvform';
1.538     schulted 9774:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9775:     
1.443     banghart 9776:     $fields{'command'} = 'processclicker';
1.538     schulted 9777:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9778:     
1.443     banghart 9779:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9780:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9781: 
                   9782:     $fields{'command'} = 'initialverifyreceipt';
                   9783:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9784:     
1.598     www      9785:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9786:             items =>[
1.598     www      9787:                         {	linktext => 'Select individual students to grade',
                   9788:                     		url => $url1a,
1.538     schulted 9789:                     		permission => 'F',
1.636     wenzelju 9790:                     		icon => 'grade_students.png',
1.598     www      9791:                     		linktitle => 'Grade current resource for a selection of students.'
                   9792:                         }, 
                   9793:                         {       linktext => 'Grade ungraded submissions.',
                   9794:                                 url => $url1b,
                   9795:                                 permission => 'F',
1.636     wenzelju 9796:                                 icon => 'ungrade_sub.png',
1.598     www      9797:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9798:                         },
1.598     www      9799: 
                   9800:                         {       linktext => 'Grading table',
                   9801:                                 url => $url1c,
                   9802:                                 permission => 'F',
1.636     wenzelju 9803:                                 icon => 'grading_table.png',
1.598     www      9804:                                 linktitle => 'Grade current resource for all students.'
                   9805:                         },
1.615     www      9806:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9807:                                 url => $url1d,
                   9808:                                 permission => 'F',
1.636     wenzelju 9809:                                 icon => 'grade_PageFolder.png',
1.598     www      9810:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9811:                         },
                   9812:                         {       linktext => 'Download submissions',
                   9813:                                 url => $url1e,
                   9814:                                 permission => 'F',
1.636     wenzelju 9815:                                 icon => 'download_sub.png',
1.621     www      9816:                                 linktitle => 'Download all students submissions.'
1.598     www      9817:                         }]},
                   9818:                          { categorytitle=>'Automated Grading',
                   9819:                items =>[
                   9820: 
1.538     schulted 9821:                 	    {	linktext => 'Upload Scores',
                   9822:                     		url => $url2,
                   9823:                     		permission => 'F',
                   9824:                     		icon => 'uploadscores.png',
                   9825:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9826:                 	    },
                   9827:                 	    {	linktext => 'Process Clicker',
                   9828:                     		url => $url3,
                   9829:                     		permission => 'F',
                   9830:                     		icon => 'addClickerInfoFile.png',
                   9831:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9832:                 	    },
1.587     raeburn  9833:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9834:                     		url => $url4,
                   9835:                     		permission => 'F',
1.636     wenzelju 9836:                     		icon => 'bubblesheet.png',
1.648     bisitz   9837:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9838:                 	    },
1.616     www      9839:                             {   linktext => 'Verify Receipt Number',
1.602     www      9840:                                 url => $url5,
                   9841:                                 permission => 'F',
1.636     wenzelju 9842:                                 icon => 'receipt_number.png',
1.602     www      9843:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9844:                             }
                   9845: 
1.538     schulted 9846:                     ]
                   9847:             });
                   9848: 
1.443     banghart 9849:     # Create the menu
                   9850:     my $Str;
1.445     banghart 9851:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9852:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9853:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9854: 
1.602     www      9855:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9856:     return $Str;    
                   9857: }
                   9858: 
1.598     www      9859: 
                   9860: sub ungraded {
                   9861:     my ($request)=@_;
                   9862:     &submit_options($request);
                   9863: }
                   9864: 
1.599     www      9865: sub submit_options_sequence {
1.608     www      9866:     my ($request,$symb) = @_;
1.599     www      9867:     if (!$symb) {return '';}
1.600     www      9868:     &commonJSfunctions($request);
                   9869:     my $result;
1.599     www      9870: 
1.600     www      9871:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9872:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9873:     $result.=&selectfield(0).
1.601     www      9874:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9875:             <div>
                   9876:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9877:             </div>
                   9878:         </div>
                   9879:   </form>';
                   9880:     return $result;
                   9881: }
                   9882: 
                   9883: sub submit_options_table {
1.608     www      9884:     my ($request,$symb) = @_;
1.600     www      9885:     if (!$symb) {return '';}
1.599     www      9886:     &commonJSfunctions($request);
1.746     raeburn  9887:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      9888:     my $result;
                   9889: 
                   9890:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9891:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9892: 
1.745     raeburn  9893:     $result.=&selectfield(1,$is_tool).
1.601     www      9894:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9895:             <div>
                   9896:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9897:             </div>
                   9898:         </div>
                   9899:   </form>';
                   9900:     return $result;
                   9901: }
1.443     banghart 9902: 
1.621     www      9903: sub submit_options_download {
                   9904:     my ($request,$symb) = @_;
                   9905:     if (!$symb) {return '';}
                   9906: 
1.746     raeburn  9907:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      9908:     &commonJSfunctions($request);
                   9909: 
                   9910:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9911:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9912:     $result.='
                   9913: <h2>
1.750     raeburn  9914:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  9915: </h2>'.&selectfield(1,$is_tool).'
1.621     www      9916:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9917:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9918:             </div>
                   9919:           </div>
1.600     www      9920: 
                   9921: 
1.621     www      9922:   </form>';
                   9923:     return $result;
                   9924: }
                   9925: 
1.443     banghart 9926: #--- Displays the submissions first page -------
                   9927: sub submit_options {
1.608     www      9928:     my ($request,$symb) = @_;
1.72      ng       9929:     if (!$symb) {return '';}
                   9930: 
1.746     raeburn  9931:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       9932:     &commonJSfunctions($request);
1.473     albertel 9933:     my $result;
1.533     bisitz   9934: 
1.72      ng       9935:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9936: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  9937:     $result.=&selectfield(1,$is_tool).'
1.601     www      9938:                 <input type="hidden" name="command" value="submission" /> 
                   9939: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9940:             </div>
                   9941:           </div>
                   9942: 
                   9943: 
                   9944:   </form>';
                   9945:     return $result;
                   9946: }
1.533     bisitz   9947: 
1.601     www      9948: sub selectfield {
1.745     raeburn  9949:    my ($full,$is_tool)=@_;
                   9950:    my %options;
                   9951:    if ($is_tool) {
                   9952:        %options =
                   9953:            (&transtatus_options,
                   9954:             'select_form_order' => ['yes','incorrect','all']);
                   9955:    } else {
                   9956:        %options = 
                   9957:            (&substatus_options,
                   9958:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   9959:    }
1.601     www      9960:    my $result='<div class="LC_columnSection">
1.537     harmsja  9961:   
1.533     bisitz   9962:     <fieldset>
                   9963:       <legend>
                   9964:        '.&mt('Sections').'
                   9965:       </legend>
1.601     www      9966:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9967:     </fieldset>
1.537     harmsja  9968:   
1.533     bisitz   9969:     <fieldset>
                   9970:       <legend>
                   9971:         '.&mt('Groups').'
                   9972:       </legend>
                   9973:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9974:     </fieldset>
1.537     harmsja  9975:   
1.533     bisitz   9976:     <fieldset>
                   9977:       <legend>
                   9978:         '.&mt('Access Status').'
                   9979:       </legend>
1.601     www      9980:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9981:     </fieldset>';
                   9982:     if ($full) {
1.745     raeburn  9983:         my $heading = &mt('Submission Status');
                   9984:         if ($is_tool) {
                   9985:             $heading = &mt('Transaction Status');
                   9986:         }
                   9987:         $result.='
1.533     bisitz   9988:     <fieldset>
                   9989:       <legend>
1.745     raeburn  9990:         '.$heading.'
1.601     www      9991:       </legend>'.
1.635     raeburn  9992:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9993:    '</fieldset>';
                   9994:     }
                   9995:     $result.='</div><br />';
1.44      ng       9996:     return $result;
1.2       albertel 9997: }
                   9998: 
1.738     raeburn  9999: sub substatus_options {
                   10000:     return &Apache::lonlocal::texthash(
                   10001:                                       'yes'       => 'with submissions',
                   10002:                                       'queued'    => 'in grading queue',
                   10003:                                       'graded'    => 'with ungraded submissions',
                   10004:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10005:                                       'all'       => 'with any status',
                   10006:                                       );
1.738     raeburn  10007: }
                   10008: 
1.745     raeburn  10009: sub transtatus_options {
                   10010:     return &Apache::lonlocal::texthash(
                   10011:                                        'yes'       => 'with score transactions',
                   10012:                                        'incorrect' => 'with less than full credit',
                   10013:                                        'all'       => 'with any status',
                   10014:                                       );
                   10015: }
                   10016: 
1.285     albertel 10017: sub reset_perm {
                   10018:     undef(%perm);
                   10019: }
                   10020: 
                   10021: sub init_perm {
                   10022:     &reset_perm();
1.300     albertel 10023:     foreach my $test_perm ('vgr','mgr','opa') {
                   10024: 
                   10025: 	my $scope = $env{'request.course.id'};
                   10026: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10027: 
                   10028: 	    $scope .= '/'.$env{'request.course.sec'};
                   10029: 	    if ( $perm{$test_perm}=
                   10030: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10031: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10032: 	    } else {
                   10033: 		delete($perm{$test_perm});
                   10034: 	    }
1.285     albertel 10035: 	}
                   10036:     }
                   10037: }
                   10038: 
1.674     raeburn  10039: sub init_old_essays {
                   10040:     my ($symb,$apath,$adom,$aname) = @_;
                   10041:     if ($symb ne '') {
                   10042:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10043:         if (keys(%essays) > 0) {
                   10044:             $old_essays{$symb} = \%essays;
                   10045:         }
                   10046:     }
                   10047:     return;
                   10048: }
                   10049: 
                   10050: sub reset_old_essays {
                   10051:     undef(%old_essays);
                   10052: }
                   10053: 
1.400     www      10054: sub gather_clicker_ids {
1.408     albertel 10055:     my %clicker_ids;
1.400     www      10056: 
                   10057:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10058: 
                   10059:     # Set up a couple variables.
1.407     albertel 10060:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10061:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10062:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10063: 
1.407     albertel 10064:     foreach my $student (keys(%$classlist)) {
1.438     www      10065:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10066:         my $username = $classlist->{$student}->[$username_idx];
                   10067:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10068:         my $clickers =
1.408     albertel 10069: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10070:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10071:             $id=~s/^[\#0]+//;
1.421     www      10072:             $id=~s/[\-\:]//g;
1.407     albertel 10073:             if (exists($clicker_ids{$id})) {
1.408     albertel 10074: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10075:             } else {
1.408     albertel 10076: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10077:             }
                   10078:         }
                   10079:     }
1.407     albertel 10080:     return %clicker_ids;
1.400     www      10081: }
                   10082: 
1.402     www      10083: sub gather_adv_clicker_ids {
1.408     albertel 10084:     my %clicker_ids;
1.402     www      10085:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10086:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10087:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10088:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10089:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10090:             my ($puname,$pudom)=split(/\:/,$person);
                   10091:             my $clickers =
1.408     albertel 10092: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10093:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10094: 		$id=~s/^[\#0]+//;
1.421     www      10095:                 $id=~s/[\-\:]//g;
1.408     albertel 10096: 		if (exists($clicker_ids{$id})) {
                   10097: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10098: 		} else {
                   10099: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10100: 		}
1.405     www      10101:             }
1.402     www      10102:         }
                   10103:     }
1.407     albertel 10104:     return %clicker_ids;
1.402     www      10105: }
                   10106: 
1.413     www      10107: sub clicker_grading_parameters {
                   10108:     return ('gradingmechanism' => 'scalar',
                   10109:             'upfiletype' => 'scalar',
                   10110:             'specificid' => 'scalar',
                   10111:             'pcorrect' => 'scalar',
                   10112:             'pincorrect' => 'scalar');
                   10113: }
                   10114: 
1.400     www      10115: sub process_clicker {
1.608     www      10116:     my ($r,$symb)=@_;
1.400     www      10117:     if (!$symb) {return '';}
                   10118:     my $result=&checkforfile_js();
1.632     www      10119:     $result.=&Apache::loncommon::start_data_table().
                   10120:              &Apache::loncommon::start_data_table_header_row().
                   10121:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10122:              &Apache::loncommon::end_data_table_header_row().
                   10123:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10124: # Attempt to restore parameters from last session, set defaults if not present
                   10125:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10126:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10127:                                                  \%Saveable_Parameters);
                   10128:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10129:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10130:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10131:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10132: 
                   10133:     my %checked;
1.521     www      10134:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10135:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10136:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10137:        }
                   10138:     }
                   10139: 
1.632     www      10140:     my $upload=&mt("Evaluate File");
1.400     www      10141:     my $type=&mt("Type");
1.402     www      10142:     my $attendance=&mt("Award points just for participation");
                   10143:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10144:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10145:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10146:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10147:     my $pcorrect=&mt("Percentage points for correct solution");
                   10148:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10149:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10150: 						   {'iclicker' => 'i>clicker',
1.666     www      10151:                                                     'interwrite' => 'interwrite PRS',
                   10152:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10153:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10154:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10155: function sanitycheck() {
                   10156: // Accept only integer percentages
                   10157:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10158:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10159: // Find out grading choice
                   10160:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10161:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10162:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10163:       }
                   10164:    }
                   10165: // By default, new choice equals user selection
                   10166:    newgradingchoice=gradingchoice;
                   10167: // Not good to give more points for false answers than correct ones
                   10168:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10169:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10170:    }
                   10171: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10172:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10173:       document.forms.gradesupload.pcorrect.value=100;
                   10174:       document.forms.gradesupload.pincorrect.value=100;
                   10175:    }
                   10176: // If the values are different, cannot be attendance only
                   10177:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10178:        (gradingchoice=='attendance')) {
                   10179:        newgradingchoice='personnel';
                   10180:    }
                   10181: // Change grading choice to new one
                   10182:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10183:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10184:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10185:       } else {
                   10186:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10187:       }
                   10188:    }
                   10189: // Remember the old state
                   10190:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10191: }
1.597     wenzelju 10192: ENDUPFORM
                   10193:     $result.= <<ENDUPFORM;
1.400     www      10194: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10195: <input type="hidden" name="symb" value="$symb" />
                   10196: <input type="hidden" name="command" value="processclickerfile" />
                   10197: <input type="file" name="upfile" size="50" />
                   10198: <br /><label>$type: $selectform</label>
1.632     www      10199: ENDUPFORM
                   10200:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10201:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10202:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10203: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10204: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10205: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10206: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10207: <br />&nbsp;&nbsp;&nbsp;
                   10208: <input type="text" name="givenanswer" size="50" />
1.413     www      10209: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10210: ENDGRADINGFORM
                   10211:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10212:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10213:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10214: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10215: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 10216: </form>'
1.632     www      10217: ENDPERCFORM
                   10218:     $result.='</td>'.
                   10219:              &Apache::loncommon::end_data_table_row().
                   10220:              &Apache::loncommon::end_data_table();
1.400     www      10221:     return $result;
                   10222: }
                   10223: 
                   10224: sub process_clicker_file {
1.608     www      10225:     my ($r,$symb)=@_;
1.400     www      10226:     if (!$symb) {return '';}
1.413     www      10227: 
                   10228:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10229:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10230:                                               \%Saveable_Parameters);
1.598     www      10231:     my $result='';
1.404     www      10232:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10233: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10234: 	return $result;
1.404     www      10235:     }
1.522     www      10236:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10237:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10238:         return $result;
1.521     www      10239:     }
1.522     www      10240:     my $foundgiven=0;
1.521     www      10241:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10242:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10243:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10244:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10245:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10246:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10247:         $foundgiven=$#answers+1;
1.521     www      10248:     }
1.407     albertel 10249:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10250:     my %correct_ids;
1.404     www      10251:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10252: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10253:     }
                   10254:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10255: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10256: 	   $correct_id=~tr/a-z/A-Z/;
                   10257: 	   $correct_id=~s/\s//gs;
                   10258: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10259:            $correct_id=~s/[\-\:]//g;
1.414     www      10260:            if ($correct_id) {
                   10261: 	      $correct_ids{$correct_id}='specified';
                   10262:            }
                   10263:         }
1.400     www      10264:     }
1.404     www      10265:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10266: 	$result.=&mt('Score based on attendance only');
1.521     www      10267:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10268:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10269:     } else {
1.408     albertel 10270: 	my $number=0;
1.411     www      10271: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10272: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10273: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10274: 	    if ($correct_ids{$id} eq 'specified') {
                   10275: 		$result.=&mt('specified');
                   10276: 	    } else {
                   10277: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10278: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10279: 	    }
                   10280: 	    $number++;
                   10281: 	}
1.411     www      10282:         $result.="</p>\n";
1.710     bisitz   10283:         if ($number==0) {
                   10284:             $result .=
                   10285:                  &Apache::lonhtmlcommon::confirm_success(
                   10286:                      &mt('No IDs found to determine correct answer'),1);
                   10287:             return $result;
                   10288:         }
1.404     www      10289:     }
1.405     www      10290:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10291:         $result .=
                   10292:             &Apache::lonhtmlcommon::confirm_success(
                   10293:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10294:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10295:         return $result;
1.405     www      10296:     }
1.410     www      10297: 
                   10298: # Were able to get all the info needed, now analyze the file
                   10299: 
1.411     www      10300:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10301:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10302:     $result.=&Apache::loncommon::start_data_table().
                   10303:              &Apache::loncommon::start_data_table_header_row().
                   10304:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10305:              &Apache::loncommon::end_data_table_header_row().
                   10306:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10307: <td>
1.410     www      10308: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10309: <input type="hidden" name="symb" value="$symb" />
                   10310: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10311: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10312: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10313: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10314: ENDHEADER
1.522     www      10315:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10316:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10317:     } 
1.408     albertel 10318:     my %responses;
                   10319:     my @questiontitles;
1.405     www      10320:     my $errormsg='';
                   10321:     my $number=0;
                   10322:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10323: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10324:     }
1.419     www      10325:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10326:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10327:     }
1.666     www      10328:     if ($env{'form.upfiletype'} eq 'turning') {
                   10329:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10330:     }
1.411     www      10331:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10332:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10333:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10334:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10335:              '<br />';
1.522     www      10336:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10337:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10338:        return $result;
1.522     www      10339:     } 
1.414     www      10340: # Remember Question Titles
                   10341: # FIXME: Possibly need delimiter other than ":"
                   10342:     for (my $i=0;$i<$number;$i++) {
                   10343:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10344:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10345:     }
1.411     www      10346:     my $correct_count=0;
                   10347:     my $student_count=0;
                   10348:     my $unknown_count=0;
1.414     www      10349: # Match answers with usernames
                   10350: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10351:     foreach my $id (keys(%responses)) {
1.410     www      10352:        if ($correct_ids{$id}) {
1.414     www      10353:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10354:           $correct_count++;
1.410     www      10355:        } elsif ($clicker_ids{$id}) {
1.437     www      10356:           if ($clicker_ids{$id}=~/\,/) {
                   10357: # More than one user with the same clicker!
1.632     www      10358:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10359:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10360:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10361:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10362:                            "<select name='multi".$id."'>";
                   10363:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10364:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10365:              }
                   10366:              $result.='</select>';
                   10367:              $unknown_count++;
                   10368:           } else {
                   10369: # Good: found one and only one user with the right clicker
                   10370:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10371:              $student_count++;
                   10372:           }
1.410     www      10373:        } else {
1.632     www      10374:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10375:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10376:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10377:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10378:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10379:                    "\n".&mt("Domain").": ".
                   10380:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10381:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10382:           $unknown_count++;
1.410     www      10383:        }
1.405     www      10384:     }
1.412     www      10385:     $result.='<hr />'.
                   10386:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10387:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10388:        if ($correct_count==0) {
1.696     bisitz   10389:           $errormsg.="Found no correct answers for grading!";
1.412     www      10390:        } elsif ($correct_count>1) {
1.414     www      10391:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10392:        }
                   10393:     }
1.428     www      10394:     if ($number<1) {
                   10395:        $errormsg.="Found no questions.";
                   10396:     }
1.412     www      10397:     if ($errormsg) {
                   10398:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10399:     } else {
                   10400:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10401:     }
1.632     www      10402:     $result.='</form></td>'.
                   10403:              &Apache::loncommon::end_data_table_row().
                   10404:              &Apache::loncommon::end_data_table();
1.614     www      10405:     return $result;
1.400     www      10406: }
                   10407: 
1.405     www      10408: sub iclicker_eval {
1.406     www      10409:     my ($questiontitles,$responses)=@_;
1.405     www      10410:     my $number=0;
                   10411:     my $errormsg='';
                   10412:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10413:         my %components=&Apache::loncommon::record_sep($line);
                   10414:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10415: 	if ($entries[0] eq 'Question') {
                   10416: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10417: 		$$questiontitles[$number]=$entries[$i];
                   10418: 		$number++;
                   10419: 	    }
                   10420: 	}
                   10421: 	if ($entries[0]=~/^\#/) {
                   10422: 	    my $id=$entries[0];
                   10423: 	    my @idresponses;
                   10424: 	    $id=~s/^[\#0]+//;
                   10425: 	    for (my $i=0;$i<$number;$i++) {
                   10426: 		my $idx=3+$i*6;
1.644     www      10427:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10428: 		push(@idresponses,$entries[$idx]);
                   10429: 	    }
                   10430: 	    $$responses{$id}=join(',',@idresponses);
                   10431: 	}
1.405     www      10432:     }
                   10433:     return ($errormsg,$number);
                   10434: }
                   10435: 
1.419     www      10436: sub interwrite_eval {
                   10437:     my ($questiontitles,$responses)=@_;
                   10438:     my $number=0;
                   10439:     my $errormsg='';
1.420     www      10440:     my $skipline=1;
                   10441:     my $questionnumber=0;
                   10442:     my %idresponses=();
1.419     www      10443:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10444:         my %components=&Apache::loncommon::record_sep($line);
                   10445:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10446:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10447:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10448:         next if $skipline;
                   10449:         if ($entries[0]!=$questionnumber) {
                   10450:            $questionnumber=$entries[0];
                   10451:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10452:            $number++;
1.419     www      10453:         }
1.420     www      10454:         my $id=$entries[4];
                   10455:         $id=~s/^[\#0]+//;
1.421     www      10456:         $id=~s/^v\d*\://i;
                   10457:         $id=~s/[\-\:]//g;
1.420     www      10458:         $idresponses{$id}[$number]=$entries[6];
                   10459:     }
1.524     raeburn  10460:     foreach my $id (keys(%idresponses)) {
1.420     www      10461:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10462:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10463:     }
                   10464:     return ($errormsg,$number);
                   10465: }
                   10466: 
1.666     www      10467: sub turning_eval {
                   10468:     my ($questiontitles,$responses)=@_;
                   10469:     my $number=0;
                   10470:     my $errormsg='';
                   10471:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10472:         my %components=&Apache::loncommon::record_sep($line);
                   10473:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10474:         if ($#entries>$number) { $number=$#entries; }
                   10475:         my $id=$entries[0];
                   10476:         my @idresponses;
                   10477:         $id=~s/^[\#0]+//;
                   10478:         unless ($id) { next; }
                   10479:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10480:             $entries[$idx]=~s/\,/\;/g;
                   10481:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10482:             push(@idresponses,$entries[$idx]);
                   10483:         }
                   10484:         $$responses{$id}=join(',',@idresponses);
                   10485:     }
                   10486:     for (my $i=1; $i<=$number; $i++) {
                   10487:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10488:     }
                   10489:     return ($errormsg,$number);
                   10490: }
                   10491: 
                   10492: 
1.414     www      10493: sub assign_clicker_grades {
1.608     www      10494:     my ($r,$symb)=@_;
1.414     www      10495:     if (!$symb) {return '';}
1.416     www      10496: # See which part we are saving to
1.582     raeburn  10497:     my $res_error;
                   10498:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10499:     if ($res_error) {
                   10500:         return &navmap_errormsg();
                   10501:     }
1.416     www      10502: # FIXME: This should probably look for the first handgradeable part
                   10503:     my $part=$$partlist[0];
                   10504: # Start screen output
1.632     www      10505:     my $result=&Apache::loncommon::start_data_table().
                   10506:              &Apache::loncommon::start_data_table_header_row().
                   10507:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10508:              &Apache::loncommon::end_data_table_header_row().
                   10509:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10510: # Get correct result
                   10511: # FIXME: Possibly need delimiter other than ":"
                   10512:     my @correct=();
1.415     www      10513:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10514:     my $number=$env{'form.number'};
                   10515:     if ($gradingmechanism ne 'attendance') {
1.414     www      10516:        foreach my $key (keys(%env)) {
                   10517:           if ($key=~/^form\.correct\:/) {
                   10518:              my @input=split(/\,/,$env{$key});
                   10519:              for (my $i=0;$i<=$#input;$i++) {
                   10520:                  if (($correct[$i]) && ($input[$i]) &&
                   10521:                      ($correct[$i] ne $input[$i])) {
                   10522:                     $result.='<br /><span class="LC_warning">'.
                   10523:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10524:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10525:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10526:                     $correct[$i]=$input[$i];
                   10527:                  }
                   10528:              }
                   10529:           }
                   10530:        }
1.415     www      10531:        for (my $i=0;$i<$number;$i++) {
1.644     www      10532:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10533:              $result.='<br /><span class="LC_error">'.
                   10534:                       &mt('No correct result given for question "[_1]"!',
                   10535:                           $env{'form.question:'.$i}).'</span>';
                   10536:           }
                   10537:        }
1.644     www      10538:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10539:     }
                   10540: # Start grading
1.415     www      10541:     my $pcorrect=$env{'form.pcorrect'};
                   10542:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10543:     my $storecount=0;
1.632     www      10544:     my %users=();
1.415     www      10545:     foreach my $key (keys(%env)) {
1.420     www      10546:        my $user='';
1.415     www      10547:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10548:           $user=$1;
                   10549:        }
                   10550:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10551:           my $id=$1;
                   10552:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10553:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10554:           } elsif ($env{'form.multi'.$id}) {
                   10555:              $user=$env{'form.multi'.$id};
1.420     www      10556:           }
                   10557:        }
1.632     www      10558:        if ($user) {
                   10559:           if ($users{$user}) {
                   10560:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10561:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10562:                       '</span><br />';
                   10563:           }
                   10564:           $users{$user}=1; 
1.415     www      10565:           my @answer=split(/\,/,$env{$key});
                   10566:           my $sum=0;
1.522     www      10567:           my $realnumber=$number;
1.415     www      10568:           for (my $i=0;$i<$number;$i++) {
1.576     www      10569:              if  ($correct[$i] eq '-') {
                   10570:                 $realnumber--;
1.644     www      10571:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10572:                 if ($gradingmechanism eq 'attendance') {
                   10573:                    $sum+=$pcorrect;
1.576     www      10574:                 } elsif ($correct[$i] eq '*') {
1.522     www      10575:                    $sum+=$pcorrect;
1.415     www      10576:                 } else {
1.644     www      10577: # We actually grade if correct or not
                   10578:                    my $increment=$pincorrect;
                   10579: # Special case: numerical answer "0"
                   10580:                    if ($correct[$i] eq '0') {
                   10581:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10582:                          $increment=$pcorrect;
                   10583:                       }
                   10584: # General numerical answer, both evaluate to something non-zero
                   10585:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10586:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10587:                          $increment=$pcorrect;
                   10588:                       }
                   10589: # Must be just alphanumeric
                   10590:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10591:                       $increment=$pcorrect;
1.415     www      10592:                    }
1.644     www      10593:                    $sum+=$increment;
1.415     www      10594:                 }
                   10595:              }
                   10596:           }
1.522     www      10597:           my $ave=$sum/(100*$realnumber);
1.416     www      10598: # Store
                   10599:           my ($username,$domain)=split(/\:/,$user);
                   10600:           my %grades=();
                   10601:           $grades{"resource.$part.solved"}='correct_by_override';
                   10602:           $grades{"resource.$part.awarded"}=$ave;
                   10603:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10604:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10605:                                                  $env{'request.course.id'},
                   10606:                                                  $domain,$username);
                   10607:           if ($returncode ne 'ok') {
                   10608:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10609:           } else {
                   10610:              $storecount++;
                   10611:           }
1.415     www      10612:        }
                   10613:     }
                   10614: # We are done
1.549     hauer    10615:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10616:              '</td>'.
                   10617:              &Apache::loncommon::end_data_table_row().
                   10618:              &Apache::loncommon::end_data_table();
1.614     www      10619:     return $result;
1.414     www      10620: }
                   10621: 
1.582     raeburn  10622: sub navmap_errormsg {
                   10623:     return '<div class="LC_error">'.
                   10624:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10625:            &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  10626:            '</div>';
                   10627: }
1.607     droeschl 10628: 
1.609     www      10629: sub startpage {
1.754     raeburn  10630:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   10631:     my %args;
                   10632:     if ($onload) {
                   10633:          my %loaditems = (
                   10634:                         'onload' => $onload,
                   10635:                       );
                   10636:          $args{'add_entries'} = \%loaditems;
                   10637:     }
1.671     raeburn  10638:     if ($nomenu) {
1.754     raeburn  10639:         $args{'only_body'} = 1; 
                   10640:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args);
1.671     raeburn  10641:     } else {
                   10642:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  10643:         $args{'bread_crumbs'} = $crumbs;
                   10644:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.671     raeburn  10645:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10646:     }
1.613     www      10647:     unless ($nodisplayflag) {
1.671     raeburn  10648:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10649:     }
1.607     droeschl 10650: }
1.582     raeburn  10651: 
1.622     www      10652: sub select_problem {
                   10653:     my ($r)=@_;
1.632     www      10654:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.745     raeburn  10655:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
1.622     www      10656:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10657:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10658: }
                   10659: 
1.1       albertel 10660: sub handler {
1.41      ng       10661:     my $request=$_[0];
1.434     albertel 10662:     &reset_caches();
1.646     raeburn  10663:     if ($request->header_only) {
                   10664:         &Apache::loncommon::content_type($request,'text/html');
                   10665:         $request->send_http_header;
                   10666:         return OK;
                   10667:     }
                   10668:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10669: 
1.664     raeburn  10670: # see what command we need to execute
                   10671: 
                   10672:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10673:     my $command=$commands[0];
                   10674: 
1.646     raeburn  10675:     &init_perm();
                   10676:     if (!$env{'request.course.id'}) {
1.664     raeburn  10677:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10678:                 ($command =~ /^scantronupload/)) {
                   10679:             # Not in a course.
                   10680:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10681:             return HTTP_NOT_ACCEPTABLE;
                   10682:         }
1.646     raeburn  10683:     } elsif (!%perm) {
                   10684:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10685:         return OK;
1.41      ng       10686:     }
1.646     raeburn  10687:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10688:     $request->send_http_header;
1.646     raeburn  10689: 
1.160     albertel 10690:     if ($#commands > 0) {
                   10691: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10692:     }
1.608     www      10693: 
                   10694: # see what the symb is
                   10695: 
                   10696:     my $symb=$env{'form.symb'};
                   10697:     unless ($symb) {
                   10698:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10699:        $symb=&Apache::lonnet::symbread($url);
                   10700:     }
1.646     raeburn  10701:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10702: 
1.513     foxr     10703:     $ssi_error = 0;
1.637     www      10704:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10705: #
1.637     www      10706: # Not called from a resource, but inside a course
1.601     www      10707: #    
1.622     www      10708:         &startpage($request,undef,[],1,1);
                   10709:         &select_problem($request);
1.41      ng       10710:     } else {
1.104     albertel 10711: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10712:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10713:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10714:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10715:                     &choose_task_version_form($symb,$env{'form.student'},
                   10716:                                               $env{'form.userdom'});
                   10717:             }
                   10718:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10719:             if ($versionform) {
                   10720:                 $request->print($versionform);
                   10721:             }
                   10722:             $request->print('<br clear="all" />');
1.611     www      10723: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10724:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10725:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10726:                 &choose_task_version_form($symb,$env{'form.student'},
                   10727:                                           $env{'form.userdom'},
                   10728:                                           $env{'form.inhibitmenu'});
                   10729:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10730:             if ($versionform) {
                   10731:                 $request->print($versionform);
                   10732:             }
                   10733:             $request->print('<br clear="all" />');
                   10734:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10735: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10736:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10737:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10738: 	    &pickStudentPage($request,$symb);
1.103     albertel 10739: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10740:             &startpage($request,$symb,
                   10741:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10742:                                        {href=>'',text=>'Select student'},
                   10743:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10744: 	    &displayPage($request,$symb);
1.104     albertel 10745: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10746:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10747:                                        {href=>'',text=>'Select student'},
                   10748:                                        {href=>'',text=>'Grade student'},
                   10749:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10750: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10751: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10752:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10753:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10754: 	    &processGroup($request,$symb);
1.104     albertel 10755: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10756:             &startpage($request,$symb);
                   10757: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10758: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10759:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10760: 	    $request->print(&submit_options($request,$symb));
1.598     www      10761:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10762:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10763:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10764:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10765:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10766:             $request->print(&submit_options_table($request,$symb));
1.598     www      10767:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10768:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10769:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10770: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10771:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10772: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10773: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10774:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10775:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10776: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10777: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10778:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10779:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10780:                                                                              text=>"Modify grades"},
                   10781:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10782: 	    $request->print(&editgrades($request,$symb));
1.602     www      10783:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10784:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10785:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10786: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10787:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10788:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10789: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10790:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10791:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10792:             $request->print(&process_clicker($request,$symb));
1.400     www      10793:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10794:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10795:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10796:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10797:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10798:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10799:                                        {href=>'', text=>'Process clicker file'},
                   10800:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10801:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10802: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10803:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10804: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10805: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10806:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10807: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10808: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10809:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10810: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10811: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10812: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10813:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10814: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10815: 	    } else {
1.257     albertel 10816: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10817: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10818: 		} else {
1.257     albertel 10819: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10820: 		}
1.627     www      10821:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10822: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10823: 	    }
1.246     albertel 10824: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10825:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10826: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10827: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  10828:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10829:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      10830: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10831:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10832:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10833:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10834: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10835:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10836: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10837: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10838:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10839: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10840:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10841:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10842: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.754     raeburn  10843:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10844:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      10845:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10846:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10847:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10848: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10849:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10850:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10851:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10852: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10853:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10854:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10855:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10856:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10857:             $request->print(&checkscantron_results($request,$symb));
                   10858:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10859:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10860:             $request->print(&submit_options_download($request,$symb));
                   10861:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10862:             &startpage($request,$symb,
                   10863:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750     raeburn  10864:     {href=>'', text=>'Download submitted files'}]);
1.621     www      10865:             &submit_download_link($request,$symb);
1.106     albertel 10866: 	} elsif ($command) {
1.620     www      10867:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10868: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10869: 	}
1.2       albertel 10870:     }
1.513     foxr     10871:     if ($ssi_error) {
                   10872: 	&ssi_print_error($request);
                   10873:     }
1.671     raeburn  10874:     if ($env{'form.inhibitmenu'}) {
                   10875:         $request->print(&Apache::loncommon::end_page());
                   10876:     } else {
                   10877:         &Apache::lonquickgrades::endGradeScreen($request);
                   10878:     }
1.434     albertel 10879:     &reset_caches();
1.646     raeburn  10880:     return OK;
1.44      ng       10881: }
                   10882: 
1.1       albertel 10883: 1;
                   10884: 
1.13      albertel 10885: __END__;
1.531     jms      10886: 
                   10887: 
                   10888: =head1 NAME
                   10889: 
                   10890: Apache::grades
                   10891: 
                   10892: =head1 SYNOPSIS
                   10893: 
                   10894: Handles the viewing of grades.
                   10895: 
                   10896: This is part of the LearningOnline Network with CAPA project
                   10897: described at http://www.lon-capa.org.
                   10898: 
                   10899: =head1 OVERVIEW
                   10900: 
                   10901: Do an ssi with retries:
1.715     bisitz   10902: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10903: 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
                   10904: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10905: 
                   10906: At least the logic that drives this has been pulled out into loncommon.
                   10907: 
                   10908: 
                   10909: 
                   10910: ssi_with_retries - Does the server side include of a resource.
                   10911:                      if the ssi call returns an error we'll retry it up to
                   10912:                      the number of times requested by the caller.
1.715     bisitz   10913:                      If we still have a problem, no text is appended to the
1.531     jms      10914:                      output and we set some global variables.
                   10915:                      to indicate to the caller an SSI error occurred.  
                   10916:                      All of this is supposed to deal with the issues described
1.715     bisitz   10917:                      in LON-CAPA BZ 5631 see:
1.531     jms      10918:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10919:                      by informing the user that this happened.
                   10920: 
                   10921: Parameters:
                   10922:   resource   - The resource to include.  This is passed directly, without
                   10923:                interpretation to lonnet::ssi.
                   10924:   form       - The form hash parameters that guide the interpretation of the resource
                   10925:                
                   10926:   retries    - Number of retries allowed before giving up completely.
                   10927: Returns:
                   10928:   On success, returns the rendered resource identified by the resource parameter.
                   10929: Side Effects:
                   10930:   The following global variables can be set:
                   10931:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10932:                               It is up to the caller to initialize this to false
                   10933:                               if desired.
                   10934:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10935:                               of the resource that could not be rendered by the ssi
                   10936:                               call.
                   10937:    ssi_error_message   - The error string fetched from the ssi response
                   10938:                               in the event of an error.
                   10939: 
                   10940: 
                   10941: =head1 HANDLER SUBROUTINE
                   10942: 
                   10943: ssi_with_retries()
                   10944: 
                   10945: =head1 SUBROUTINES
                   10946: 
                   10947: =over
                   10948: 
1.671     raeburn  10949: =head1 Routines to display previous version of a Task for a specific student
                   10950: 
                   10951: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10952: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10953: requires a proctor to check-in the student, a new version of the Task will
                   10954: be created when the student is checked in to the new opportunity.
                   10955: 
                   10956: If a particular student has tried two or more versions of a particular task,
                   10957: the submission screen provides a user with vgr privileges (e.g., a Course
                   10958: Coordinator) the ability to display a previous version worked on by the
                   10959: student.  By default, the current version is displayed. If a previous version
                   10960: has been selected for display, submission data are only shown that pertain
                   10961: to that particular version, and the interface to submit grades is not shown.
                   10962: 
                   10963: =over 4
                   10964: 
                   10965: =item show_previous_task_version()
                   10966: 
                   10967: Displays a specified version of a student's Task, as the student sees it.
                   10968: 
                   10969: Inputs: 2
                   10970:         request - request object
                   10971:         symb    - unique symb for current instance of resource
                   10972: 
                   10973: Output: None.
                   10974: 
                   10975: Side Effects: calls &show_problem() to print version of Task, with
                   10976:               version contained in form item: $env{'form.previousversion'}
                   10977: 
                   10978: =item choose_task_version_form()
                   10979: 
                   10980: Displays a web form used to select which version of a student's view of a
                   10981: Task should be displayed.  Either launches a pop-up window, or replaces
                   10982: content in existing pop-up, or replaces page in main window.
                   10983: 
                   10984: Inputs: 4
                   10985:         symb    - unique symb for current instance of resource
                   10986:         uname   - username of student
                   10987:         udom    - domain of student
                   10988:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10989:                   breadcrumbs etc., are displayed
                   10990: 
                   10991: Output: 4
                   10992:         current   - student's current version
                   10993:         displayed - student's version being displayed
                   10994:         result    - scalar containing HTML for web form used to switch to
                   10995:                     a different version (or a link to close window, if pop-up).
                   10996:         js        - javascript for processing selection in versions web form
                   10997: 
                   10998: Side Effects: None.
                   10999: 
                   11000: =item previous_display_javascript()
                   11001: 
                   11002: Inputs: 2
                   11003:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11004:                   breadcrumbs etc., are displayed.
                   11005:         current - student's current version number.
                   11006: 
                   11007: Output: 1
                   11008:         js      - javascript for processing selection in versions web form.
                   11009: 
                   11010: Side Effects: None.
                   11011: 
                   11012: =back
                   11013: 
                   11014: =head1 Routines to process bubblesheet data.
                   11015: 
                   11016: =over 4
                   11017: 
1.531     jms      11018: =item scantron_get_correction() : 
                   11019: 
                   11020:    Builds the interface screen to interact with the operator to fix a
                   11021:    specific error condition in a specific scanline
                   11022: 
                   11023:  Arguments:
                   11024:     $r           - Apache request object
                   11025:     $i           - number of the current scanline
                   11026:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   11027:     $scan_config - hash ref as returned from &get_scantron_config()
                   11028:     $line        - full contents of the current scanline
                   11029:     $error       - error condition, valid values are
                   11030:                    'incorrectCODE', 'duplicateCODE',
                   11031:                    'doublebubble', 'missingbubble',
                   11032:                    'duplicateID', 'incorrectID'
                   11033:     $arg         - extra information needed
                   11034:        For errors:
                   11035:          - duplicateID   - paper number that this studentID was seen before on
                   11036:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11037:                            seen on before
                   11038:          - incorrectCODE - current incorrect CODE 
                   11039:          - doublebubble  - array ref of the bubble lines that have double
                   11040:                            bubble errors
                   11041:          - missingbubble - array ref of the bubble lines that have missing
                   11042:                            bubble errors
                   11043: 
1.691     raeburn  11044:    $randomorder - True if exam folder has randomorder set
                   11045:    $randompick  - True if exam folder has randompick set
                   11046:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11047:                      for current line to question number used for same question
                   11048:                      in "Master Seqence" (as seen by Course Coordinator).
                   11049:    $startline   - Reference to hash where key is question number (0 is first)
                   11050:                   and value is number of first bubble line for current student
                   11051:                   or code-based randompick and/or randomorder.
                   11052: 
                   11053: 
                   11054: 
1.531     jms      11055: =item  scantron_get_maxbubble() : 
                   11056: 
1.582     raeburn  11057:    Arguments:
                   11058:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11059:                       failure to retrieve a navmap object.
                   11060:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11061:        calling routine should trap the error condition and display the warning
                   11062:        found in &navmap_errormsg().
                   11063: 
1.649     raeburn  11064:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11065: 
1.531     jms      11066:    Returns the maximum number of bubble lines that are expected to
                   11067:    occur. Does this by walking the selected sequence rendering the
                   11068:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11069:    for what the current value of the problem counter is.
                   11070: 
                   11071:    Caches the results to $env{'form.scantron_maxbubble'},
                   11072:    $env{'form.scantron.bubble_lines.n'}, 
                   11073:    $env{'form.scantron.first_bubble_line.n'} and
                   11074:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11075:    which are the total number of bubble lines, the number of bubble
1.531     jms      11076:    lines for response n and number of the first bubble line for response n,
                   11077:    and a comma separated list of numbers of bubble lines for sub-questions
                   11078:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11079: 
                   11080: 
                   11081: =item  scantron_validate_missingbubbles() : 
                   11082: 
                   11083:    Validates all scanlines in the selected file to not have any
                   11084:     answers that don't have bubbles that have not been verified
                   11085:     to be bubble free.
                   11086: 
                   11087: =item  scantron_process_students() : 
                   11088: 
1.659     raeburn  11089:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11090: 
                   11091:    The parsed scanline hash is added to %env 
                   11092: 
                   11093:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11094:    foreach resource , with the form data of
                   11095: 
                   11096: 	'submitted'     =>'scantron' 
                   11097: 	'grade_target'  =>'grade',
                   11098: 	'grade_username'=> username of student
                   11099: 	'grade_domain'  => domain of student
                   11100: 	'grade_courseid'=> of course
                   11101: 	'grade_symb'    => symb of resource to grade
                   11102: 
                   11103:     This triggers a grading pass. The problem grading code takes care
                   11104:     of converting the bubbled letter information (now in %env) into a
                   11105:     valid submission.
                   11106: 
                   11107: =item  scantron_upload_scantron_data() :
                   11108: 
1.659     raeburn  11109:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11110: 
                   11111: =item  scantron_upload_scantron_data_save() : 
                   11112: 
                   11113:    Adds a provided bubble information data file to the course if user
                   11114:    has the correct privileges to do so. 
                   11115: 
                   11116: =item  valid_file() :
                   11117: 
                   11118:    Validates that the requested bubble data file exists in the course.
                   11119: 
                   11120: =item  scantron_download_scantron_data() : 
                   11121: 
                   11122:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11123:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11124:    course.
                   11125: 
                   11126: =item  scantron_validate_ID() : 
                   11127: 
                   11128:    Validates all scanlines in the selected file to not have any
1.556     weissno  11129:    invalid or underspecified student/employee IDs
1.531     jms      11130: 
1.582     raeburn  11131: =item navmap_errormsg() :
                   11132: 
                   11133:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11134:    Should be called whenever the request to instantiate a navmap object fails.
                   11135: 
                   11136: =back
1.582     raeburn  11137: 
1.531     jms      11138: =back
                   11139: 
                   11140: =cut

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