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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.725   ! raeburn     4: # $Id: grades.pm,v 1.724 2014/08/25 20:23:01 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.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &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 />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     333:         my @answer = %answer;
                    334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    336: 	my ($toprow,$bottomrow);
                    337: 	foreach my $foil (@$order) {
                    338: 	    if ($grading{$foil} == 1) {
                    339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    340: 	    } else {
                    341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    342: 	    }
1.398     albertel  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  344: 	}
                    345: 	return '<blockquote><table border="1">'.
1.466     albertel  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   348: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  349:     } elsif ($response eq 'match') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     351:         my @answer = %answer;
                    352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    355: 	my ($toprow,$middlerow,$bottomrow);
                    356: 	foreach my $foil (@$order) {
                    357: 	    my $item=shift(@items);
                    358: 	    if ($grading{$foil} == 1) {
                    359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  361: 	    } else {
                    362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  364: 	    }
1.398     albertel  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        366: 	}
1.126     ng        367: 	return '<blockquote><table border="1">'.
1.466     albertel  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  370: 	    $middlerow.'</tr>'.
1.466     albertel  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   372: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  373:     } elsif ($response eq 'radiobutton') {
                    374: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     375:         my @answer = %answer;
                    376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  377: 	my ($toprow,$bottomrow);
1.434     albertel  378: 	my $correct = 
1.640     raeburn   379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  380: 	foreach my $foil (@$order) {
1.148     albertel  381: 	    if (exists($answer{$foil})) {
1.434     albertel  382: 		if ($foil eq $correct) {
1.466     albertel  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  384: 		} else {
1.466     albertel  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  386: 		}
                    387: 	    } else {
1.466     albertel  388: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  389: 	    }
1.398     albertel  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  391: 	}
                    392: 	return '<blockquote><table border="1">'.
1.466     albertel  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   395: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  396:     } elsif ($response eq 'essay') {
1.257     albertel  397: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        401: 
1.257     albertel  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    407: 	    $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        408: 	}
1.720     kruse     409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
                    410: 
1.268     albertel  411:     } elsif ( $response eq 'organic') {
1.721     bisitz    412:         my $result=&mt('Smile representation: [_1]',
                    413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    416: 	return $result;
1.335     albertel  417:     } elsif ( $response eq 'Task') {
                    418: 	if ( $answer eq 'SUBMITTED') {
                    419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  421: 	    return $result;
                    422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    424: 			       keys(%{$record}));
                    425: 	    return join('<br />',($version,@matches));
                    426: 			       
                    427: 			       
                    428: 	} else {
                    429: 	    my $result =
                    430: 		'<p>'
                    431: 		.&mt('Overall result: [_1]',
                    432: 		     $record->{$version."resource.$respid.$partid.status"})
                    433: 		.'</p>';
                    434: 	    
                    435: 	    $result .= '<ul>';
                    436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    437: 			     keys(%{$record}));
                    438: 	    foreach my $grade (sort(@grade)) {
                    439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    441: 				     $dim, $record->{$grade}).
                    442: 			  '</li>';
                    443: 	    }
                    444: 	    $result.='</ul>';
                    445: 	    return $result;
                    446: 	}
1.716     bisitz    447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    448:         # Respect multiple input fields, see Bug #5409
1.440     albertel  449: 	$answer = 
                    450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    451: 							      $answer);
1.720     kruse     452: 	return $answer;
1.122     ng        453:     }
1.720     kruse     454:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        455: }
                    456: 
                    457: #-- A couple of common js functions
                    458: sub commonJSfunctions {
                    459:     my $request = shift;
1.597     wenzelju  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        461:     function radioSelection(radioButton) {
                    462: 	var selection=null;
                    463: 	if (radioButton.length > 1) {
                    464: 	    for (var i=0; i<radioButton.length; i++) {
                    465: 		if (radioButton[i].checked) {
                    466: 		    return radioButton[i].value;
                    467: 		}
                    468: 	    }
                    469: 	} else {
                    470: 	    if (radioButton.checked) return radioButton.value;
                    471: 	}
                    472: 	return selection;
                    473:     }
                    474: 
                    475:     function pullDownSelection(selectOne) {
                    476: 	var selection="";
                    477: 	if (selectOne.length > 1) {
                    478: 	    for (var i=0; i<selectOne.length; i++) {
                    479: 		if (selectOne[i].selected) {
                    480: 		    return selectOne[i].value;
                    481: 		}
                    482: 	    }
                    483: 	} else {
1.138     albertel  484:             // only one value it must be the selected one
                    485: 	    return selectOne.value;
1.118     ng        486: 	}
                    487:     }
                    488: COMMONJSFUNCTIONS
                    489: }
                    490: 
1.44      ng        491: #--- Dumps the class list with usernames,list of sections,
                    492: #--- section, ids and fullnames for each user.
                    493: sub getclasslist {
1.449     banghart  494:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  495:     my @getsec;
1.450     banghart  496:     my @getgroup;
1.442     banghart  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  498:     if (!ref($getsec)) {
                    499: 	if ($getsec ne '' && $getsec ne 'all') {
                    500: 	    @getsec=($getsec);
                    501: 	}
                    502:     } else {
                    503: 	@getsec=@{$getsec};
                    504:     }
                    505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  506:     if (!ref($getgroup)) {
                    507: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    508: 	    @getgroup=($getgroup);
                    509: 	}
                    510:     } else {
                    511: 	@getgroup=@{$getgroup};
                    512:     }
                    513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  514: 
1.449     banghart  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  516:     # Bail out if we were unable to get the classlist
1.56      matthew   517:     return if (! defined($classlist));
1.449     banghart  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   519:     #
                    520:     my %sections;
                    521:     my %fullnames;
1.205     matthew   522:     foreach my $student (keys(%$classlist)) {
                    523:         my $end      = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    525:         my $start    = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    527:         my $id       = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    529:         my $section  = 
                    530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    531:         my $fullname = 
                    532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    533:         my $status   = 
                    534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  535:         my $group   = 
                    536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        537: 	# filter students according to status selected
1.442     banghart  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    539: 	    if (!($stu_status =~ $status)) {
1.450     banghart  540: 		delete($classlist->{$student});
1.76      ng        541: 		next;
                    542: 	    }
                    543: 	}
1.450     banghart  544: 	# filter students according to groups selected
1.453     banghart  545: 	my @stu_groups = split(/,/,$group);
1.450     banghart  546: 	if (@getgroup) {
                    547: 	    my $exclude = 1;
1.454     banghart  548: 	    foreach my $grp (@getgroup) {
                    549: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  550: 	            if ($stu_group eq $grp) {
                    551: 	                $exclude = 0;
                    552:     	            } 
1.450     banghart  553: 	        }
1.453     banghart  554:     	        if (($grp eq 'none') && !$group) {
                    555:         	        $exclude = 0;
                    556:         	}
1.450     banghart  557: 	    }
                    558: 	    if ($exclude) {
                    559: 	        delete($classlist->{$student});
                    560: 	    }
                    561: 	}
1.205     matthew   562: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  563: 	if (&canview($section)) {
1.291     albertel  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  565: 		$sections{$section}++;
1.450     banghart  566: 		if ($classlist->{$student}) {
                    567: 		    $fullnames{$student}=$fullname;
                    568: 		}
1.103     albertel  569: 	    } else {
1.205     matthew   570: 		delete($classlist->{$student});
1.103     albertel  571: 	    }
                    572: 	} else {
1.205     matthew   573: 	    delete($classlist->{$student});
1.103     albertel  574: 	}
1.44      ng        575:     }
                    576:     my %seen = ();
1.56      matthew   577:     my @sections = sort(keys(%sections));
                    578:     return ($classlist,\@sections,\%fullnames);
1.44      ng        579: }
                    580: 
1.103     albertel  581: sub canmodify {
                    582:     my ($sec)=@_;
                    583:     if ($perm{'mgr'}) {
                    584: 	if (!defined($perm{'mgr_section'})) {
                    585: 	    # can modify whole class
                    586: 	    return 1;
                    587: 	} else {
                    588: 	    if ($sec eq $perm{'mgr_section'}) {
                    589: 		#can modify the requested section
                    590: 		return 1;
                    591: 	    } else {
                    592: 		# can't modify the request section
                    593: 		return 0;
                    594: 	    }
                    595: 	}
                    596:     }
                    597:     #can't modify
                    598:     return 0;
                    599: }
                    600: 
                    601: sub canview {
                    602:     my ($sec)=@_;
                    603:     if ($perm{'vgr'}) {
                    604: 	if (!defined($perm{'vgr_section'})) {
                    605: 	    # can modify whole class
                    606: 	    return 1;
                    607: 	} else {
                    608: 	    if ($sec eq $perm{'vgr_section'}) {
                    609: 		#can modify the requested section
                    610: 		return 1;
                    611: 	    } else {
                    612: 		# can't modify the request section
                    613: 		return 0;
                    614: 	    }
                    615: 	}
                    616:     }
                    617:     #can't modify
                    618:     return 0;
                    619: }
                    620: 
1.44      ng        621: #--- Retrieve the grade status of a student for all the parts
                    622: sub student_gradeStatus {
1.324     albertel  623:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        625:     my %partstatus = ();
                    626:     foreach (@$partlist) {
1.128     ng        627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        628: 	$status              = 'nothing' if ($status eq '');
                    629: 	$partstatus{$_}      = $status;
                    630: 	my $subkey           = "resource.$_.submitted_by";
                    631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    632:     }
                    633:     return %partstatus;
                    634: }
                    635: 
1.45      ng        636: # hidden form and javascript that calls the form
                    637: # Use by verifyscript and viewgrades
                    638: # Shows a student's view of problem and submission
                    639: sub jscriptNform {
1.324     albertel  640:     my ($symb) = @_;
1.442     banghart  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        643: 	'    function viewOneStudent(user,domain) {'."\n".
                    644: 	'	document.onestudent.student.value = user;'."\n".
                    645: 	'	document.onestudent.userdom.value = domain;'."\n".
                    646: 	'	document.onestudent.submit();'."\n".
                    647: 	'    }'."\n".
1.597     wenzelju  648: 	"\n");
1.45      ng        649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        652: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    653: 	'<input type="hidden" name="student" value="" />'."\n".
                    654: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    655: 	'</form>'."\n";
                    656:     return $jscript;
                    657: }
1.39      ng        658: 
1.447     foxr      659: 
                    660: 
1.315     bowersj2  661: # Given the score (as a number [0-1] and the weight) what is the final
                    662: # point value? This function will round to the nearest tenth, third,
                    663: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  664: sub compute_points {
1.315     bowersj2  665:     my ($score, $weight) = @_;
                    666:     
                    667:     my $tolerance = .00001;
                    668:     my $points = $score * $weight;
                    669: 
                    670:     # Check for nearness to 1/x.
                    671:     my $check_for_nearness = sub {
                    672:         my ($factor) = @_;
                    673:         my $num = ($points * $factor) + $tolerance;
                    674:         my $floored_num = floor($num);
1.316     albertel  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  676:             return $floored_num / $factor;
                    677:         }
                    678:         return $points;
                    679:     };
                    680: 
                    681:     $points = $check_for_nearness->(10);
                    682:     $points = $check_for_nearness->(3);
                    683:     $points = $check_for_nearness->(4);
                    684:     
                    685:     return $points;
                    686: }
                    687: 
1.44      ng        688: #------------------ End of general use routines --------------------
1.87      www       689: 
                    690: #
                    691: # Find most similar essay
                    692: #
                    693: 
                    694: sub most_similar {
1.674     raeburn   695:     my ($uname,$udom,$symb,$uessay)=@_;
                    696: 
                    697:     unless ($symb) { return ''; }
                    698: 
                    699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       700: 
                    701: # ignore spaces and punctuation
                    702: 
                    703:     $uessay=~s/\W+/ /gs;
                    704: 
1.282     www       705: # ignore empty submissions (occuring when only files are sent)
                    706: 
1.598     www       707:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       708: 
1.87      www       709: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       710:     my $limit=0.6;
1.87      www       711:     my $sname='';
                    712:     my $sdom='';
                    713:     my $scrsid='';
                    714:     my $sessay='';
                    715: # go through all essays ...
1.674     raeburn   716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       718: # ... except the same student
1.426     albertel  719:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   720: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  721: 	$tessay=~s/\W+/ /gs;
1.87      www       722: # String similarity gives up if not even limit
1.426     albertel  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       724: # Found one
1.426     albertel  725: 	if ($tsimilar>$limit) {
                    726: 	    $limit=$tsimilar;
                    727: 	    $sname=$tname;
                    728: 	    $sdom=$tdom;
                    729: 	    $scrsid=$tcrsid;
1.674     raeburn   730: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  731: 	}
1.87      www       732:     }
1.88      www       733:     if ($limit>0.6) {
1.87      www       734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    735:     } else {
                    736:        return ('','','','',0);
                    737:     }
                    738: }
                    739: 
1.44      ng        740: #-------------------------------------------------------------------
                    741: 
                    742: #------------------------------------ Receipt Verification Routines
1.45      ng        743: #
1.602     www       744: 
                    745: sub initialverifyreceipt {
1.608     www       746:    my ($request,$symb) = @_;
1.602     www       747:    &commonJSfunctions($request);
1.694     bisitz    748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    750:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    752:         '<input type="hidden" name="command" value="verify" />'.
                    753:         "</form>\n";
1.602     www       754: }
                    755: 
1.44      ng        756: #--- Check whether a receipt number is valid.---
                    757: sub verifyreceipt {
1.608     www       758:     my ($request,$symb)  = @_;
1.44      ng        759: 
1.257     albertel  760:     my $courseid = $env{'request.course.id'};
1.184     www       761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  762: 	$env{'form.receipt'};
1.44      ng        763:     $receipt     =~ s/[^\-\d]//g;
                    764: 
1.487     albertel  765:     my $title.=
                    766: 	'<h3><span class="LC_info">'.
1.605     www       767: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    768: 	'</span></h3>'."\n";
1.44      ng        769: 
                    770:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   771:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  772:     
                    773:     my $receiptparts=0;
1.390     albertel  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  776:     my $parts=['0'];
1.582     raeburn   777:     if ($receiptparts) {
                    778:         my $res_error; 
                    779:         ($parts)=&response_type($symb,\$res_error);
                    780:         if ($res_error) {
                    781:             return &navmap_errormsg();
                    782:         } 
                    783:     }
1.486     albertel  784:     
                    785:     my $header = 
                    786: 	&Apache::loncommon::start_data_table().
                    787: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  791:     if ($receiptparts) {
1.487     albertel  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  793:     }
                    794:     $header.=
                    795: 	&Apache::loncommon::end_data_table_header_row();
                    796: 
1.294     albertel  797:     foreach (sort 
                    798: 	     {
                    799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    801: 		 }
                    802: 		 return $a cmp $b;
                    803: 	     } (keys(%$fullname))) {
1.44      ng        804: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  805: 	foreach my $part (@$parts) {
                    806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  807: 		$contents.=
                    808: 		    &Apache::loncommon::start_data_table_row().
                    809: 		    '<td>&nbsp;'."\n".
1.177     albertel  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    814: 		if ($receiptparts) {
                    815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    816: 		}
1.486     albertel  817: 		$contents.= 
                    818: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  819: 		
                    820: 		$matches++;
                    821: 	    }
1.44      ng        822: 	}
                    823:     }
                    824:     if ($matches == 0) {
1.584     bisitz    825:         $string = $title
                    826:                  .'<p class="LC_warning">'
                    827:                  .&mt('No match found for the above receipt number.')
                    828:                  .'</p>';
1.44      ng        829:     } else {
1.324     albertel  830: 	$string = &jscriptNform($symb).$title.
1.487     albertel  831: 	    '<p>'.
1.584     bisitz    832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  833: 	    '</p>'.
1.486     albertel  834: 	    $header.
                    835: 	    $contents.
                    836: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        837:     }
1.614     www       838:     return $string;
1.44      ng        839: }
                    840: 
                    841: #--- This is called by a number of programs.
                    842: #--- Called from the Grading Menu - View/Grade an individual student
                    843: #--- Also called directly when one clicks on the subm button 
                    844: #    on the problem page.
1.30      ng        845: sub listStudents {
1.617     www       846:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  847: 
1.257     albertel  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       852:     unless ($submitonly) {
                    853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    854:     }
1.49      albertel  855: 
1.632     www       856:     my $result='';
1.623     www       857:     my $res_error;
                    858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  859: 
1.559     raeburn   860:     my %lt = &Apache::lonlocal::texthash (
                    861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    862: 		'single'   => 'Please select the student before clicking on the Next button.',
                    863: 	     );
1.597     wenzelju  864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        865:     function checkSelect(checkBox) {
                    866: 	var ctr=0;
                    867: 	var sense="";
                    868: 	if (checkBox.length > 1) {
                    869: 	    for (var i=0; i<checkBox.length; i++) {
                    870: 		if (checkBox[i].checked) {
                    871: 		    ctr++;
                    872: 		}
                    873: 	    }
1.485     albertel  874: 	    sense = '$lt{'multiple'}';
1.110     ng        875: 	} else {
                    876: 	    if (checkBox.checked) {
                    877: 		ctr = 1;
                    878: 	    }
1.485     albertel  879: 	    sense = '$lt{'single'}';
1.110     ng        880: 	}
                    881: 	if (ctr == 0) {
1.485     albertel  882: 	    alert(sense);
1.110     ng        883: 	    return false;
                    884: 	}
                    885: 	document.gradesub.submit();
                    886:     }
                    887: 
                    888:     function reLoadList(formname) {
1.112     ng        889: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        890: 	formname.command.value = 'submission';
                    891: 	formname.submit();
                    892:     }
1.45      ng        893: LISTJAVASCRIPT
                    894: 
1.118     ng        895:     &commonJSfunctions($request);
1.41      ng        896:     $request->print($result);
1.39      ng        897: 
1.154     albertel  898:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       899: 	"\n";
1.485     albertel  900: 	
1.561     bisitz    901:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    903:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    904:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    906:                   .&Apache::lonhtmlcommon::row_closure();
                    907:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    908:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    909:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    910:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    911:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  912: 
                    913:     my $submission_options;
1.442     banghart  914:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    915:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  916:     $env{'form.Status'} = $saveStatus;
1.485     albertel  917:     $submission_options.=
1.592     bisitz    918:         '<span class="LC_nobreak">'.
1.624     www       919:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     920:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    921:         '<span class="LC_nobreak">'.
                    922:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     923:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    924:         '<span class="LC_nobreak">'.
1.628     www       925:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     926:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    927:         '<span class="LC_nobreak">'.
                    928:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     929:         &mt('all submissions with details').'</label></span>';
                    930:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    931:                   .$submission_options
                    932:                   .&Apache::lonhtmlcommon::row_closure();
                    933: 
                    934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    935:                   .'<select name="increment">'
                    936:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    937:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    938:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    939:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    940:                   .'</select>'
                    941:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  942: 
                    943:     $gradeTable .= 
1.432     banghart  944:         &build_section_inputs().
1.45      ng        945: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    948: 
1.618     www       949:     if (exists($env{'form.Status'})) {
1.561     bisitz    950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        951:     } else {
1.561     bisitz    952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    953:                       .&Apache::lonhtmlcommon::StatusOptions(
                    954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    955:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        956:     }
1.112     ng        957: 
1.561     bisitz    958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    960:                   .&Apache::lonhtmlcommon::row_closure(1)
                    961:                   .&Apache::lonhtmlcommon::end_pick_box();
                    962: 
                    963:     $gradeTable .= '<p>'
1.618     www       964:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    965:                   .'<input type="hidden" name="command" value="processGroup" />'
                    966:                   .'</p>';
1.249     albertel  967: 
                    968: # checkall buttons
                    969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        970:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  973:     $gradeTable.=&check_buttons();
1.450     banghart  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  975:     $gradeTable.= &Apache::loncommon::start_data_table().
                    976: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        977:     my $loop = 0;
                    978:     while ($loop < 2) {
1.485     albertel  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       981: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  982: 	    foreach my $part (sort(@$partlist)) {
                    983: 		my $display_part=
                    984: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    985: 		$gradeTable.=
                    986: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        987: 	    }
1.301     albertel  988: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  989: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        990: 	}
                    991: 	$loop++;
1.126     ng        992: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        993:     }
1.474     albertel  994:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        995: 
1.45      ng        996:     my $ctr = 0;
1.294     albertel  997:     foreach my $student (sort 
                    998: 			 {
                    999: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1000: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1001: 			     }
                   1002: 			     return $a cmp $b;
                   1003: 			 }
                   1004: 			 (keys(%$fullname))) {
1.41      ng       1005: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1006: 
1.110     ng       1007: 	my %status = ();
1.301     albertel 1008: 
                   1009: 	if ($submitonly eq 'queued') {
                   1010: 	    my %queue_status = 
                   1011: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1012: 							$udom,$uname);
                   1013: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1014: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1015: 	}
                   1016: 
1.618     www      1017: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1018: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1019: 	    my $submitted = 0;
1.164     albertel 1020: 	    my $graded = 0;
1.248     albertel 1021: 	    my $incorrect = 0;
1.110     ng       1022: 	    foreach (keys(%status)) {
1.145     albertel 1023: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1024: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1025: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1026: 		
1.110     ng       1027: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1028: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1029: 		    $submitted = 0;
1.150     albertel 1030: 		    my ($part)=split(/\./,$partid);
1.110     ng       1031: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1032: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1033: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1034: 		}
1.41      ng       1035: 	    }
1.248     albertel 1036: 	    
1.156     albertel 1037: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1038: 				     $submitonly eq 'incorrect' ||
                   1039: 				     $submitonly eq 'graded'));
1.248     albertel 1040: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1041: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1042: 	}
1.34      ng       1043: 
1.45      ng       1044: 	$ctr++;
1.249     albertel 1045: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1046:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1047: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1048: 	    if ($ctr%2 ==1) {
                   1049: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1050: 	    }
1.126     ng       1051: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1052:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1053:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1054: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1055: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1056: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1057: 
1.618     www      1058: 	    if ($submitonly ne 'all') {
1.524     raeburn  1059: 		foreach (sort(keys(%status))) {
1.485     albertel 1060: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1061: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1062: 		}
1.41      ng       1063: 	    }
1.126     ng       1064: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1065: 	    if ($ctr%2 ==0) {
                   1066: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1067: 	    }
1.41      ng       1068: 	}
                   1069:     }
1.110     ng       1070:     if ($ctr%2 ==1) {
1.126     ng       1071: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1072: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1073: 		foreach (@$partlist) {
                   1074: 		    $gradeTable.='<td>&nbsp;</td>';
                   1075: 		}
1.301     albertel 1076: 	    } elsif ($submitonly eq 'queued') {
                   1077: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1078: 	    }
1.474     albertel 1079: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1080:     }
                   1081: 
1.474     albertel 1082:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1083:         '<input type="button" '.
                   1084:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1085:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1086:     if ($ctr == 0) {
1.96      albertel 1087: 	my $num_students=(scalar(keys(%$fullname)));
                   1088: 	if ($num_students eq 0) {
1.485     albertel 1089: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1090: 	} else {
1.171     albertel 1091: 	    my $submissions='submissions';
                   1092: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1093: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1094: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1096: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1097: 		    $num_students).
                   1098: 		'</span><br />';
1.96      albertel 1099: 	}
1.46      ng       1100:     } elsif ($ctr == 1) {
1.474     albertel 1101: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1102:     }
                   1103:     $request->print($gradeTable);
1.44      ng       1104:     return '';
1.10      ng       1105: }
                   1106: 
1.44      ng       1107: #---- Called from the listStudents routine
1.249     albertel 1108: 
                   1109: sub check_script {
                   1110:     my ($form, $type)=@_;
1.597     wenzelju 1111:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1112:     function checkall() {
                   1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1114:             ele = document.forms.'.$form.'.elements[i];
                   1115:             if (ele.name == "'.$type.'") {
                   1116:             document.forms.'.$form.'.elements[i].checked=true;
                   1117:                                        }
                   1118:         }
                   1119:     }
                   1120: 
                   1121:     function checksec() {
                   1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1123:             ele = document.forms.'.$form.'.elements[i];
                   1124:            string = document.forms.'.$form.'.chksec.value;
                   1125:            if
                   1126:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1127:               document.forms.'.$form.'.elements[i].checked=true;
                   1128:             }
                   1129:         }
                   1130:     }
                   1131: 
                   1132: 
                   1133:     function uncheckall() {
                   1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1135:             ele = document.forms.'.$form.'.elements[i];
                   1136:             if (ele.name == "'.$type.'") {
                   1137:             document.forms.'.$form.'.elements[i].checked=false;
                   1138:                                        }
                   1139:         }
                   1140:     }
                   1141: 
1.597     wenzelju 1142: '."\n");
1.249     albertel 1143:     return $chkallscript;
                   1144: }
                   1145: 
                   1146: sub check_buttons {
1.485     albertel 1147:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1148:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1149:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1150:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1151:     return $buttons;
                   1152: }
                   1153: 
1.44      ng       1154: #     Displays the submissions for one student or a group of students
1.34      ng       1155: sub processGroup {
1.619     www      1156:     my ($request,$symb)  = @_;
1.41      ng       1157:     my $ctr        = 0;
1.155     albertel 1158:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1159:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1160: 
1.396     banghart 1161:     foreach my $student (@stuchecked) {
                   1162: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1163: 	$env{'form.student'}        = $uname;
                   1164: 	$env{'form.userdom'}        = $udom;
                   1165: 	$env{'form.fullname'}       = $fullname;
1.619     www      1166: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1167: 	$ctr++;
                   1168:     }
                   1169:     return '';
1.35      ng       1170: }
1.34      ng       1171: 
1.44      ng       1172: #------------------------------------------------------------------------------------
                   1173: #
                   1174: #-------------------------- Next few routines handles grading by student, essentially
                   1175: #                           handles essay response type problem/part
                   1176: #
                   1177: #--- Javascript to handle the submission page functionality ---
                   1178: sub sub_page_js {
                   1179:     my $request = shift;
1.539     riegler  1180: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1182:     function updateRadio(formname,id,weight) {
1.125     ng       1183: 	var gradeBox = formname["GD_BOX"+id];
                   1184: 	var radioButton = formname["RADVAL"+id];
                   1185: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1187: 	gradeBox.value = pts;
                   1188: 	var resetbox = false;
                   1189: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1190: 	    alert("$alertmsg"+pts);
1.71      ng       1191: 	    for (var i=0; i<radioButton.length; i++) {
                   1192: 		if (radioButton[i].checked) {
                   1193: 		    gradeBox.value = i;
                   1194: 		    resetbox = true;
                   1195: 		}
                   1196: 	    }
                   1197: 	    if (!resetbox) {
                   1198: 		formtextbox.value = "";
                   1199: 	    }
                   1200: 	    return;
1.44      ng       1201: 	}
1.71      ng       1202: 
                   1203: 	if (pts > weight) {
                   1204: 	    var resp = confirm("You entered a value ("+pts+
                   1205: 			       ") greater than the weight for the part. Accept?");
                   1206: 	    if (resp == false) {
1.125     ng       1207: 		gradeBox.value = oldpts;
1.71      ng       1208: 		return;
                   1209: 	    }
1.44      ng       1210: 	}
1.13      albertel 1211: 
1.71      ng       1212: 	for (var i=0; i<radioButton.length; i++) {
                   1213: 	    radioButton[i].checked=false;
                   1214: 	    if (pts == i && pts != "") {
                   1215: 		radioButton[i].checked=true;
                   1216: 	    }
                   1217: 	}
                   1218: 	updateSelect(formname,id);
1.125     ng       1219: 	formname["stores"+id].value = "0";
1.41      ng       1220:     }
1.5       albertel 1221: 
1.72      ng       1222:     function writeBox(formname,id,pts) {
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1224: 	if (checkSolved(formname,id) == 'update') {
                   1225: 	    gradeBox.value = pts;
                   1226: 	} else {
1.125     ng       1227: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1228: 	    gradeBox.value = oldpts;
1.125     ng       1229: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1230: 	    for (var i=0; i<radioButton.length; i++) {
                   1231: 		radioButton[i].checked=false;
1.72      ng       1232: 		if (i == oldpts) {
1.71      ng       1233: 		    radioButton[i].checked=true;
                   1234: 		}
                   1235: 	    }
1.41      ng       1236: 	}
1.125     ng       1237: 	formname["stores"+id].value = "0";
1.71      ng       1238: 	updateSelect(formname,id);
                   1239: 	return;
1.41      ng       1240:     }
1.44      ng       1241: 
1.71      ng       1242:     function clearRadBox(formname,id) {
                   1243: 	if (checkSolved(formname,id) == 'noupdate') {
                   1244: 	    updateSelect(formname,id);
                   1245: 	    return;
                   1246: 	}
1.125     ng       1247: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1248: 	for (var i=0; i<gradeSelect.length; i++) {
                   1249: 	    if (gradeSelect[i].selected) {
                   1250: 		var selectx=i;
                   1251: 	    }
                   1252: 	}
1.125     ng       1253: 	var stores = formname["stores"+id];
1.71      ng       1254: 	if (selectx == stores.value) { return };
1.125     ng       1255: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1256: 	gradeBox.value = "";
1.125     ng       1257: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1258: 	for (var i=0; i<radioButton.length; i++) {
                   1259: 	    radioButton[i].checked=false;
                   1260: 	}
                   1261: 	stores.value = selectx;
                   1262:     }
1.5       albertel 1263: 
1.71      ng       1264:     function checkSolved(formname,id) {
1.125     ng       1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1267: 	    if (!reply) {return "noupdate";}
1.120     ng       1268: 	    formname.overRideScore.value = 'yes';
1.41      ng       1269: 	}
1.71      ng       1270: 	return "update";
1.13      albertel 1271:     }
1.71      ng       1272: 
                   1273:     function updateSelect(formname,id) {
1.125     ng       1274: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1275: 	return;
1.41      ng       1276:     }
1.33      ng       1277: 
1.121     ng       1278: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1279:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1280: 	formname.gradeOpt.value = val;
1.71      ng       1281: 	if (val == "Save & Next") {
                   1282: 	    for (i=0;i<=total;i++) {
                   1283: 		for (j=0;j<parttot;j++) {
1.125     ng       1284: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1287: 			if (points == "") {
1.125     ng       1288: 			    var name = formname["name"+i].value;
1.129     ng       1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1290: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1291: 					       ", part "+partid+". Continue?");
1.71      ng       1292: 			    if (resp == false) {
1.125     ng       1293: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1294: 				return false;
                   1295: 			    }
                   1296: 			}
                   1297: 		    }
                   1298: 		    
                   1299: 		}
                   1300: 	    }
                   1301: 	    
                   1302: 	}
1.120     ng       1303: 	formname.submit();
                   1304:     }
                   1305: 
1.71      ng       1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1307:     function checkSubmitPage(formname,total) {
                   1308: 	noscore = new Array(100);
                   1309: 	var ptr = 0;
                   1310: 	for (i=1;i<total;i++) {
1.125     ng       1311: 	    var partid = formname["q_"+i].value;
1.127     ng       1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1314: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1315: 		if (points == "" && status != "correct_by_student") {
                   1316: 		    noscore[ptr] = i;
                   1317: 		    ptr++;
                   1318: 		}
                   1319: 	    }
                   1320: 	}
                   1321: 	if (ptr != 0) {
                   1322: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1323: 	    var prolist = "";
                   1324: 	    if (ptr == 1) {
                   1325: 		prolist = noscore[0];
                   1326: 	    } else {
                   1327: 		var i = 0;
                   1328: 		while (i < ptr-1) {
                   1329: 		    prolist += noscore[i]+", ";
                   1330: 		    i++;
                   1331: 		}
                   1332: 		prolist += "and "+noscore[i];
                   1333: 	    }
                   1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1335: 	    if (resp == false) {
                   1336: 		return false;
                   1337: 	    }
                   1338: 	}
1.45      ng       1339: 
1.71      ng       1340: 	formname.submit();
                   1341:     }
                   1342: SUBJAVASCRIPT
                   1343: }
1.45      ng       1344: 
1.71      ng       1345: #--- javascript for essay type problem --
                   1346: sub sub_page_kw_js {
                   1347:     my $request = shift;
1.80      ng       1348:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1349:     &commonJSfunctions($request);
1.350     albertel 1350: 
1.629     www      1351:     my $inner_js_msg_central= (<<INNERJS);
                   1352: <script type="text/javascript">
1.350     albertel 1353:     function checkInput() {
                   1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1356:       var usrctr = document.msgcenter.usrctr.value;
                   1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1359: 
                   1360:       var msgchk = "";
                   1361:       if (document.msgcenter.subchk.checked) {
                   1362:          msgchk = "msgsub,";
                   1363:       }
                   1364:       var includemsg = 0;
                   1365:       for (var i=1; i<=nmsg; i++) {
                   1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1367:           var frmmsg = document.msgcenter["msg"+i];
                   1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1369:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1370:           showflg.value = "1";
                   1371:           var chkbox = document.msgcenter["msgn"+i];
                   1372:           if (chkbox.checked) {
                   1373:              msgchk += "savemsg"+i+",";
                   1374:              includemsg = 1;
                   1375:           }
                   1376:       }
                   1377:       if (document.msgcenter.newmsgchk.checked) {
                   1378:          msgchk += "newmsg"+usrctr;
                   1379:          includemsg = 1;
                   1380:       }
                   1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1384:       includemsg.value = msgchk;
                   1385: 
                   1386:       self.close()
                   1387: 
                   1388:     }
1.629     www      1389: </script>
1.350     albertel 1390: INNERJS
                   1391: 
1.629     www      1392:     my $inner_js_highlight_central= (<<INNERJS);
                   1393: <script type="text/javascript">
1.351     albertel 1394:     function updateChoice(flag) {
                   1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1398:       opener.document.SCORE.refresh.value = "on";
                   1399:       if (opener.document.SCORE.keywords.value!=""){
                   1400:          opener.document.SCORE.submit();
                   1401:       }
                   1402:       self.close()
                   1403:     }
1.629     www      1404: </script>
1.351     albertel 1405: INNERJS
                   1406: 
                   1407:     my $start_page_msg_central = 
                   1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1409: 				       {'js_ready'  => 1,
                   1410: 					'only_body' => 1,
                   1411: 					'bgcolor'   =>'#FFFFFF',});
                   1412:     my $end_page_msg_central = 
                   1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1414: 
                   1415: 
                   1416:     my $start_page_highlight_central = 
                   1417:         &Apache::loncommon::start_page('Highlight Central',
                   1418: 				       $inner_js_highlight_central,
1.350     albertel 1419: 				       {'js_ready'  => 1,
                   1420: 					'only_body' => 1,
                   1421: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1422:     my $end_page_highlight_central = 
1.350     albertel 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1424: 
1.219     www      1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1426:     $docopen=~s/^document\.//;
1.652     raeburn  1427:     my %lt = &Apache::lonlocal::texthash(
                   1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1429:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1430:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1431:                 comp => 'Compose Message for: ',
                   1432:                 incl => 'Include',
1.656     raeburn  1433:                 type => 'Type',
1.652     raeburn  1434:                 subj => 'Subject',
                   1435:                 mesa => 'Message',
                   1436:                 new  => 'New',
                   1437:                 save => 'Save',
                   1438:                 canc => 'Cancel',
                   1439:                 kehi => 'Keyword Highlight Options',
                   1440:                 txtc => 'Text Color',
                   1441:                 font => 'Font Size',
1.656     raeburn  1442:                 fnst => 'Font Style',
1.718     bisitz   1443:                 col1 => 'red',
                   1444:                 col2 => 'green',
                   1445:                 col3 => 'blue',
                   1446:                 siz1 => 'normal',
                   1447:                 siz2 => '+1',
                   1448:                 siz3 => '+2',
                   1449:                 sty1 => 'normal',
                   1450:                 sty2 => 'italic',
                   1451:                 sty3 => 'bold',
1.652     raeburn  1452:              );
1.597     wenzelju 1453:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1454: 
1.44      ng       1455: //===================== Show list of keywords ====================
1.122     ng       1456:   function keywords(formname) {
1.652     raeburn  1457:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1458:     if (nret==null) return;
1.122     ng       1459:     formname.keywords.value = nret;
1.44      ng       1460: 
1.122     ng       1461:     if (formname.keywords.value != "") {
1.128     ng       1462: 	formname.refresh.value = "on";
1.122     ng       1463: 	formname.submit();
1.44      ng       1464:     }
                   1465:     return;
                   1466:   }
                   1467: 
                   1468: //===================== Script to view submitted by ==================
                   1469:   function viewSubmitter(submitter) {
                   1470:     document.SCORE.refresh.value = "on";
                   1471:     document.SCORE.NCT.value = "1";
                   1472:     document.SCORE.unamedom0.value = submitter;
                   1473:     document.SCORE.submit();
                   1474:     return;
                   1475:   }
                   1476: 
                   1477: //===================== Script to add keyword(s) ==================
                   1478:   function getSel() {
                   1479:     if (document.getSelection) txt = document.getSelection();
                   1480:     else if (document.selection) txt = document.selection.createRange().text;
                   1481:     else return;
                   1482:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1483:     if (cleantxt=="") {
1.652     raeburn  1484: 	alert("$lt{'plse'}");
1.44      ng       1485: 	return;
                   1486:     }
1.652     raeburn  1487:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1488:     if (nret==null) return;
1.127     ng       1489:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1490:     if (document.SCORE.keywords.value != "") {
1.127     ng       1491: 	document.SCORE.refresh.value = "on";
1.44      ng       1492: 	document.SCORE.submit();
                   1493:     }
                   1494:     return;
                   1495:   }
                   1496: 
                   1497: //====================== Script for composing message ==============
1.80      ng       1498:    // preload images
                   1499:    img1 = new Image();
                   1500:    img1.src = "$iconpath/mailbkgrd.gif";
                   1501:    img2 = new Image();
                   1502:    img2.src = "$iconpath/mailto.gif";
                   1503: 
1.44      ng       1504:   function msgCenter(msgform,usrctr,fullname) {
                   1505:     var Nmsg  = msgform.savemsgN.value;
                   1506:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1507:     var subject = msgform.msgsub.value;
1.127     ng       1508:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1509:     re = /msgsub/;
                   1510:     var shwsel = "";
                   1511:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1512:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1513:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1514:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1515: 	var testmsg = "savemsg"+i+",";
                   1516: 	re = new RegExp(testmsg,"g");
1.44      ng       1517: 	shwsel = "";
                   1518: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1519: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1520: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1521: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1522: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1523:     }
1.125     ng       1524:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1525:     shwsel = "";
                   1526:     re = /newmsg/;
                   1527:     if (re.test(msgchk)) { shwsel = "checked" }
                   1528:     newMsg(newmsg,shwsel);
                   1529:     msgTail(); 
                   1530:     return;
                   1531:   }
                   1532: 
1.123     ng       1533:   function checkEntities(strx) {
                   1534:     if (strx.length == 0) return strx;
                   1535:     var orgStr = ["&", "<", ">", '"']; 
                   1536:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1537:     var counter = 0;
                   1538:     while (counter < 4) {
                   1539: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1540: 	counter++;
                   1541:     }
                   1542:     return strx;
                   1543:   }
                   1544: 
                   1545:   function strReplace(strx, orgStr, newStr) {
                   1546:     return strx.split(orgStr).join(newStr);
                   1547:   }
                   1548: 
1.44      ng       1549:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1550:     var height = 70*Nmsg+250;
1.44      ng       1551:     if (height > 600) {
                   1552: 	height = 600;
                   1553:     }
1.118     ng       1554:     var xpos = (screen.width-600)/2;
                   1555:     xpos = (xpos < 0) ? '0' : xpos;
                   1556:     var ypos = (screen.height-height)/2-30;
                   1557:     ypos = (ypos < 0) ? '0' : ypos;
                   1558: 
1.668     www      1559:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1560:     pWin.focus();
                   1561:     pDoc = pWin.document;
1.219     www      1562:     pDoc.$docopen;
1.351     albertel 1563:     pDoc.write('$start_page_msg_central');
1.76      ng       1564: 
                   1565:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1566:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1567:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1568: 
1.676     golterma 1569:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1570:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1571: }
                   1572:     function displaySubject(msg,shwsel) {
1.76      ng       1573:     pDoc = pWin.document;
1.676     golterma 1574:     pDoc.write("<tr>");
                   1575:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1576:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1577:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1578: }
                   1579: 
1.72      ng       1580:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1581:     pDoc = pWin.document;
1.676     golterma 1582:     pDoc.write("<tr>");
                   1583:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1584:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1585:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1586: }
                   1587: 
                   1588:   function newMsg(newmsg,shwsel) {
1.76      ng       1589:     pDoc = pWin.document;
1.676     golterma 1590:     pDoc.write("<tr>");
                   1591:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1592:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1593:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1594: }
                   1595: 
                   1596:   function msgTail() {
1.76      ng       1597:     pDoc = pWin.document;
1.676     golterma 1598:     //pDoc.write("<\\/table>");
1.465     albertel 1599:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1600:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1601:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1602:     pDoc.write("<\\/form>");
1.351     albertel 1603:     pDoc.write('$end_page_msg_central');
1.128     ng       1604:     pDoc.close();
1.44      ng       1605: }
                   1606: 
                   1607: //====================== Script for keyword highlight options ==============
                   1608:   function kwhighlight() {
                   1609:     var kwclr    = document.SCORE.kwclr.value;
                   1610:     var kwsize   = document.SCORE.kwsize.value;
                   1611:     var kwstyle  = document.SCORE.kwstyle.value;
                   1612:     var redsel = "";
                   1613:     var grnsel = "";
                   1614:     var blusel = "";
1.718     bisitz   1615:     var txtcol1 = "$lt{'col1'}";
                   1616:     var txtcol2 = "$lt{'col2'}";
                   1617:     var txtcol3 = "$lt{'col3'}";
                   1618:     var txtsiz1 = "$lt{'siz1'}";
                   1619:     var txtsiz2 = "$lt{'siz2'}";
                   1620:     var txtsiz3 = "$lt{'siz3'}";
                   1621:     var txtsty1 = "$lt{'sty1'}";
                   1622:     var txtsty2 = "$lt{'sty2'}";
                   1623:     var txtsty3 = "$lt{'sty3'}";
                   1624:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1625:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1626:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1627:     var sznsel = "";
                   1628:     var sz1sel = "";
                   1629:     var sz2sel = "";
1.718     bisitz   1630:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1631:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1632:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1633:     var synsel = "";
                   1634:     var syisel = "";
                   1635:     var sybsel = "";
1.718     bisitz   1636:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1637:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1638:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1639:     highlightCentral();
1.718     bisitz   1640:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1641:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1642:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1643:     highlightend();
                   1644:     return;
                   1645:   }
                   1646: 
                   1647:   function highlightCentral() {
1.76      ng       1648: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1649:     var xpos = (screen.width-400)/2;
                   1650:     xpos = (xpos < 0) ? '0' : xpos;
                   1651:     var ypos = (screen.height-330)/2-30;
                   1652:     ypos = (ypos < 0) ? '0' : ypos;
                   1653: 
1.206     albertel 1654:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1655:     hwdWin.focus();
                   1656:     var hDoc = hwdWin.document;
1.219     www      1657:     hDoc.$docopen;
1.351     albertel 1658:     hDoc.write('$start_page_highlight_central');
1.76      ng       1659:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.718     bisitz   1660:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1661: 
1.718     bisitz   1662:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
                   1663:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1664:   }
                   1665: 
                   1666:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1667:     var hDoc = hwdWin.document;
1.718     bisitz   1668:     hDoc.write("<tr>");
1.76      ng       1669:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1670:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1671:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1672:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1673:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1674:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1675:     hDoc.write("<\\/tr>");
1.44      ng       1676:   }
                   1677: 
                   1678:   function highlightend() { 
1.76      ng       1679:     var hDoc = hwdWin.document;
1.718     bisitz   1680:     hDoc.write("<\\/table><br \\/>");
                   1681:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1682:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1683:     hDoc.write("<\\/form>");
1.351     albertel 1684:     hDoc.write('$end_page_highlight_central');
1.128     ng       1685:     hDoc.close();
1.44      ng       1686:   }
                   1687: 
                   1688: SUBJAVASCRIPT
                   1689: }
                   1690: 
1.349     albertel 1691: sub get_increment {
1.348     bowersj2 1692:     my $increment = $env{'form.increment'};
                   1693:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1694:         $increment != .1) {
                   1695:         $increment = 1;
                   1696:     }
                   1697:     return $increment;
                   1698: }
                   1699: 
1.585     bisitz   1700: sub gradeBox_start {
                   1701:     return (
                   1702:         &Apache::loncommon::start_data_table()
                   1703:        .&Apache::loncommon::start_data_table_header_row()
                   1704:        .'<th>'.&mt('Part').'</th>'
                   1705:        .'<th>'.&mt('Points').'</th>'
                   1706:        .'<th>&nbsp;</th>'
                   1707:        .'<th>'.&mt('Assign Grade').'</th>'
                   1708:        .'<th>'.&mt('Weight').'</th>'
                   1709:        .'<th>'.&mt('Grade Status').'</th>'
                   1710:        .&Apache::loncommon::end_data_table_header_row()
                   1711:     );
                   1712: }
                   1713: 
                   1714: sub gradeBox_end {
                   1715:     return (
                   1716:         &Apache::loncommon::end_data_table()
                   1717:     );
                   1718: }
1.71      ng       1719: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1720: sub gradeBox {
1.322     albertel 1721:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1722:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1723: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1724:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1725:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1726:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1727:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1728:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1729: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1730:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1731:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1732:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1733: 				       [$partid]);
                   1734:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1735:     if ($last_resets{$partid}) {
                   1736:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1737:     }
1.695     bisitz   1738:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1739:     my $ctr = 0;
1.348     bowersj2 1740:     my $thisweight = 0;
1.349     albertel 1741:     my $increment = &get_increment();
1.485     albertel 1742: 
                   1743:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1744:     while ($thisweight<=$wgt) {
1.532     bisitz   1745: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1746:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1747: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1748: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1749: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1750:         $thisweight += $increment;
1.71      ng       1751: 	$ctr++;
                   1752:     }
1.485     albertel 1753:     $radio.='</tr></table>';
                   1754: 
                   1755:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1756: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1757: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1758: 	$wgt.')" /></td>'."\n";
1.485     albertel 1759:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1760: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1761: 	' </td>'."\n";
                   1762:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1763: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1764:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1765: 	$line.='<option></option>'.
                   1766: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1767:     } else {
1.485     albertel 1768: 	$line.='<option selected="selected"></option>'.
                   1769: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1770:     }
1.485     albertel 1771:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1772: 
                   1773: 
                   1774:     $result .= 
1.695     bisitz   1775: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1776:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1777:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1778:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1779: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1780: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1781: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1782:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1783:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1784:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1785:         $aggtries.'" />'."\n";
1.582     raeburn  1786:     my $res_error;
                   1787:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1788:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1789:     if ($res_error) {
                   1790:         return &navmap_errormsg();
                   1791:     }
1.318     banghart 1792:     return $result;
                   1793: }
1.322     albertel 1794: 
                   1795: sub handback_box {
1.623     www      1796:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1797:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1798:     my (@respids);
1.652     raeburn  1799:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1800:     foreach my $part_response_id (@part_response_id) {
                   1801:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1802:         if ($part eq $partid) {
1.375     albertel 1803:             push(@respids,$resp);
1.323     banghart 1804:         }
                   1805:     }
1.318     banghart 1806:     my $result;
1.323     banghart 1807:     foreach my $respid (@respids) {
1.322     albertel 1808: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1809: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1810: 	next if (!@$files);
1.654     raeburn  1811: 	my $file_counter = 0;
1.313     banghart 1812: 	foreach my $file (@$files) {
1.368     banghart 1813: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1814:                 $file_counter++;
1.368     banghart 1815:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1816:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1817:     	        $file_disp = "$name.$ext";
                   1818:     	        $file = $file_path.$file_disp;
                   1819:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1820:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1821:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1822:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1823: 	    }
1.322     albertel 1824: 	}
1.654     raeburn  1825:         if ($file_counter) {
                   1826:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1827:                        '<span class="LC_info">'.
                   1828:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1829:         }
1.313     banghart 1830:     }
1.318     banghart 1831:     return $result;    
1.71      ng       1832: }
1.44      ng       1833: 
1.58      albertel 1834: sub show_problem {
1.382     albertel 1835:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1836:     my $rendered;
1.382     albertel 1837:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1838:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1839:     if ($mode eq 'both' or $mode eq 'text') {
                   1840: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1841: 						       $env{'request.course.id'},
                   1842: 						       undef,\%form);
1.144     albertel 1843:     }
1.58      albertel 1844:     if ($removeform) {
                   1845: 	$rendered=~s|<form(.*?)>||g;
                   1846: 	$rendered=~s|</form>||g;
1.374     albertel 1847: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1848:     }
1.144     albertel 1849:     my $companswer;
                   1850:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1851: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1852: 	$companswer=
                   1853: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1854: 						    $env{'request.course.id'},
                   1855: 						    %form);
1.144     albertel 1856:     }
1.58      albertel 1857:     if ($removeform) {
                   1858: 	$companswer=~s|<form(.*?)>||g;
                   1859: 	$companswer=~s|</form>||g;
1.144     albertel 1860: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1861:     }
1.671     raeburn  1862:     my $renderheading = &mt('View of the problem');
                   1863:     my $answerheading = &mt('Correct answer');
                   1864:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1865:         my $stu_fullname = $env{'form.fullname'};
                   1866:         if ($stu_fullname eq '') {
                   1867:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1868:         }
                   1869:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1870:         if ($forwhom ne '') {
                   1871:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1872:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1873:         }
                   1874:     }
1.468     albertel 1875:     $rendered=
1.588     bisitz   1876:         '<div class="LC_Box">'
1.671     raeburn  1877:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1878:        .$rendered
                   1879:        .'</div>';
1.468     albertel 1880:     $companswer=
1.588     bisitz   1881:         '<div class="LC_Box">'
1.671     raeburn  1882:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1883:        .$companswer
                   1884:        .'</div>';
1.468     albertel 1885:     my $result;
1.144     albertel 1886:     if ($mode eq 'both') {
1.588     bisitz   1887:         $result=$rendered.$companswer;
1.144     albertel 1888:     } elsif ($mode eq 'text') {
1.588     bisitz   1889:         $result=$rendered;
1.144     albertel 1890:     } elsif ($mode eq 'answer') {
1.588     bisitz   1891:         $result=$companswer;
1.144     albertel 1892:     }
1.71      ng       1893:     return $result;
1.58      albertel 1894: }
1.397     albertel 1895: 
1.396     banghart 1896: sub files_exist {
                   1897:     my ($r, $symb) = @_;
                   1898:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1899: 
1.396     banghart 1900:     foreach my $student (@students) {
                   1901:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1902:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1903: 					      $udom,$uname);
1.396     banghart 1904:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1905:         foreach my $submission (@$string) {
                   1906:             my ($partid,$respid) =
                   1907: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1908:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1909: 					   \%record);
                   1910:             return 1 if (@$files);
1.396     banghart 1911:         }
                   1912:     }
1.397     albertel 1913:     return 0;
1.396     banghart 1914: }
1.397     albertel 1915: 
1.394     banghart 1916: sub download_all_link {
                   1917:     my ($r,$symb) = @_;
1.621     www      1918:     unless (&files_exist($r, $symb)) {
                   1919:        $r->print(&mt('There are currently no submitted documents.'));
                   1920:        return;
                   1921:     }
                   1922: 
1.395     albertel 1923:     my $all_students = 
                   1924: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1925: 
                   1926:     my $parts =
                   1927: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1928: 
1.394     banghart 1929:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1930:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1931:                              'cgi.'.$identifier.'.symb' => $symb,
                   1932:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1933:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1934: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1935:     return;
                   1936: }
                   1937: 
                   1938: sub submit_download_link {
                   1939:     my ($request,$symb) = @_;
                   1940:     if (!$symb) { return ''; }
                   1941: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1942:     &download_all_link($request,$symb);
1.394     banghart 1943: }
1.395     albertel 1944: 
1.432     banghart 1945: sub build_section_inputs {
                   1946:     my $section_inputs;
                   1947:     if ($env{'form.section'} eq '') {
                   1948:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1949:     } else {
                   1950:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1951:         foreach my $section (@sections) {
1.432     banghart 1952:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1953:         }
                   1954:     }
                   1955:     return $section_inputs;
                   1956: }
                   1957: 
1.44      ng       1958: # --------------------------- show submissions of a student, option to grade 
                   1959: sub submission {
1.608     www      1960:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1961:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1962:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1963:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1964:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1965: 
1.605     www      1966:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1967:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1968: 
                   1969:     if (!&canview($usec)) {
1.712     bisitz   1970:         $request->print(
                   1971:             '<span class="LC_warning">'.
1.713     bisitz   1972:             &mt('Unable to view requested student.').
1.712     bisitz   1973:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1974:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1975:             '</span>');
1.104     albertel 1976: 	return;
                   1977:     }
                   1978: 
1.257     albertel 1979:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1980:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1981:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1982:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1983:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1984: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1985: 	'/check.gif" height="16" border="0" />';
1.41      ng       1986: 
                   1987:     # header info
                   1988:     if ($counter == 0) {
                   1989: 	&sub_page_js($request);
1.621     www      1990: 	&sub_page_kw_js($request);
1.118     ng       1991: 
1.44      ng       1992: 	# option to display problem, only once else it cause problems 
                   1993:         # with the form later since the problem has a form.
1.257     albertel 1994: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1995: 	    my $mode;
1.257     albertel 1996: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1997: 		$mode='both';
1.257     albertel 1998: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1999: 		$mode='text';
1.257     albertel 2000: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2001: 		$mode='answer';
                   2002: 	    }
1.329     albertel 2003: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2004: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2005: 	}
1.441     www      2006: 
1.704     raeburn  2007: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2008:         # if this subroutine has been called once.
1.41      ng       2009: 	my %keyhash = ();
1.624     www      2010: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2011:         if (1) {
1.41      ng       2012: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2013: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2014: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2015: 
1.257     albertel 2016: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2017: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2018: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2019: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2020: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2021: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2022: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2023: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2024: 	}
1.257     albertel 2025: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2026: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2027: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2028: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2029: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2030: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2031: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2032: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2033: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2034: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2035: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2036: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2037: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2038: 			&build_section_inputs().
1.326     albertel 2039: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2040: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2041: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2042: #	if ($env{'form.handgrade'} eq 'yes') {
                   2043:         if (1) {
1.257     albertel 2044: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2045: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2046: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2047: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2048: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2049: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2050: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2051: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2052: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2053: 	    }
1.123     ng       2054: 	}
1.41      ng       2055: 	
                   2056: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2057: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2058: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2059: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2060: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2061: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2062: 		'" />'."\n".
                   2063: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2064: 	    $cts++;
                   2065: 	}
                   2066: 	$request->print($prnmsg);
1.32      ng       2067: 
1.624     www      2068: #	if ($env{'form.handgrade'} eq 'yes') {
                   2069:         if (1) {
1.652     raeburn  2070: 
                   2071:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2072:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2073:                           keyw => 'Keyword Options',
1.655     raeburn  2074:                           list => 'List',
1.652     raeburn  2075:                           past => 'Paste Selection to List',
1.661     www      2076:                           high => 'Highlight Attribute',
1.652     raeburn  2077:                      );    
1.88      www      2078: #
                   2079: # Print out the keyword options line
                   2080: #
1.718     bisitz   2081: 	    $request->print(
                   2082:                 '<div class="LC_columnSection">'
                   2083:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2084:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2085:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2086:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2087:  class="page">'.$lt{'past'}.'</a>',
                   2088:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2089:                     {legend => $lt{'keyw'}})
                   2090:                .'</fieldset></div>'
                   2091:             );
                   2092: 
1.88      www      2093: #
                   2094: # Load the other essays for similarity check
                   2095: #
1.324     albertel 2096:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2097: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2098: 	    $apath=&escape($apath);
1.88      www      2099: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2100:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2101:         }
                   2102:     }
1.44      ng       2103: 
1.441     www      2104: # This is where output for one specific student would start
1.592     bisitz   2105:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2106:     $request->print(
                   2107:         "\n\n"
                   2108:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2109:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2110:        ."\n"
                   2111:     );
1.441     www      2112: 
1.592     bisitz   2113:     # Show additional functions if allowed
                   2114:     if ($perm{'vgr'}) {
                   2115:         $request->print(
                   2116:             &Apache::loncommon::track_student_link(
1.708     bisitz   2117:                 'View recent activity',
1.592     bisitz   2118:                 $uname,$udom,'check')
                   2119:            .' '
                   2120:         );
                   2121:     }
                   2122:     if ($perm{'opa'}) {
                   2123:         $request->print(
                   2124:             &Apache::loncommon::pprmlink(
                   2125:                 &mt('Set/Change parameters'),
                   2126:                 $uname,$udom,$symb,'check'));
                   2127:     }
                   2128: 
                   2129:     # Show Problem
1.257     albertel 2130:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2131: 	my $mode;
1.257     albertel 2132: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2133: 	    $mode='both';
1.257     albertel 2134: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2135: 	    $mode='text';
1.257     albertel 2136: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2137: 	    $mode='answer';
                   2138: 	}
1.329     albertel 2139: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2140: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2141:     }
1.144     albertel 2142: 
1.257     albertel 2143:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2144:     my $res_error;
                   2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2146:     if ($res_error) {
                   2147:         $request->print(&navmap_errormsg());
                   2148:         return;
                   2149:     }
1.41      ng       2150: 
1.44      ng       2151:     # Display student info
1.41      ng       2152:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2153: 
                   2154:     my $result='<div class="LC_Box">'
                   2155:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2156:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2157:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2158: #    if ($env{'form.handgrade'} eq 'no') {
                   2159:     if (1) {
1.588     bisitz   2160:         $result.='<p class="LC_info">'
                   2161:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2162:                 ."</p>\n";
1.469     albertel 2163:     }
                   2164: 
1.118     ng       2165:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2166:     my $fullname;
                   2167:     my $col_fullnames = [];
1.624     www      2168: #    if ($env{'form.handgrade'} eq 'yes') {
                   2169:     if (1) {
1.464     albertel 2170: 	(my $sub_result,$fullname,$col_fullnames)=
                   2171: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2172: 				 $counter);
                   2173: 	$result.=$sub_result;
1.41      ng       2174:     }
1.44      ng       2175:     $request->print($result."\n");
1.702     kruse    2176:     
1.44      ng       2177:     # print student answer/submission
1.588     bisitz   2178:     # Options are (1) Handgraded submission only
1.44      ng       2179:     #             (2) Last submission, includes submission that is not handgraded 
                   2180:     #                  (for multi-response type part)
                   2181:     #             (3) Last submission plus the parts info
                   2182:     #             (4) The whole record for this student
1.702     kruse    2183:     
                   2184:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2185: 	
1.702     kruse    2186:     my $lastsubonly;
1.468     albertel 2187: 
1.702     kruse    2188:     if ($$timestamp eq '') {
                   2189:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2190:     } else {
                   2191:         $lastsubonly =
                   2192:             '<div class="LC_grade_submissions_body">'
                   2193:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2194: 
                   2195: 	my %seenparts;
                   2196: 	my @part_response_id = &flatten_responseType($responseType);
                   2197: 	foreach my $part (@part_response_id) {
                   2198: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2199: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2200: 
1.702     kruse    2201: 	    my ($partid,$respid) = @{ $part };
                   2202: 	    my $display_part=&get_display_part($partid,$symb);
                   2203: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2204: 		if (exists($seenparts{$partid})) { next; }
                   2205: 		$seenparts{$partid}=1;
                   2206:                 $request->print(
                   2207:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2208:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2209:                                '<a href="javascript:viewSubmitter(\''.
                   2210:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2211:                                '\');" target="_self">'.
                   2212:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2213:                     '<br />');
                   2214: 		next;
                   2215: 		}
                   2216: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2217: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2218:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2219:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2220:                     ' <span class="LC_internal_info">'.
                   2221:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2222:                     '</span>&nbsp; &nbsp;'.
                   2223: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2224: 		next;
                   2225: 	    }
                   2226: 	    foreach my $submission (@$string) {
                   2227: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2228: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2229: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2230: 		# Similarity check
                   2231:                 my $similar='';
                   2232:                 my ($type,$trial,$rndseed);
                   2233:                 if ($hide eq 'rand') {
                   2234:                     $type = 'randomizetry';
                   2235:                     $trial = $record{"resource.$partid.tries"};
                   2236:                     $rndseed = $record{"resource.$partid.rndseed"};
                   2237:                 }
                   2238: 	        if ($env{'form.checkPlag'}) {
                   2239:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2240: 		        &most_similar($uname,$udom,$symb,$subval);
                   2241: 		    if ($osim) {
                   2242: 			$osim=int($osim*100.0);
                   2243: 			my %old_course_desc = 
                   2244: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2245: 							{'one_time' => 1});
                   2246: 
                   2247:                         if ($hide eq 'anon') {
                   2248:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2249:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2250:                         } else {
                   2251: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2252: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2253: 				    $osim,
                   2254: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2255: 				        $old_course_desc{'description'},
                   2256: 				        $old_course_desc{'num'},
                   2257: 				        $old_course_desc{'domain'}).
                   2258: 				    '</span></h3><blockquote><i>'.
                   2259: 				    &keywords_highlight($oessay).
                   2260: 				    '</i></blockquote><hr />';
1.702     kruse    2261:                         }
                   2262: 	            }
                   2263: 		}
                   2264: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2265:                                      undef,$type,$trial,$rndseed);
                   2266:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2267: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2268: 		    my $display_part=&get_display_part($partid,$symb);
                   2269:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2270:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2271:                         ' <span class="LC_internal_info">'.
                   2272:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2273:                         '</span>&nbsp; &nbsp;';
                   2274: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2275:                         
                   2276: 		    if (@$files) {
                   2277:                         if ($hide eq 'anon') {
                   2278:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2279:                         } else {
                   2280:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2281:                                         .'<br /><span class="LC_warning">';
                   2282:                             if(@$files == 1) {
                   2283:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2284:                             } else {
1.702     kruse    2285:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2286:                             }
                   2287:                             $lastsubonly .= '</span>';                         
                   2288:                             foreach my $file (@$files) {
                   2289:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2290:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2291:                             }
                   2292:                         }
1.702     kruse    2293: 			$lastsubonly.='<br />';
                   2294:                     }
                   2295:                     if ($hide eq 'anon') {
                   2296:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2297:                     } else {
1.724     raeburn  2298:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2299:                         if ($draft) {
                   2300:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2301:                         }
                   2302:                         $subval =
1.702     kruse    2303: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2304: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2305:                         if ($responsetype eq 'essay') {
                   2306:                             $subval =~ s{\n}{<br />}g;
                   2307:                         }
                   2308:                         $lastsubonly.=$subval."\n";
1.702     kruse    2309:                     }
                   2310: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2311: 		    $lastsubonly.='</div>';
1.41      ng       2312: 		}
1.702     kruse    2313:             }
1.151     albertel 2314: 	}
1.702     kruse    2315: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2316:     }
                   2317:     $request->print($lastsubonly);
                   2318:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2319:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2320: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2321:   
1.702     kruse    2322:     } 
                   2323:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2324:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2325: 								 $env{'request.course.id'},
1.44      ng       2326: 								 $last,'.submission',
                   2327: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2328:     }
1.121     ng       2329:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2330: 	.$udom.'" />'."\n");
1.44      ng       2331:     # return if view submission with no grading option
1.618     www      2332:     if (!&canmodify($usec)) {
1.633     www      2333: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2334: 	return;
1.180     albertel 2335:     } else {
1.468     albertel 2336: 	$request->print('</div>'."\n");
1.41      ng       2337:     }
1.33      ng       2338: 
1.121     ng       2339:     # essay grading message center
1.624     www      2340: #    if ($env{'form.handgrade'} eq 'yes') {
                   2341:     if (1) {
1.468     albertel 2342: 	my $result='<div class="LC_grade_message_center">';
                   2343:     
                   2344: 	$result.='<div class="LC_grade_message_center_header">'.
                   2345: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2346: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2347: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2348: 	if (scalar(@$col_fullnames) > 0) {
                   2349: 	    my $lastone = pop(@$col_fullnames);
                   2350: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2351: 	}
                   2352: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2353: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2354: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2355: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2356: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2357: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2358: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2359: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2360: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2361: 	    '<br />&nbsp;('.
1.468     albertel 2362: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2363: 	$result.='</div></div>';
1.121     ng       2364: 	$request->print($result);
1.118     ng       2365:     }
1.41      ng       2366: 
                   2367:     my %seen = ();
                   2368:     my @partlist;
1.129     ng       2369:     my @gradePartRespid;
1.375     albertel 2370:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2371:     $request->print(
1.588     bisitz   2372:         '<div class="LC_Box">'
                   2373:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2374:     );
1.592     bisitz   2375:     $request->print(&gradeBox_start());
1.375     albertel 2376:     foreach my $part_response_id (@part_response_id) {
                   2377:     	my ($partid,$respid) = @{ $part_response_id };
                   2378: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2379: 	next if ($seen{$partid} > 0);
1.41      ng       2380: 	$seen{$partid}++;
1.393     albertel 2381: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2382: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2383: 	push(@partlist,$partid);
                   2384: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2385: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2386:     }
1.585     bisitz   2387:     $request->print(&gradeBox_end()); # </div>
                   2388:     $request->print('</div>');
1.468     albertel 2389: 
                   2390:     $request->print('<div class="LC_grade_info_links">');
                   2391:     $request->print('</div>');
                   2392: 
1.45      ng       2393:     $result='<input type="hidden" name="partlist'.$counter.
                   2394: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2395:     $result.='<input type="hidden" name="gradePartRespid'.
                   2396: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2397:     my $ctr = 0;
                   2398:     while ($ctr < scalar(@partlist)) {
                   2399: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2400: 	    $partlist[$ctr].'" />'."\n";
                   2401: 	$ctr++;
                   2402:     }
1.468     albertel 2403:     $request->print($result.''."\n");
1.41      ng       2404: 
1.441     www      2405: # Done with printing info for one student
                   2406: 
1.468     albertel 2407:     $request->print('</div>');#LC_grade_show_user
1.441     www      2408: 
                   2409: 
1.41      ng       2410:     # print end of form
                   2411:     if ($counter == $total) {
1.592     bisitz   2412:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2413: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2414: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2415: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2416: 	my $ntstu ='<select name="NTSTU">'.
                   2417: 	    '<option>1</option><option>2</option>'.
                   2418: 	    '<option>3</option><option>5</option>'.
                   2419: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2420: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2421: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2422:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2423: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2424: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2425: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2426: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2427:         $endform.='<span class="LC_warning">'.
                   2428:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2429:                   '</span>'."\n" ;
1.349     albertel 2430:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2431:             "' name='increment' />";
1.485     albertel 2432: 	$endform.='</td></tr></table></form>';
1.41      ng       2433: 	$request->print($endform);
                   2434:     }
                   2435:     return '';
1.38      ng       2436: }
                   2437: 
1.464     albertel 2438: sub check_collaborators {
                   2439:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2440:     my ($result,@col_fullnames);
                   2441:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2442:     foreach my $part (keys(%$handgrade)) {
                   2443: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2444: 					'.maxcollaborators',
                   2445: 					$symb,$udom,$uname);
                   2446: 	next if ($ncol <= 0);
                   2447: 	$part =~ s/\_/\./g;
                   2448: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2449: 	my (@good_collaborators, @bad_collaborators);
                   2450: 	foreach my $possible_collaborator
1.630     www      2451: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2452: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2453: 	    next if ($possible_collaborator eq '');
1.631     www      2454: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2455: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2456: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2457: 	    # Doing this grep allows 'fuzzy' specification
                   2458: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2459: 			       keys(%$classlist));
                   2460: 	    if (! scalar(@matches)) {
                   2461: 		push(@bad_collaborators, $possible_collaborator);
                   2462: 	    } else {
                   2463: 		push(@good_collaborators, @matches);
                   2464: 	    }
                   2465: 	}
                   2466: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2467: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2468: 	    foreach my $name (@good_collaborators) {
                   2469: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2470: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2471: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2472: 	    }
1.630     www      2473: 	    $result.='</ol><br />'."\n";
1.466     albertel 2474: 	    my ($part)=split(/\./,$part);
1.464     albertel 2475: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2476: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2477: 		"\n";
                   2478: 	}
                   2479: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2480: 	    $result.='<div class="LC_warning">';
1.464     albertel 2481: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2482: 	    $result .= '</div>';
                   2483: 	}         
                   2484: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2485: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2486: 	    $result .= &mt('This student has submitted too many '.
                   2487: 		'collaborators.  Maximum is [_1].',$ncol);
                   2488: 	    $result .= '</div>';
                   2489: 	}
                   2490:     }
                   2491:     return ($result,$fullname,\@col_fullnames);
                   2492: }
                   2493: 
1.44      ng       2494: #--- Retrieve the last submission for all the parts
1.38      ng       2495: sub get_last_submission {
1.119     ng       2496:     my ($returnhash)=@_;
1.596     raeburn  2497:     my (@string,$timestamp,%lasthidden);
1.119     ng       2498:     if ($$returnhash{'version'}) {
1.46      ng       2499: 	my %lasthash=();
                   2500: 	my ($version);
1.119     ng       2501: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2502: 	    foreach my $key (sort(split(/\:/,
                   2503: 					$$returnhash{$version.':keys'}))) {
                   2504: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2505: 		$timestamp = 
1.545     raeburn  2506: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2507: 	    }
                   2508: 	}
1.640     raeburn  2509:         my (%typeparts,%randombytry);
1.596     raeburn  2510:         my $showsurv = 
                   2511:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2512:         foreach my $key (sort(keys(%lasthash))) {
                   2513:             if ($key =~ /\.type$/) {
                   2514:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2515:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2516:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2517:                     my ($ign,@parts) = split(/\./,$key);
                   2518:                     pop(@parts);
1.641     raeburn  2519:                     my $id = join('.',@parts);
1.640     raeburn  2520:                     if ($lasthash{$key} eq 'randomizetry') {
                   2521:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2522:                     } else {
                   2523:                         unless ($showsurv) {
                   2524:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2525:                         }
1.596     raeburn  2526:                     }
                   2527:                     delete($lasthash{$key});
                   2528:                 }
                   2529:             }
                   2530:         }
                   2531:         my @hidden = keys(%typeparts);
1.640     raeburn  2532:         my @randomize = keys(%randombytry);
1.397     albertel 2533: 	foreach my $key (keys(%lasthash)) {
                   2534: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2535:             my $hide;
                   2536:             if (@hidden) {
                   2537:                 foreach my $id (@hidden) {
                   2538:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2539:                         $hide = 'anon';
1.596     raeburn  2540:                         last;
                   2541:                     }
                   2542:                 }
                   2543:             }
1.640     raeburn  2544:             unless ($hide) {
                   2545:                 if (@randomize) {
                   2546:                     foreach my $id (@hidden) {
                   2547:                         if ($key =~ /^\Q$id\E/) {
                   2548:                             $hide = 'rand';
                   2549:                             last;
                   2550:                         }
                   2551:                     }
                   2552:                 }
                   2553:             }
1.397     albertel 2554: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2555: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2556:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2557:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2558:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2559: 	}
                   2560:     }
1.397     albertel 2561:     if (!@string) {
                   2562: 	$string[0] =
1.539     riegler  2563: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2564:     }
                   2565:     return (\@string,\$timestamp);
1.38      ng       2566: }
1.35      ng       2567: 
1.44      ng       2568: #--- High light keywords, with style choosen by user.
1.38      ng       2569: sub keywords_highlight {
1.44      ng       2570:     my $string    = shift;
1.257     albertel 2571:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2572:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2573:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2574:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2575:     foreach my $keyword (@keylist) {
                   2576: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2577:     }
                   2578:     return $string;
1.38      ng       2579: }
1.36      ng       2580: 
1.671     raeburn  2581: # For Tasks provide a mechanism to display previous version for one specific student
                   2582: 
                   2583: sub show_previous_task_version {
                   2584:     my ($request,$symb) = @_;
                   2585:     if ($symb eq '') {
1.717     bisitz   2586:         $request->print(
                   2587:             '<span class="LC_error">'.
                   2588:             &mt('Unable to handle ambiguous references.').
                   2589:             '</span>');
1.671     raeburn  2590:         return '';
                   2591:     }
                   2592:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2593:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2594:     if (!&canview($usec)) {
1.712     bisitz   2595:         $request->print(
                   2596:             '<span class="LC_warning">'.
1.713     bisitz   2597:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2598:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2599:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2600:             '</span>');
1.671     raeburn  2601:         return;
                   2602:     }
                   2603:     my $mode = 'both';
                   2604:     my $isTask = ($symb =~/\.task$/);
                   2605:     if ($isTask) {
                   2606:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2607:             if ($env{'form.fullname'} eq '') {
                   2608:                 $env{'form.fullname'} =
                   2609:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2610:             }
                   2611:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2612:             $request->print("\n\n".
                   2613:                             '<div class="LC_grade_show_user">'.
                   2614:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2615:                             '</h2>'."\n");
                   2616:             &Apache::lonxml::clear_problem_counter();
                   2617:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2618:                             {'previousversion' => $env{'form.previousversion'} }));
                   2619:             $request->print("\n</div>");
                   2620:         }
                   2621:     }
                   2622:     return;
                   2623: }
                   2624: 
                   2625: sub choose_task_version_form {
                   2626:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2627:     my $isTask = ($symb =~/\.task$/);
                   2628:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2629:     if ($isTask) {
                   2630:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2631:                                               $udom,$uname);
                   2632:         if (($record{'resource.0.version'} eq '') ||
                   2633:             ($record{'resource.0.version'} < 2)) {
                   2634:             return ($record{'resource.0.version'},
                   2635:                     $record{'resource.0.version'},$result,$js);
                   2636:         } else {
                   2637:             $current = $record{'resource.0.version'};
                   2638:         }
                   2639:         if ($env{'form.previousversion'}) {
                   2640:             $displayed = $env{'form.previousversion'};
                   2641:             $rowtitle = &mt('Choose another version:')
                   2642:         } else {
                   2643:             $displayed = $current;
                   2644:             $rowtitle = &mt('Show earlier version:');
                   2645:         }
                   2646:         $result = '<div class="LC_left_float">';
                   2647:         my $list;
                   2648:         my $numversions = 0;
                   2649:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2650:             if ($i == $current) {
                   2651:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2652:                     next;
                   2653:                 } else {
                   2654:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2655:                     $numversions ++;
                   2656:                 }
                   2657:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2658:                 unless ($i == $env{'form.previousversion'}) {
                   2659:                     $numversions ++;
                   2660:                 }
                   2661:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2662:             }
                   2663:         }
                   2664:         if ($numversions) {
                   2665:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2666:             $result .=
                   2667:                 '<form name="getprev" method="post" action=""'.
                   2668:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2669:                 &Apache::loncommon::start_data_table().
                   2670:                 &Apache::loncommon::start_data_table_row().
                   2671:                 '<th align="left">'.$rowtitle.'</th>'.
                   2672:                 '<td><select name="version">'.
                   2673:                 '<option>'.&mt('Select').'</option>'.
                   2674:                 $list.
                   2675:                 '</select></td>'.
                   2676:                 &Apache::loncommon::end_data_table_row();
                   2677:             unless ($nomenu) {
                   2678:                 $result .= &Apache::loncommon::start_data_table_row().
                   2679:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2680:                 '<td><span class="LC_nobreak">'.
                   2681:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2682:                 &mt('Yes').'</label>'.
                   2683:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2684:                 '</span></td>'.
                   2685:                 &Apache::loncommon::end_data_table_row();
                   2686:             }
                   2687:             $result .=
                   2688:                 &Apache::loncommon::start_data_table_row().
                   2689:                 '<th align="left">&nbsp;</th>'.
                   2690:                 '<td>'.
                   2691:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2692:                 '</td>'.
                   2693:                 &Apache::loncommon::end_data_table_row().
                   2694:                 &Apache::loncommon::end_data_table().
                   2695:                 '</form>';
                   2696:             $js = &previous_display_javascript($nomenu,$current);
                   2697:         } elsif ($displayed && $nomenu) {
                   2698:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2699:         } else {
                   2700:             $result .= &mt('No previous versions to show for this student');
                   2701:         }
                   2702:         $result .= '</div>';
                   2703:     }
                   2704:     return ($current,$displayed,$result,$js);
                   2705: }
                   2706: 
                   2707: sub previous_display_javascript {
                   2708:     my ($nomenu,$current) = @_;
                   2709:     my $js = <<"JSONE";
                   2710: <script type="text/javascript">
                   2711: // <![CDATA[
                   2712: function previousVersion(uname,udom,symb) {
                   2713:     var current = '$current';
                   2714:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2715:     var prevstr = new RegExp("^\\\\d+\$");
                   2716:     if (!prevstr.test(version)) {
                   2717:         return false;
                   2718:     }
                   2719:     var url = '';
                   2720:     if (version == current) {
                   2721:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2722:     } else {
                   2723:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2724:     }
                   2725: JSONE
                   2726:     if ($nomenu) {
                   2727:         $js .= <<"JSTWO";
                   2728:     document.location.href = url;
                   2729: JSTWO
                   2730:     } else {
                   2731:         $js .= <<"JSTHREE";
                   2732:     var newwin = 0;
                   2733:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2734:         if (document.getprev.prevwin[i].checked == true) {
                   2735:             newwin = document.getprev.prevwin[i].value;
                   2736:         }
                   2737:     }
                   2738:     if (newwin == 1) {
                   2739:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2740:         url = url+'&inhibitmenu=yes';
                   2741:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2742:             previousWin = window.open(url,'',options,1);
                   2743:         } else {
                   2744:             previousWin.location.href = url;
                   2745:         }
                   2746:         previousWin.focus();
                   2747:         return false;
                   2748:     } else {
                   2749:         document.location.href = url;
                   2750:         return false;
                   2751:     }
                   2752: JSTHREE
                   2753:     }
                   2754:     $js .= <<"ENDJS";
                   2755:     return false;
                   2756: }
                   2757: // ]]>
                   2758: </script>
                   2759: ENDJS
                   2760: 
                   2761: }
                   2762: 
1.44      ng       2763: #--- Called from submission routine
1.38      ng       2764: sub processHandGrade {
1.608     www      2765:     my ($request,$symb) = @_;
1.324     albertel 2766:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2767:     my $button = $env{'form.gradeOpt'};
                   2768:     my $ngrade = $env{'form.NCT'};
                   2769:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2770:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2771:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2772: 
1.44      ng       2773:     if ($button eq 'Save & Next') {
                   2774: 	my $ctr = 0;
                   2775: 	while ($ctr < $ngrade) {
1.257     albertel 2776: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2777: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2778: 	    if ($errorflag eq 'no_score') {
                   2779: 		$ctr++;
                   2780: 		next;
                   2781: 	    }
1.104     albertel 2782: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2783: 		$request->print(
                   2784:                     '<span class="LC_error">'
                   2785:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2786:                    .'</span>');
1.104     albertel 2787: 		$ctr++;
                   2788: 		next;
                   2789: 	    }
1.257     albertel 2790: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2791: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2792: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2793:             my ($feedurl,$showsymb) =
                   2794: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2795: 	    my $messagetail;
1.62      albertel 2796: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2797: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2798: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2799: 		$subject.=' ['.$restitle.']';
1.44      ng       2800: 		my (@msgnum) = split(/,/,$includemsg);
                   2801: 		foreach (@msgnum) {
1.257     albertel 2802: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2803: 		}
1.80      ng       2804: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2805: 		if ($env{'form.withgrades'.$ctr}) {
                   2806: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2807: 		    $messagetail = " for <a href=\"".
1.605     www      2808: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2809: 		}
                   2810: 		$msgstatus = 
                   2811:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2812: 						     $message.$messagetail,
1.418     albertel 2813:                                                      undef,$feedurl,undef,
1.386     raeburn  2814:                                                      undef,undef,$showsymb,
                   2815:                                                      $restitle);
1.574     bisitz   2816: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2817: 				$msgstatus.'<br />');
1.44      ng       2818: 	    }
1.257     albertel 2819: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2820: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2821: 		foreach my $collabstr (@collabstrs) {
                   2822: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2823: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2824: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2825: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2826: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2827: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2828: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2829: 			    next;
1.418     albertel 2830: 			} elsif ($message ne '') {
                   2831: 			    my ($baseurl,$showsymb) = 
                   2832: 				&get_feedurl_and_symb($symb,$collaborator,
                   2833: 						      $udom);
                   2834: 			    if ($env{'form.withgrades'.$ctr}) {
                   2835: 				$messagetail = " for <a href=\"".
1.605     www      2836:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2837: 			    }
1.418     albertel 2838: 			    $msgstatus = 
                   2839: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2840: 			}
1.44      ng       2841: 		    }
                   2842: 		}
                   2843: 	    }
                   2844: 	    $ctr++;
                   2845: 	}
                   2846:     }
                   2847: 
1.624     www      2848: #    if ($env{'form.handgrade'} eq 'yes') {
                   2849:     if (1) {
1.119     ng       2850: 	# Keywords sorted in alphabatical order
1.257     albertel 2851: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2852: 	my %keyhash = ();
1.257     albertel 2853: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2854: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2855: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2856: 	$env{'form.keywords'} = join(' ',@keywords);
                   2857: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2858: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2859: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2860: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2861: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2862: 
                   2863: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2864: 	# New messages are saved in env for the next student.
1.119     ng       2865: 	# All messages are saved in nohist_handgrade.db
                   2866: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2867: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2868: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2869: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2870: 		$idx++;
                   2871: 	    }
                   2872: 	    $ctr++;
1.41      ng       2873: 	}
1.119     ng       2874: 	$ctr = 0;
                   2875: 	while ($ctr < $ngrade) {
1.257     albertel 2876: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2877: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2878: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2879: 		$idx++;
                   2880: 	    }
                   2881: 	    $ctr++;
1.41      ng       2882: 	}
1.257     albertel 2883: 	$env{'form.savemsgN'} = --$idx;
                   2884: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2885: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2886: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2887:     }
1.44      ng       2888:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2889:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2890:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2891: 	my ($ctr,$total) = (0,0);
                   2892: 	while ($ctr < $ngrade) {
1.257     albertel 2893: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2894: 	    $ctr++;
                   2895: 	}
1.257     albertel 2896: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2897: 	$ctr = 0;
                   2898: 	while ($ctr < $total) {
1.257     albertel 2899: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2900: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2901: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2902: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2903: 	    $ctr++;
                   2904: 	}
                   2905: 	return '';
                   2906:     }
1.36      ng       2907: 
1.44      ng       2908:     # Get the next/previous one or group of students
1.257     albertel 2909:     my $firststu = $env{'form.unamedom0'};
                   2910:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2911:     my $ctr = 2;
1.41      ng       2912:     while ($laststu eq '') {
1.257     albertel 2913: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2914: 	$ctr++;
                   2915: 	$laststu = $firststu if ($ctr > $ngrade);
                   2916:     }
1.44      ng       2917: 
1.41      ng       2918:     my (@parsedlist,@nextlist);
                   2919:     my ($nextflg) = 0;
1.524     raeburn  2920:     foreach my $item (sort 
1.294     albertel 2921: 	     {
                   2922: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2923: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2924: 		 }
                   2925: 		 return $a cmp $b;
                   2926: 	     } (keys(%$fullname))) {
1.605     www      2927: # FIXME: this is fishy, looks like the button label
1.41      ng       2928: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2929: 	    push(@parsedlist,$item);
1.41      ng       2930: 	}
1.524     raeburn  2931: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2932: 	if ($button eq 'Previous') {
1.524     raeburn  2933: 	    last if ($item eq $firststu);
                   2934: 	    push(@parsedlist,$item);
1.41      ng       2935: 	}
                   2936:     }
                   2937:     $ctr = 0;
1.605     www      2938: # FIXME: this is fishy, looks like the button label
1.41      ng       2939:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2940:     my $res_error;
                   2941:     my ($partlist) = &response_type($symb,\$res_error);
                   2942:     if ($res_error) {
                   2943:         $request->print(&navmap_errormsg());
                   2944:         return;
                   2945:     }
1.41      ng       2946:     foreach my $student (@parsedlist) {
1.257     albertel 2947: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2948: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2949: 	
                   2950: 	if ($submitonly eq 'queued') {
                   2951: 	    my %queue_status = 
                   2952: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2953: 							$udom,$uname);
                   2954: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2955: 	}
                   2956: 
1.156     albertel 2957: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2958: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2959: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2960: 	    my $submitted = 0;
1.248     albertel 2961: 	    my $ungraded = 0;
                   2962: 	    my $incorrect = 0;
1.524     raeburn  2963: 	    foreach my $item (keys(%status)) {
                   2964: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2965: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2966: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2967: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2968: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2969: 		    $submitted = 0;
                   2970: 		}
1.41      ng       2971: 	    }
1.156     albertel 2972: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2973: 				     $submitonly eq 'incorrect' ||
                   2974: 				     $submitonly eq 'graded'));
1.248     albertel 2975: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2976: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2977: 	}
1.524     raeburn  2978: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2979: 	last if ($ctr == $ntstu);
1.41      ng       2980: 	$ctr++;
                   2981:     }
1.36      ng       2982: 
1.41      ng       2983:     $ctr = 0;
                   2984:     my $total = scalar(@nextlist)-1;
1.39      ng       2985: 
1.524     raeburn  2986:     foreach (sort(@nextlist)) {
1.41      ng       2987: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2988: 	$env{'form.student'}  = $uname;
                   2989: 	$env{'form.userdom'}  = $udom;
                   2990: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2991: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2992: 	$ctr++;
                   2993:     }
                   2994:     if ($total < 0) {
1.653     raeburn  2995: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2996: 	$request->print($the_end);
                   2997:     }
                   2998:     return '';
1.38      ng       2999: }
1.36      ng       3000: 
1.44      ng       3001: #---- Save the score and award for each student, if changed
1.38      ng       3002: sub saveHandGrade {
1.324     albertel 3003:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3004:     my @version_parts;
1.104     albertel 3005:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3006: 					   $env{'request.course.id'});
1.104     albertel 3007:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3008:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3009:     my @parts_graded;
1.77      ng       3010:     my %newrecord  = ();
                   3011:     my ($pts,$wgt) = ('','');
1.269     raeburn  3012:     my %aggregate = ();
                   3013:     my $aggregateflag = 0;
1.301     albertel 3014:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3015:     foreach my $new_part (@parts) {
1.337     banghart 3016: 	#collaborator ($submi may vary for different parts
1.259     banghart 3017: 	if ($submitter && $new_part ne $part) { next; }
                   3018: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3019: 	if ($dropMenu eq 'excused') {
1.259     banghart 3020: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3021: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3022: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3023: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3024: 		}
1.364     banghart 3025: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3026: 	    }
1.125     ng       3027: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3028: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3029: 	    foreach my $key (keys(%record)) {
1.259     banghart 3030: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3031: 	    }
1.259     banghart 3032: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3033: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3034:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3035: 
                   3036:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3037: 					       [$new_part]);
                   3038:             my $aggtries =$totaltries;
1.269     raeburn  3039:             if ($last_resets{$new_part}) {
1.270     albertel 3040:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3041: 					   $new_part);
1.269     raeburn  3042:             }
1.270     albertel 3043: 
                   3044:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3045:             if ($aggtries > 0) {
1.327     albertel 3046:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3047:                 $aggregateflag = 1;
                   3048:             }
1.125     ng       3049: 	} elsif ($dropMenu eq '') {
1.259     banghart 3050: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3051: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3052: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3053: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3054: 		next;
                   3055: 	    }
1.259     banghart 3056: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3057: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3058: 	    my $partial= $pts/$wgt;
1.259     banghart 3059: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3060: 		#do not update score for part if not changed.
1.346     banghart 3061:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3062: 		next;
1.251     banghart 3063: 	    } else {
1.524     raeburn  3064: 	        push(@parts_graded,$new_part);
1.153     albertel 3065: 	    }
1.259     banghart 3066: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3067: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3068: 	    }
1.259     banghart 3069: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3070: 	    if ($partial == 0) {
1.153     albertel 3071: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3072: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3073: 		}
1.41      ng       3074: 	    } else {
1.153     albertel 3075: 		if ($record{$reckey} ne 'correct_by_override') {
                   3076: 		    $newrecord{$reckey} = 'correct_by_override';
                   3077: 		}
                   3078: 	    }	    
                   3079: 	    if ($submitter && 
1.259     banghart 3080: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3081: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3082: 	    }
1.259     banghart 3083: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3084: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3085: 	}
1.259     banghart 3086: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3087: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3088: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3089: 	        $dropMenu eq 'reset status')
                   3090: 	   {
1.524     raeburn  3091: 	    push(@version_parts,$new_part);
1.259     banghart 3092: 	}
1.41      ng       3093:     }
1.301     albertel 3094:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3095:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3096: 
1.344     albertel 3097:     if (%newrecord) {
                   3098:         if (@version_parts) {
1.364     banghart 3099:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3100:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3101: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3102: 	    foreach my $new_part (@version_parts) {
                   3103: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3104: 				$new_part,\%newrecord);
                   3105: 	    }
1.259     banghart 3106:         }
1.44      ng       3107: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3108: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3109: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3110: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3111:     }
1.269     raeburn  3112:     if ($aggregateflag) {
                   3113:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3114: 			      $cdom,$cnum);
1.269     raeburn  3115:     }
1.301     albertel 3116:     return ('',$pts,$wgt);
1.36      ng       3117: }
1.322     albertel 3118: 
1.380     albertel 3119: sub check_and_remove_from_queue {
                   3120:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3121:     my @ungraded_parts;
                   3122:     foreach my $part (@{$parts}) {
                   3123: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3124: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3125: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3126: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3127: 		) {
                   3128: 	    push(@ungraded_parts, $part);
                   3129: 	}
                   3130:     }
                   3131:     if ( !@ungraded_parts ) {
                   3132: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3133: 					       $cnum,$domain,$stuname);
                   3134:     }
                   3135: }
                   3136: 
1.337     banghart 3137: sub handback_files {
                   3138:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3139:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3140:     my $res_error;
                   3141:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3142:     if ($res_error) {
                   3143:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3144:         return;
                   3145:     }
1.654     raeburn  3146:     my @handedback;
                   3147:     my $file_msg;
1.375     albertel 3148:     my @part_response_id = &flatten_responseType($responseType);
                   3149:     foreach my $part_response_id (@part_response_id) {
                   3150:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3151: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3152:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3153:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3154:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3155:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3156:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3157:                     my ($directory,$answer_file) = 
1.654     raeburn  3158:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3159:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3160: 		        &file_name_version_ext($answer_file);
1.355     banghart 3161: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3162:                     my $getpropath = 1;
1.662     raeburn  3163:                     my ($dir_list,$listerror) = 
                   3164:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3165:                                                  $domain,$stuname,$getpropath);
                   3166: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3167:                     # fix filename
1.355     banghart 3168:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3169:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3170:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3171:             	                                $save_file_name);
1.337     banghart 3172:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3173:                         $request->print('<br /><span class="LC_error">'.
                   3174:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3175:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3176:                                         '</span>');
1.356     banghart 3177:                     } else {
1.360     banghart 3178:                         # mark the file as read only
1.654     raeburn  3179:                         push(@handedback,$save_file_name);
1.367     albertel 3180: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3181: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3182: 			}
                   3183:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3184: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3185:                     }
1.686     bisitz   3186:                     $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 3187:                 }
                   3188:             }
                   3189:         }
1.654     raeburn  3190:     }
                   3191:     if (@handedback > 0) {
                   3192:         $request->print('<br />');
                   3193:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3194:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3195:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3196:         my ($subject,$message);
                   3197:         if (scalar(@handedback) == 1) {
                   3198:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3199:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3200:         } else {
                   3201:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3202:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3203:         }
                   3204:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3205:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3206:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3207:         my ($feedurl,$showsymb) =
                   3208:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3209:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3210:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3211:         my $msgstatus =
                   3212:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3213:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3214:                  $restitle);
                   3215:         if ($msgstatus) {
                   3216:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3217:         }
                   3218:     }
1.338     banghart 3219:     return;
1.337     banghart 3220: }
                   3221: 
1.418     albertel 3222: sub get_feedurl_and_symb {
                   3223:     my ($symb,$uname,$udom) = @_;
                   3224:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3225:     $url = &Apache::lonnet::clutter($url);
                   3226:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3227: 					$symb,$udom,$uname);
                   3228:     if ($encrypturl =~ /^yes$/i) {
                   3229: 	&Apache::lonenc::encrypted(\$url,1);
                   3230: 	&Apache::lonenc::encrypted(\$symb,1);
                   3231:     }
                   3232:     return ($url,$symb);
                   3233: }
                   3234: 
1.313     banghart 3235: sub get_submitted_files {
                   3236:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3237:     my @files;
                   3238:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3239:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3240:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3241:     	    push(@files,$file_url.$file);
                   3242:         }
                   3243:     }
                   3244:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3245:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3246:     }
                   3247:     return (\@files);
                   3248: }
1.322     albertel 3249: 
1.269     raeburn  3250: # ----------- Provides number of tries since last reset.
                   3251: sub get_num_tries {
                   3252:     my ($record,$last_reset,$part) = @_;
                   3253:     my $timestamp = '';
                   3254:     my $num_tries = 0;
                   3255:     if ($$record{'version'}) {
                   3256:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3257:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3258:                 $timestamp = $$record{$version.':timestamp'};
                   3259:                 if ($timestamp > $last_reset) {
                   3260:                     $num_tries ++;
                   3261:                 } else {
                   3262:                     last;
                   3263:                 }
                   3264:             }
                   3265:         }
                   3266:     }
                   3267:     return $num_tries;
                   3268: }
                   3269: 
                   3270: # ----------- Determine decrements required in aggregate totals 
                   3271: sub decrement_aggs {
                   3272:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3273:     my %decrement = (
                   3274:                         attempts => 0,
                   3275:                         users => 0,
                   3276:                         correct => 0
                   3277:                     );
                   3278:     $decrement{'attempts'} = $aggtries;
                   3279:     if ($solvedstatus =~ /^correct/) {
                   3280:         $decrement{'correct'} = 1;
                   3281:     }
                   3282:     if ($aggtries == $totaltries) {
                   3283:         $decrement{'users'} = 1;
                   3284:     }
1.524     raeburn  3285:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3286:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3287:     }
                   3288:     return;
                   3289: }
                   3290: 
                   3291: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3292: sub get_last_resets {
1.270     albertel 3293:     my ($symb,$courseid,$partids) =@_;
                   3294:     my %last_resets;
1.269     raeburn  3295:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3296:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3297:     my @keys;
                   3298:     foreach my $part (@{$partids}) {
                   3299: 	push(@keys,"$symb\0$part\0resettime");
                   3300:     }
                   3301:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3302: 				     $cdom,$cname);
                   3303:     foreach my $part (@{$partids}) {
                   3304: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3305:     }
1.270     albertel 3306:     return %last_resets;
1.269     raeburn  3307: }
                   3308: 
1.251     banghart 3309: # ----------- Handles creating versions for portfolio files as answers
                   3310: sub version_portfiles {
1.343     banghart 3311:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3312:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3313:     my @returned_keys;
1.255     banghart 3314:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3315:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3316:     foreach my $key (keys(%$record)) {
1.259     banghart 3317:         my $new_portfiles;
1.263     banghart 3318:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3319:             my @versioned_portfiles;
1.367     albertel 3320:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3321:             foreach my $file (@portfiles) {
1.306     banghart 3322:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3323:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3324: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3325: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3326:                 my $getpropath = 1;    
1.662     raeburn  3327:                 my ($dir_list,$listerror) = 
                   3328:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3329:                                              $stu_name,$getpropath);
                   3330:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3331:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3332:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3333:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3334:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3335:                         [$directory.$new_answer],
1.306     banghart 3336:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3337:                 }
1.252     banghart 3338:             }
1.343     banghart 3339:             $$record{$key} = join(',',@versioned_portfiles);
                   3340:             push(@returned_keys,$key);
1.251     banghart 3341:         }
                   3342:     } 
1.343     banghart 3343:     return (@returned_keys);   
1.305     banghart 3344: }
                   3345: 
1.307     banghart 3346: sub get_next_version {
1.341     banghart 3347:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3348:     my $version;
1.662     raeburn  3349:     if (ref($dir_list) eq 'ARRAY') {
                   3350:         foreach my $row (@{$dir_list}) {
                   3351:             my ($file) = split(/\&/,$row,2);
                   3352:             my ($file_name,$file_version,$file_ext) =
                   3353: 	        &file_name_version_ext($file);
                   3354:             if (($file_name eq $answer_name) && 
                   3355: 	        ($file_ext eq $answer_ext)) {
                   3356:                      # gets here if filename and extension match, 
                   3357:                      # regardless of version
1.307     banghart 3358:                 if ($file_version ne '') {
1.662     raeburn  3359:                     # a versioned file is found  so save it for later
                   3360:                     if ($file_version > $version) {
                   3361: 		        $version = $file_version;
                   3362: 	            }
                   3363:                 }
1.307     banghart 3364:             }
                   3365:         }
1.662     raeburn  3366:     }
1.307     banghart 3367:     $version ++;
                   3368:     return($version);
                   3369: }
                   3370: 
1.305     banghart 3371: sub version_selected_portfile {
1.306     banghart 3372:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3373:     my ($answer_name,$answer_ver,$answer_ext) =
                   3374:         &file_name_version_ext($file_name);
                   3375:     my $new_answer;
                   3376:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3377:     if($env{'form.copy'} eq '-1') {
                   3378:         $new_answer = 'problem getting file';
                   3379:     } else {
                   3380:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3381:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3382:                             $stu_name,$domain,'copy',
                   3383: 		        '/portfolio'.$directory.$new_answer);
                   3384:     }    
                   3385:     return ($new_answer);
1.251     banghart 3386: }
                   3387: 
1.304     albertel 3388: sub file_name_version_ext {
                   3389:     my ($file)=@_;
                   3390:     my @file_parts = split(/\./, $file);
                   3391:     my ($name,$version,$ext);
                   3392:     if (@file_parts > 1) {
                   3393: 	$ext=pop(@file_parts);
                   3394: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3395: 	    $version=pop(@file_parts);
                   3396: 	}
                   3397: 	$name=join('.',@file_parts);
                   3398:     } else {
                   3399: 	$name=join('.',@file_parts);
                   3400:     }
                   3401:     return($name,$version,$ext);
                   3402: }
                   3403: 
1.44      ng       3404: #--------------------------------------------------------------------------------------
                   3405: #
                   3406: #-------------------------- Next few routines handles grading by section or whole class
                   3407: #
                   3408: #--- Javascript to handle grading by section or whole class
1.42      ng       3409: sub viewgrades_js {
                   3410:     my ($request) = shift;
                   3411: 
1.539     riegler  3412:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3413:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3414:    function writePoint(partid,weight,point) {
1.125     ng       3415: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3416: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3417: 	if (point == "textval") {
1.125     ng       3418: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3419: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3420: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3421: 		var resetbox = false;
                   3422: 		for (var i=0; i<radioButton.length; i++) {
                   3423: 		    if (radioButton[i].checked) {
                   3424: 			textbox.value = i;
                   3425: 			resetbox = true;
                   3426: 		    }
                   3427: 		}
                   3428: 		if (!resetbox) {
                   3429: 		    textbox.value = "";
                   3430: 		}
                   3431: 		return;
                   3432: 	    }
1.109     matthew  3433: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3434: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3435: 				   ") greater than the weight for the part. Accept?");
                   3436: 		if (resp == false) {
                   3437: 		    textbox.value = "";
                   3438: 		    return;
                   3439: 		}
                   3440: 	    }
1.42      ng       3441: 	    for (var i=0; i<radioButton.length; i++) {
                   3442: 		radioButton[i].checked=false;
1.109     matthew  3443: 		if (parseFloat(point) == i) {
1.42      ng       3444: 		    radioButton[i].checked=true;
                   3445: 		}
                   3446: 	    }
1.41      ng       3447: 
1.42      ng       3448: 	} else {
1.125     ng       3449: 	    textbox.value = parseFloat(point);
1.42      ng       3450: 	}
1.41      ng       3451: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3452: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3453: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3454: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3455: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3456: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3457: 	    if (saveval != "correct") {
                   3458: 		scorename.value = point;
1.43      ng       3459: 		if (selname[0].selected != true) {
                   3460: 		    selname[0].selected = true;
                   3461: 		}
1.42      ng       3462: 	    }
                   3463: 	}
1.125     ng       3464: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3465:     }
                   3466: 
                   3467:     function writeRadText(partid,weight) {
1.125     ng       3468: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3469: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3470:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3471: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3472: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3473: 	    for (var i=0; i<radioButton.length; i++) {
                   3474: 		radioButton[i].checked=false;
                   3475: 
                   3476: 	    }
                   3477: 	    textbox.value = "";
                   3478: 
                   3479: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3480: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3481: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3482: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3483: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3484: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3485: 		if ((saveval != "correct") || override) {
1.42      ng       3486: 		    scorename.value = "";
1.125     ng       3487: 		    if (selval[1].selected) {
                   3488: 			selname[1].selected = true;
                   3489: 		    } else {
                   3490: 			selname[2].selected = true;
                   3491: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3492: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3493: 		    }
1.42      ng       3494: 		}
                   3495: 	    }
1.43      ng       3496: 	} else {
                   3497: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3498: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3499: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3500: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3501: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3502: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3503: 		if ((saveval != "correct") || override) {
1.125     ng       3504: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3505: 		    selname[0].selected = true;
                   3506: 		}
                   3507: 	    }
                   3508: 	}	    
1.42      ng       3509:     }
                   3510: 
                   3511:     function changeSelect(partid,user) {
1.125     ng       3512: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3513: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3514: 	var point  = textbox.value;
1.125     ng       3515: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3516: 
1.109     matthew  3517: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3518: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3519: 	    textbox.value = "";
                   3520: 	    return;
                   3521: 	}
1.109     matthew  3522: 	if (parseFloat(point) > parseFloat(weight)) {
                   3523: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3524: 			       ") greater than the weight of the part. Accept?");
                   3525: 	    if (resp == false) {
                   3526: 		textbox.value = "";
                   3527: 		return;
                   3528: 	    }
                   3529: 	}
1.42      ng       3530: 	selval[0].selected = true;
                   3531:     }
                   3532: 
                   3533:     function changeOneScore(partid,user) {
1.125     ng       3534: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3535: 	if (selval[1].selected || selval[2].selected) {
                   3536: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3537: 	    if (selval[2].selected) {
                   3538: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3539: 	    }
1.269     raeburn  3540:         }
1.42      ng       3541:     }
                   3542: 
                   3543:     function resetEntry(numpart) {
                   3544: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3545: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3546: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3547: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3548: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3549: 	    for (var i=0; i<radioButton.length; i++) {
                   3550: 		radioButton[i].checked=false;
                   3551: 
                   3552: 	    }
                   3553: 	    textbox.value = "";
                   3554: 	    selval[0].selected = true;
                   3555: 
                   3556: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3557: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3558: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3559: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3560: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3561: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3562: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3563: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3564: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3565: 		if (saveselval == "excused") {
1.43      ng       3566: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3567: 		} else {
1.43      ng       3568: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3569: 		}
                   3570: 	    }
1.41      ng       3571: 	}
1.42      ng       3572:     }
                   3573: 
1.41      ng       3574: VIEWJAVASCRIPT
1.42      ng       3575: }
                   3576: 
1.44      ng       3577: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3578: sub viewgrades {
1.608     www      3579:     my ($request,$symb) = @_;
1.42      ng       3580:     &viewgrades_js($request);
1.41      ng       3581: 
1.168     albertel 3582:     #need to make sure we have the correct data for later EXT calls, 
                   3583:     #thus invalidate the cache
                   3584:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3585:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3586:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3587:     &Apache::lonnet::clear_EXT_cache_status();
                   3588: 
1.398     albertel 3589:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3590: 
                   3591:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3592:     $result.=&jscriptNform($symb);
1.41      ng       3593: 
1.44      ng       3594:     #beginning of class grading form
1.442     banghart 3595:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3596:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3597: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3598: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3599: 	&build_section_inputs().
1.442     banghart 3600: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3601: 
1.560     raeburn  3602:     my ($common_header,$specific_header);
1.257     albertel 3603:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3604: 	$common_header = &mt('Assign Common Grade to Class');
                   3605:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3606:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3607:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3608: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3609:     } else {
1.560     raeburn  3610:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3611:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3612: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3613:     }
1.560     raeburn  3614:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3615:     #radio buttons/text box for assigning points for a section or class.
                   3616:     #handles different parts of a problem
1.582     raeburn  3617:     my $res_error;
                   3618:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3619:     if ($res_error) {
                   3620:         return &navmap_errormsg();
                   3621:     }
1.42      ng       3622:     my %weight = ();
                   3623:     my $ctsparts = 0;
1.45      ng       3624:     my %seen = ();
1.375     albertel 3625:     my @part_response_id = &flatten_responseType($responseType);
                   3626:     foreach my $part_response_id (@part_response_id) {
                   3627:     	my ($partid,$respid) = @{ $part_response_id };
                   3628: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3629: 	next if $seen{$partid};
                   3630: 	$seen{$partid}++;
1.375     albertel 3631: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3632: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3633: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3634: 
1.324     albertel 3635: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3636: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3637: 	my $ctr = 0;
1.42      ng       3638: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3639: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3640: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3641: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3642: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3643: 	    $ctr++;
                   3644: 	}
1.485     albertel 3645: 	$radio.='</tr></table>';
                   3646: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3647: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3648: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3649: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3650:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3651:             '<select name="SELVAL_'.$partid.'" '.
                   3652:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3653:                 $weight{$partid}.')"> '.
1.401     albertel 3654: 	    '<option selected="selected"> </option>'.
1.485     albertel 3655: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3656: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3657: 	    '</select></td>'.
                   3658:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3659: 	$line.='<input type="hidden" name="partid_'.
                   3660: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3661: 	$line.='<input type="hidden" name="weight_'.
                   3662: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3663: 
                   3664: 	$result.=
                   3665: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3666: 	    '<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 3667: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3668: 	$ctsparts++;
1.41      ng       3669:     }
1.474     albertel 3670:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3671: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3672:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3673: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3674: 
1.44      ng       3675:     #table listing all the students in a section/class
                   3676:     #header of table
1.560     raeburn  3677:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3678:               &Apache::loncommon::start_data_table().
                   3679: 	      &Apache::loncommon::start_data_table_header_row().
                   3680: 	      '<th>'.&mt('No.').'</th>'.
                   3681: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3682:     my $partserror;
                   3683:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3684:     if ($partserror) {
                   3685:         return &navmap_errormsg();
                   3686:     }
1.324     albertel 3687:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3688:     my @partids = ();
1.41      ng       3689:     foreach my $part (@parts) {
                   3690: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3691:         my $narrowtext = &mt('Tries');
                   3692: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3693: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3694: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3695:         push(@partids,$partid);
1.628     www      3696: #
                   3697: # FIXME: Looks like $display looks at English text
                   3698: #
1.324     albertel 3699: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3700: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3701: 	    $result.='<th>'.
1.697     bisitz   3702: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3703: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3704: 	    next;
1.485     albertel 3705: 	    
1.207     albertel 3706: 	} else {
1.485     albertel 3707: 	    if ($display =~ /Problem Status/) {
                   3708: 		my $grade_status_mt = &mt('Grade Status');
                   3709: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3710: 	    }
                   3711: 	    my $part_mt = &mt('Part:');
                   3712: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3713: 	}
1.485     albertel 3714: 
1.474     albertel 3715: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3716:     }
1.474     albertel 3717:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3718: 
1.270     albertel 3719:     my %last_resets = 
                   3720: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3721: 
1.41      ng       3722:     #get info for each student
1.44      ng       3723:     #list all the students - with points and grade status
1.257     albertel 3724:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3725:     my $ctr = 0;
1.294     albertel 3726:     foreach (sort 
                   3727: 	     {
                   3728: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3729: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3730: 		 }
                   3731: 		 return $a cmp $b;
                   3732: 	     } (keys(%$fullname))) {
1.126     ng       3733: 	$ctr++;
1.324     albertel 3734: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3735: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3736:     }
1.474     albertel 3737:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3738:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3739:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3740: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3741:     if (scalar(%$fullname) eq 0) {
                   3742: 	my $colspan=3+scalar(@parts);
1.433     banghart 3743: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3744:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3745: 	$result='<span class="LC_warning">'.
1.485     albertel 3746: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3747: 	        $section_display, $stu_status).
1.433     banghart 3748: 	    '</span>';
1.96      albertel 3749:     }
1.41      ng       3750:     return $result;
                   3751: }
                   3752: 
1.44      ng       3753: #--- call by previous routine to display each student
1.41      ng       3754: sub viewstudentgrade {
1.324     albertel 3755:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3756:     my ($uname,$udom) = split(/:/,$student);
                   3757:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3758:     my %aggregates = (); 
1.474     albertel 3759:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3760: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3761: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3762: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3763: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3764: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3765:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3766:     foreach my $apart (@$parts) {
                   3767: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3768: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3769:         $result.='<td align="center">';
1.269     raeburn  3770:         my ($aggtries,$totaltries);
                   3771:         unless (exists($aggregates{$part})) {
1.270     albertel 3772: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3773: 
                   3774: 	    $aggtries = $totaltries;
1.269     raeburn  3775:             if ($$last_resets{$part}) {  
1.270     albertel 3776:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3777: 					   $part);
                   3778:             }
1.269     raeburn  3779:             $result.='<input type="hidden" name="'.
                   3780:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3781:             $result.='<input type="hidden" name="'.
                   3782:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3783:             $aggregates{$part} = 1;
                   3784:         }
1.41      ng       3785: 	if ($type eq 'awarded') {
1.320     albertel 3786: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3787: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3788: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3789: 	    $result.='<input type="text" name="'.
1.89      albertel 3790: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3791:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3792: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3793: 	} elsif ($type eq 'solved') {
                   3794: 	    my ($status,$foo)=split(/_/,$score,2);
                   3795: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3796: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3797: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3798: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3799: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3800:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3801: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3802: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3803: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3804: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3805: 	} else {
                   3806: 	    $result.='<input type="hidden" name="'.
                   3807: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3808: 		    "\n";
1.233     albertel 3809: 	    $result.='<input type="text" name="'.
1.122     ng       3810: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3811: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3812: 	}
                   3813:     }
1.474     albertel 3814:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3815:     return $result;
1.38      ng       3816: }
                   3817: 
1.44      ng       3818: #--- change scores for all the students in a section/class
                   3819: #    record does not get update if unchanged
1.38      ng       3820: sub editgrades {
1.608     www      3821:     my ($request,$symb) = @_;
1.41      ng       3822: 
1.433     banghart 3823:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3824:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3825:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3826: 
1.477     albertel 3827:     my $result= &Apache::loncommon::start_data_table().
                   3828: 	&Apache::loncommon::start_data_table_header_row().
                   3829: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3830: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3831:     my %scoreptr = (
                   3832: 		    'correct'  =>'correct_by_override',
                   3833: 		    'incorrect'=>'incorrect_by_override',
                   3834: 		    'excused'  =>'excused',
                   3835: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3836:                     'credited' =>'credit_attempted',
1.43      ng       3837: 		    'nothing'  => '',
                   3838: 		    );
1.257     albertel 3839:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3840: 
1.44      ng       3841:     my (@partid);
                   3842:     my %weight = ();
1.54      albertel 3843:     my %columns = ();
1.44      ng       3844:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3845: 
1.582     raeburn  3846:     my $partserror;
                   3847:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3848:     if ($partserror) {
                   3849:         return &navmap_errormsg();
                   3850:     }
1.54      albertel 3851:     my $header;
1.257     albertel 3852:     while ($ctr < $env{'form.totalparts'}) {
                   3853: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3854: 	push(@partid,$partid);
1.257     albertel 3855: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3856: 	$ctr++;
1.54      albertel 3857:     }
1.324     albertel 3858:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3859:     foreach my $partid (@partid) {
1.478     albertel 3860: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3861: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3862: 	$columns{$partid}=2;
                   3863: 	foreach my $stores (@parts) {
                   3864: 	    my ($part,$type) = &split_part_type($stores);
                   3865: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3866: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3867: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3868: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3869:             my $narrowtext = &mt('Tries');
                   3870: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3871: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3872: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3873: 	    $columns{$partid}+=2;
                   3874: 	}
                   3875:     }
                   3876:     foreach my $partid (@partid) {
1.324     albertel 3877: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3878: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3879: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3880: 	    '</th>';
1.54      albertel 3881: 
1.44      ng       3882:     }
1.477     albertel 3883:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3884: 	&Apache::loncommon::start_data_table_header_row().
                   3885: 	$header.
                   3886: 	&Apache::loncommon::end_data_table_header_row();
                   3887:     my @noupdate;
1.126     ng       3888:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3889:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3890: 	my $line;
1.257     albertel 3891: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3892: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3893: 	my %newrecord;
                   3894: 	my $updateflag = 0;
1.281     albertel 3895: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3896: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3897: 	if (!&canmodify($usec)) {
1.126     ng       3898: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3899: 	    push(@noupdate,
1.478     albertel 3900: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3901: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3902: 	    next;
                   3903: 	}
1.269     raeburn  3904:         my %aggregate = ();
                   3905:         my $aggregateflag = 0;
1.281     albertel 3906: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3907: 	foreach (@partid) {
1.257     albertel 3908: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3909: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3910: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3911: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3912: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3913: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3914: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3915: 	    my $score;
                   3916: 	    if ($partial eq '') {
1.257     albertel 3917: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3918: 	    } elsif ($partial > 0) {
                   3919: 		$score = 'correct_by_override';
                   3920: 	    } elsif ($partial == 0) {
                   3921: 		$score = 'incorrect_by_override';
                   3922: 	    }
1.257     albertel 3923: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3924: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3925: 
1.292     albertel 3926: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3927: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3928: 	    if ($dropMenu eq 'reset status' &&
                   3929: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3930: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3931: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3932: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3933: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3934: 		$updateflag = 1;
1.269     raeburn  3935:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3936:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3937:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3938:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3939:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3940:                     $aggregateflag = 1;
                   3941:                 }
1.139     albertel 3942: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3943: 		$updateflag = 1;
                   3944: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3945: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3946: 		$rec_update++;
1.125     ng       3947: 	    }
                   3948: 
1.93      albertel 3949: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3950: 		'<td align="center">'.$awarded.
                   3951: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3952: 
1.54      albertel 3953: 
                   3954: 	    my $partid=$_;
                   3955: 	    foreach my $stores (@parts) {
                   3956: 		my ($part,$type) = &split_part_type($stores);
                   3957: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3958: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3959: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3960: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3961: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3962: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3963: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3964: 		    $updateflag=1;
                   3965: 		}
1.93      albertel 3966: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3967: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3968: 	    }
1.44      ng       3969: 	}
1.477     albertel 3970: 	$line.="\n";
1.301     albertel 3971: 
                   3972: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3973: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3974: 
1.44      ng       3975: 	if ($updateflag) {
                   3976: 	    $count++;
1.257     albertel 3977: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3978: 				    $udom,$uname);
1.301     albertel 3979: 
                   3980: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3981: 					      $cnum,$udom,$uname)) {
                   3982: 		# need to figure out if should be in queue.
                   3983: 		my %record =  
                   3984: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3985: 					     $udom,$uname);
                   3986: 		my $all_graded = 1;
                   3987: 		my $none_graded = 1;
                   3988: 		foreach my $part (@parts) {
                   3989: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3990: 			$all_graded = 0;
                   3991: 		    } else {
                   3992: 			$none_graded = 0;
                   3993: 		    }
                   3994: 		}
                   3995: 
                   3996: 		if ($all_graded || $none_graded) {
                   3997: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3998: 							   $symb,$cdom,$cnum,
                   3999: 							   $udom,$uname);
                   4000: 		}
                   4001: 	    }
                   4002: 
1.477     albertel 4003: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4004: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4005: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4006: 	    $updateCtr++;
1.93      albertel 4007: 	} else {
1.477     albertel 4008: 	    push(@noupdate,
                   4009: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4010: 	    $noupdateCtr++;
1.44      ng       4011: 	}
1.269     raeburn  4012:         if ($aggregateflag) {
                   4013:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4014: 				  $cdom,$cnum);
1.269     raeburn  4015:         }
1.93      albertel 4016:     }
1.477     albertel 4017:     if (@noupdate) {
1.126     ng       4018: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4019: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4020: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4021: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4022: 	    &mt('No Changes Occurred For the Students Below').
                   4023: 	    '</td>'.
1.477     albertel 4024: 	    &Apache::loncommon::end_data_table_row();
                   4025: 	foreach my $line (@noupdate) {
                   4026: 	    $result.=
                   4027: 		&Apache::loncommon::start_data_table_row().
                   4028: 		$line.
                   4029: 		&Apache::loncommon::end_data_table_row();
                   4030: 	}
1.44      ng       4031:     }
1.614     www      4032:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4033:     my $msg = '<p><b>'.
                   4034: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4035: 	    $rec_update,$count).'</b><br />'.
                   4036: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4037: 	'</b></p>';
1.44      ng       4038:     return $title.$msg.$result;
1.5       albertel 4039: }
1.54      albertel 4040: 
                   4041: sub split_part_type {
                   4042:     my ($partstr) = @_;
                   4043:     my ($temp,@allparts)=split(/_/,$partstr);
                   4044:     my $type=pop(@allparts);
1.439     albertel 4045:     my $part=join('_',@allparts);
1.54      albertel 4046:     return ($part,$type);
                   4047: }
                   4048: 
1.44      ng       4049: #------------- end of section for handling grading by section/class ---------
                   4050: #
                   4051: #----------------------------------------------------------------------------
                   4052: 
1.5       albertel 4053: 
1.44      ng       4054: #----------------------------------------------------------------------------
                   4055: #
                   4056: #-------------------------- Next few routines handles grading by csv upload
                   4057: #
                   4058: #--- Javascript to handle csv upload
1.27      albertel 4059: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4060:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4061:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4062:   return(<<ENDPICK);
                   4063:   function verify(vf) {
                   4064:     var foundsomething=0;
                   4065:     var founduname=0;
1.243     albertel 4066:     var foundID=0;
1.27      albertel 4067:     for (i=0;i<=vf.nfields.value;i++) {
                   4068:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4069:       if (i==0 && tw!=0) { foundID=1; }
                   4070:       if (i==1 && tw!=0) { founduname=1; }
                   4071:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4072:     }
1.246     albertel 4073:     if (founduname==0 && foundID==0) {
                   4074: 	alert('$error1');
                   4075: 	return;
1.27      albertel 4076:     }
                   4077:     if (foundsomething==0) {
1.246     albertel 4078: 	alert('$error2');
                   4079: 	return;
1.27      albertel 4080:     }
                   4081:     vf.submit();
                   4082:   }
                   4083:   function flip(vf,tf) {
                   4084:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4085:     var i;
                   4086:     for (i=0;i<=vf.nfields.value;i++) {
                   4087:       //can not pick the same destination field for both name and domain
                   4088:       if (((i ==0)||(i ==1)) && 
                   4089:           ((tf==0)||(tf==1)) && 
                   4090:           (i!=tf) &&
                   4091:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4092:         eval('vf.f'+i+'.selectedIndex=0;')
                   4093:       }
                   4094:     }
                   4095:   }
                   4096: ENDPICK
                   4097: }
                   4098: 
                   4099: sub csvupload_javascript_forward_associate {
1.573     bisitz   4100:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4101:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4102:   return(<<ENDPICK);
                   4103:   function verify(vf) {
                   4104:     var foundsomething=0;
                   4105:     var founduname=0;
1.243     albertel 4106:     var foundID=0;
1.27      albertel 4107:     for (i=0;i<=vf.nfields.value;i++) {
                   4108:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4109:       if (tw==1) { foundID=1; }
                   4110:       if (tw==2) { founduname=1; }
                   4111:       if (tw>3) { foundsomething=1; }
1.27      albertel 4112:     }
1.246     albertel 4113:     if (founduname==0 && foundID==0) {
                   4114: 	alert('$error1');
                   4115: 	return;
1.27      albertel 4116:     }
                   4117:     if (foundsomething==0) {
1.246     albertel 4118: 	alert('$error2');
                   4119: 	return;
1.27      albertel 4120:     }
                   4121:     vf.submit();
                   4122:   }
                   4123:   function flip(vf,tf) {
                   4124:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4125:     var i;
                   4126:     //can not pick the same destination field twice
                   4127:     for (i=0;i<=vf.nfields.value;i++) {
                   4128:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4129:         eval('vf.f'+i+'.selectedIndex=0;')
                   4130:       }
                   4131:     }
                   4132:   }
                   4133: ENDPICK
                   4134: }
                   4135: 
1.26      albertel 4136: sub csvuploadmap_header {
1.324     albertel 4137:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4138:     my $javascript;
1.257     albertel 4139:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4140: 	$javascript=&csvupload_javascript_reverse_associate();
                   4141:     } else {
                   4142: 	$javascript=&csvupload_javascript_forward_associate();
                   4143:     }
1.45      ng       4144: 
1.418     albertel 4145:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4146:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4147:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4148:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4149:     my $reverse=&mt("Reverse Association");
1.41      ng       4150:     $request->print(<<ENDPICK);
1.632     www      4151: <br />
                   4152: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4153: <input type="hidden" name="associate"  value="" />
                   4154: <input type="hidden" name="phase"      value="three" />
                   4155: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4156: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4157: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4158: <input type="hidden" name="upfile_associate" 
1.257     albertel 4159:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4160: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4161: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4162: <hr />
                   4163: ENDPICK
1.597     wenzelju 4164:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4165:     return '';
1.26      albertel 4166: 
                   4167: }
                   4168: 
                   4169: sub csvupload_fields {
1.582     raeburn  4170:     my ($symb,$errorref) = @_;
                   4171:     my (@parts) = &getpartlist($symb,$errorref);
                   4172:     if (ref($errorref)) {
                   4173:         if ($$errorref) {
                   4174:             return;
                   4175:         }
                   4176:     }
                   4177: 
1.556     weissno  4178:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4179: 		['username','Student Username'],
                   4180: 		['domain','Student Domain']);
1.324     albertel 4181:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4182:     foreach my $part (sort(@parts)) {
                   4183: 	my @datum;
                   4184: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4185: 	my $name=$part;
                   4186: 	if  (!$display) { $display = $name; }
                   4187: 	@datum=($name,$display);
1.244     albertel 4188: 	if ($name=~/^stores_(.*)_awarded/) {
                   4189: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4190: 	}
1.41      ng       4191: 	push(@fields,\@datum);
                   4192:     }
                   4193:     return (@fields);
1.26      albertel 4194: }
                   4195: 
                   4196: sub csvuploadmap_footer {
1.41      ng       4197:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4198:     my $buttontext = &mt('Assign Grades');
1.41      ng       4199:     $request->print(<<ENDPICK);
1.26      albertel 4200: </table>
                   4201: <input type="hidden" name="nfields" value="$i" />
                   4202: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4203: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4204: </form>
                   4205: ENDPICK
                   4206: }
                   4207: 
1.283     albertel 4208: sub checkforfile_js {
1.638     www      4209:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4210:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4211:     function checkUpload(formname) {
                   4212: 	if (formname.upfile.value == "") {
1.539     riegler  4213: 	    alert("$alertmsg");
1.86      ng       4214: 	    return false;
                   4215: 	}
                   4216: 	formname.submit();
                   4217:     }
                   4218: CSVFORMJS
1.283     albertel 4219:     return $result;
                   4220: }
                   4221: 
                   4222: sub upcsvScores_form {
1.608     www      4223:     my ($request,$symb) = @_;
1.283     albertel 4224:     if (!$symb) {return '';}
                   4225:     my $result=&checkforfile_js();
1.632     www      4226:     $result.=&Apache::loncommon::start_data_table().
                   4227:              &Apache::loncommon::start_data_table_header_row().
                   4228:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4229:              &Apache::loncommon::end_data_table_header_row().
                   4230:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4231:     my $upload=&mt("Upload Scores");
1.86      ng       4232:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4233:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4234:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4235:     $result.=<<ENDUPFORM;
1.106     albertel 4236: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4237: <input type="hidden" name="symb" value="$symb" />
                   4238: <input type="hidden" name="command" value="csvuploadmap" />
                   4239: $upfile_select
1.589     bisitz   4240: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4241: </form>
                   4242: ENDUPFORM
1.370     www      4243:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4244:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4245:              '</td>'.
                   4246:             &Apache::loncommon::end_data_table_row().
                   4247:             &Apache::loncommon::end_data_table();
1.86      ng       4248:     return $result;
                   4249: }
                   4250: 
                   4251: 
1.26      albertel 4252: sub csvuploadmap {
1.608     www      4253:     my ($request,$symb)= @_;
1.41      ng       4254:     if (!$symb) {return '';}
1.72      ng       4255: 
1.41      ng       4256:     my $datatoken;
1.257     albertel 4257:     if (!$env{'form.datatoken'}) {
1.41      ng       4258: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4259:     } else {
1.257     albertel 4260: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4261: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4262:     }
1.41      ng       4263:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4264:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4265:     my ($i,$keyfields);
                   4266:     if (@records) {
1.582     raeburn  4267:         my $fieldserror;
                   4268: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4269:         if ($fieldserror) {
                   4270:             $request->print(&navmap_errormsg());
                   4271:             return;
                   4272:         }
1.257     albertel 4273: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4274: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4275: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4276: 							  \@fields);
                   4277: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4278: 	    chop($keyfields);
                   4279: 	} else {
                   4280: 	    unshift(@fields,['none','']);
                   4281: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4282: 							    \@fields);
1.311     banghart 4283:             foreach my $rec (@records) {
                   4284:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4285:                 if (%temp) {
                   4286:                     $keyfields=join(',',sort(keys(%temp)));
                   4287:                     last;
                   4288:                 }
                   4289:             }
1.41      ng       4290: 	}
                   4291:     }
                   4292:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4293: 
1.41      ng       4294:     return '';
1.27      albertel 4295: }
                   4296: 
1.246     albertel 4297: sub csvuploadoptions {
1.608     www      4298:     my ($request,$symb)= @_;
1.632     www      4299:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4300:     $request->print(<<ENDPICK);
                   4301: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4302: <input type="hidden" name="command"    value="csvuploadassign" />
                   4303: <p>
                   4304: <label>
                   4305:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4306:    $overwrite
1.246     albertel 4307: </label>
                   4308: </p>
                   4309: ENDPICK
                   4310:     my %fields=&get_fields();
                   4311:     if (!defined($fields{'domain'})) {
1.257     albertel 4312: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4313: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4314:     }
1.257     albertel 4315:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4316: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4317: 	my $cleankey=$1;
                   4318: 	if ($cleankey eq 'command') { next; }
                   4319: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4320: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4321:     }
                   4322:     # FIXME do a check for any duplicated user ids...
                   4323:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4324:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4325: <hr /></form>'."\n");
1.246     albertel 4326:     return '';
                   4327: }
                   4328: 
                   4329: sub get_fields {
                   4330:     my %fields;
1.257     albertel 4331:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4332:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4333: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4334: 	    if ($env{'form.f'.$i} ne 'none') {
                   4335: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4336: 	    }
                   4337: 	} else {
1.257     albertel 4338: 	    if ($env{'form.f'.$i} ne 'none') {
                   4339: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4340: 	    }
                   4341: 	}
1.27      albertel 4342:     }
1.246     albertel 4343:     return %fields;
                   4344: }
                   4345: 
                   4346: sub csvuploadassign {
1.608     www      4347:     my ($request,$symb)= @_;
1.246     albertel 4348:     if (!$symb) {return '';}
1.345     bowersj2 4349:     my $error_msg = '';
1.246     albertel 4350:     &Apache::loncommon::load_tmp_file($request);
                   4351:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4352:     my %fields=&get_fields();
1.257     albertel 4353:     my $courseid=$env{'request.course.id'};
1.97      albertel 4354:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4355:     my @notallowed;
1.41      ng       4356:     my @skipped;
1.657     raeburn  4357:     my @warnings;
1.41      ng       4358:     my $countdone=0;
                   4359:     foreach my $grade (@gradedata) {
                   4360: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4361: 	my $domain;
                   4362: 	if ($entries{$fields{'domain'}}) {
                   4363: 	    $domain=$entries{$fields{'domain'}};
                   4364: 	} else {
1.257     albertel 4365: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4366: 	}
1.243     albertel 4367: 	$domain=~s/\s//g;
1.41      ng       4368: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4369: 	$username=~s/\s//g;
1.243     albertel 4370: 	if (!$username) {
                   4371: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4372: 	    $id=~s/\s//g;
1.243     albertel 4373: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4374: 	    $username=$ids{$id};
                   4375: 	}
1.41      ng       4376: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4377: 	    my $id=$entries{$fields{'ID'}};
                   4378: 	    $id=~s/\s//g;
                   4379: 	    if ($id) {
                   4380: 		push(@skipped,"$id:$domain");
                   4381: 	    } else {
                   4382: 		push(@skipped,"$username:$domain");
                   4383: 	    }
1.41      ng       4384: 	    next;
                   4385: 	}
1.108     albertel 4386: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4387: 	if (!&canmodify($usec)) {
                   4388: 	    push(@notallowed,"$username:$domain");
                   4389: 	    next;
                   4390: 	}
1.244     albertel 4391: 	my %points;
1.41      ng       4392: 	my %grades;
                   4393: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4394: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4395: 		$dest eq 'domain') { next; }
                   4396: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4397: 	    if ($dest=~/stores_(.*)_points/) {
                   4398: 		my $part=$1;
                   4399: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4400: 					      $symb,$domain,$username);
1.345     bowersj2 4401:                 if ($wgt) {
                   4402:                     $entries{$fields{$dest}}=~s/\s//g;
                   4403:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4404:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4405:                                           : 'correct_by_override';
1.638     www      4406:                     if ($pcr>1) {
1.657     raeburn  4407:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4408:                     }
1.345     bowersj2 4409:                     $grades{"resource.$part.awarded"}=$pcr;
                   4410:                     $grades{"resource.$part.solved"}=$award;
                   4411:                     $points{$part}=1;
                   4412:                 } else {
                   4413:                     $error_msg = "<br />" .
                   4414:                         &mt("Some point values were assigned"
                   4415:                             ." for problems with a weight "
                   4416:                             ."of zero. These values were "
                   4417:                             ."ignored.");
                   4418:                 }
1.244     albertel 4419: 	    } else {
                   4420: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4421: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4422: 		my $store_key=$dest;
                   4423: 		$store_key=~s/^stores/resource/;
                   4424: 		$store_key=~s/_/\./g;
                   4425: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4426: 	    }
1.41      ng       4427: 	}
1.508     www      4428: 	if (! %grades) { 
                   4429:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4430:         } else {
                   4431: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4432: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4433: 					   $env{'request.course.id'},
                   4434: 					   $domain,$username);
1.508     www      4435: 	   if ($result eq 'ok') {
1.627     www      4436: # Successfully stored
1.508     www      4437: 	      $request->print('.');
1.627     www      4438: # Remove from grading queue
                   4439:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4440:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4441:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4442:                                              $domain,$username);
                   4443:               $countdone++;
                   4444:            } else {
1.508     www      4445: 	      $request->print("<p><span class=\"LC_error\">".
                   4446:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4447:                                   "$username:$domain",$result)."</span></p>");
                   4448: 	   }
                   4449: 	   $request->rflush();
                   4450:         }
1.41      ng       4451:     }
1.570     www      4452:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4453:     if (@warnings) {
                   4454:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4455:         $request->print(join(', ',@warnings));
                   4456:     }
1.41      ng       4457:     if (@skipped) {
1.571     www      4458: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4459:         $request->print(join(', ',@skipped));
1.106     albertel 4460:     }
                   4461:     if (@notallowed) {
1.571     www      4462: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4463: 	$request->print(join(', ',@notallowed));
1.41      ng       4464:     }
1.106     albertel 4465:     $request->print("<br />\n");
1.345     bowersj2 4466:     return $error_msg;
1.26      albertel 4467: }
1.44      ng       4468: #------------- end of section for handling csv file upload ---------
                   4469: #
                   4470: #-------------------------------------------------------------------
                   4471: #
1.122     ng       4472: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4473: #
                   4474: #--- Select a page/sequence and a student to grade
1.68      ng       4475: sub pickStudentPage {
1.608     www      4476:     my ($request,$symb) = @_;
1.68      ng       4477: 
1.539     riegler  4478:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4479:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4480: 
                   4481: function checkPickOne(formname) {
1.76      ng       4482:     if (radioSelection(formname.student) == null) {
1.539     riegler  4483: 	alert("$alertmsg");
1.68      ng       4484: 	return;
                   4485:     }
1.125     ng       4486:     ptr = pullDownSelection(formname.selectpage);
                   4487:     formname.page.value = formname["page"+ptr].value;
                   4488:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4489:     formname.submit();
                   4490: }
                   4491: 
                   4492: LISTJAVASCRIPT
1.118     ng       4493:     &commonJSfunctions($request);
1.608     www      4494: 
1.257     albertel 4495:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4496:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4497:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4498: 
1.398     albertel 4499:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4500: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4501: 
1.80      ng       4502:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4503:     my $map_error;
                   4504:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4505:     if ($map_error) {
                   4506:         $request->print(&navmap_errormsg());
                   4507:         return; 
                   4508:     }
1.137     albertel 4509:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4510: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4511: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4512: 
                   4513:     # Collection of hidden fields
1.70      ng       4514:     my $ctr=0;
1.68      ng       4515:     foreach (@$titles) {
1.700     bisitz   4516:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4517:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4518:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4519:         $ctr++;
1.68      ng       4520:     }
1.700     bisitz   4521:     $result.='<input type="hidden" name="page" />'."\n".
                   4522:         '<input type="hidden" name="title" />'."\n";
                   4523: 
                   4524:     $result.=&build_section_inputs();
                   4525:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4526:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4527: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4528: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4529: 
1.700     bisitz   4530:     # Show grading options
                   4531:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4532:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4533:     $ctr=0;
                   4534:     foreach (@$titles) {
                   4535: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4536: 	$select.='<option value="'.$ctr.'"'.
                   4537: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4538: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4539: 	$ctr++;
                   4540:     }
1.700     bisitz   4541:     $select.= '</select>';
1.68      ng       4542: 
1.700     bisitz   4543:     $result.=
                   4544:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4545:        .$select
                   4546:        .&Apache::lonhtmlcommon::row_closure();
                   4547: 
                   4548:     $result.=
                   4549:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4550:        .'<label><input type="radio" name="vProb" value="no"'
                   4551:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4552:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4553:            .&mt('yes').'</label>'."\n"
                   4554:        .&Apache::lonhtmlcommon::row_closure();
                   4555: 
                   4556:     $result.=
                   4557:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4558:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4559:            .&mt('none').' </label>'."\n"
                   4560:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4561:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4562:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4563:            .&mt('all submissions with details').' </label>'
                   4564:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4565:     
1.700     bisitz   4566:     $result.=
                   4567:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4568:        .'<input type="text" name="CODE" value="" />'
                   4569:        .&Apache::lonhtmlcommon::row_closure(1)
                   4570:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4571: 
1.700     bisitz   4572:     # Show list of students to select for grading
                   4573:     $result.='<br /><input type="button" '.
1.589     bisitz   4574:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4575: 
1.68      ng       4576:     $request->print($result);
                   4577: 
1.485     albertel 4578:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4579: 	&Apache::loncommon::start_data_table().
                   4580: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4581: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4582: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4583: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4584: 	'<th>'.&nameUserString('header').'</th>'.
                   4585: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4586:  
1.76      ng       4587:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4588:     my $ptr = 1;
1.294     albertel 4589:     foreach my $student (sort 
                   4590: 			 {
                   4591: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4592: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4593: 			     }
                   4594: 			     return $a cmp $b;
                   4595: 			 } (keys(%$fullname))) {
1.68      ng       4596: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4597: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4598:                                   : '</td>');
1.126     ng       4599: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4600: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4601: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4602: 	$studentTable.=
                   4603: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4604:                          : '');
1.68      ng       4605: 	$ptr++;
                   4606:     }
1.484     albertel 4607:     if ($ptr%2 == 0) {
                   4608: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4609: 	    &Apache::loncommon::end_data_table_row();
                   4610:     }
                   4611:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4612:     $studentTable.='<input type="button" '.
1.589     bisitz   4613:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4614: 
                   4615:     $request->print($studentTable);
                   4616: 
                   4617:     return '';
                   4618: }
                   4619: 
                   4620: sub getSymbMap {
1.582     raeburn  4621:     my ($map_error) = @_;
1.132     bowersj2 4622:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4623:     unless (ref($navmap)) {
                   4624:         if (ref($map_error)) {
                   4625:             $$map_error = 'navmap';
                   4626:         }
                   4627:         return;
                   4628:     }
1.68      ng       4629:     my %symbx = ();
                   4630:     my @titles = ();
1.117     bowersj2 4631:     my $minder = 0;
                   4632: 
                   4633:     # Gather every sequence that has problems.
1.240     albertel 4634:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4635: 					       1,0,1);
1.117     bowersj2 4636:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4637: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4638: 	    my $title = $minder.'.'.
                   4639: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4640: 	    push(@titles, $title); # minder in case two titles are identical
                   4641: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4642: 	    $minder++;
1.241     albertel 4643: 	}
1.68      ng       4644:     }
                   4645:     return \@titles,\%symbx;
                   4646: }
                   4647: 
1.72      ng       4648: #
                   4649: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4650: sub displayPage {
1.608     www      4651:     my ($request,$symb) = @_;
1.257     albertel 4652:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4653:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4654:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4655:     my $pageTitle = $env{'form.page'};
1.103     albertel 4656:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4657:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4658:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4659: 
                   4660:     #need to make sure we have the correct data for later EXT calls, 
                   4661:     #thus invalidate the cache
                   4662:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4663:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4664:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4665:     &Apache::lonnet::clear_EXT_cache_status();
                   4666: 
1.103     albertel 4667:     if (!&canview($usec)) {
1.712     bisitz   4668:         $request->print(
                   4669:             '<span class="LC_warning">'.
                   4670:             &mt('Unable to view requested student. ([_1])',
                   4671:                     $env{'form.student'}).
                   4672:             '</span>');
                   4673:         return;
1.103     albertel 4674:     }
1.398     albertel 4675:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4676:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4677: 	'</h3>'."\n";
1.500     albertel 4678:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4679:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4680: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4681:     } else {
                   4682: 	delete($env{'form.CODE'});
                   4683:     }
1.71      ng       4684:     &sub_page_js($request);
                   4685:     $request->print($result);
                   4686: 
1.132     bowersj2 4687:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4688:     unless (ref($navmap)) {
                   4689:         $request->print(&navmap_errormsg());
                   4690:         return;
                   4691:     }
1.257     albertel 4692:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4693:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4694:     if (!$map) {
1.485     albertel 4695: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4696: 	return; 
                   4697:     }
1.68      ng       4698:     my $iterator = $navmap->getIterator($map->map_start(),
                   4699: 					$map->map_finish());
                   4700: 
1.71      ng       4701:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4702: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4703: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4704: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4705: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4706: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4707: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4708: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4709: 
1.382     albertel 4710:     if (defined($env{'form.CODE'})) {
                   4711: 	$studentTable.=
                   4712: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4713:     }
1.381     albertel 4714:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4715: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4716: 
1.594     bisitz   4717:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4718:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4719:         '</span>'."\n".
1.484     albertel 4720: 	&Apache::loncommon::start_data_table().
                   4721: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4722: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4723: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4724: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4725: 
1.329     albertel 4726:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4727:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4728:     $iterator->next(); # skip the first BEGIN_MAP
                   4729:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4730:     while ($depth > 0) {
1.68      ng       4731:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4732:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4733: 
1.385     albertel 4734:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4735: 	    my $parts = $curRes->parts();
1.68      ng       4736:             my $title = $curRes->compTitle();
1.71      ng       4737: 	    my $symbx = $curRes->symb();
1.484     albertel 4738: 	    $studentTable.=
                   4739: 		&Apache::loncommon::start_data_table_row().
                   4740: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4741: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4742: 		                        : '<br />('.&mt('[_1]parts',
                   4743: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4744: 		 ).
                   4745: 		 '</td>';
1.71      ng       4746: 	    $studentTable.='<td valign="top">';
1.382     albertel 4747: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4748: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4749: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4750: 					     undef,'both',\%form);
1.71      ng       4751: 	    } else {
1.382     albertel 4752: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4753: 		$companswer =~ s|<form(.*?)>||g;
                   4754: 		$companswer =~ s|</form>||g;
1.71      ng       4755: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4756: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4757: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4758: #		}
1.116     ng       4759: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4760: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4761: 	    }
                   4762: 
1.257     albertel 4763: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4764: 
1.257     albertel 4765: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4766: 		if ($record{'version'} eq '') {
1.485     albertel 4767: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4768: 		} else {
1.116     ng       4769: 		    my %responseType = ();
                   4770: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4771: 			my @responseIds =$curRes->responseIds($partid);
                   4772: 			my @responseType =$curRes->responseType($partid);
                   4773: 			my %responseIds;
                   4774: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4775: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4776: 			}
                   4777: 			$responseType{$partid} = \%responseIds;
1.116     ng       4778: 		    }
1.148     albertel 4779: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4780: 
1.71      ng       4781: 		}
1.257     albertel 4782: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4783: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4784: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4785: 									$env{'request.course.id'},
1.71      ng       4786: 									'','.submission');
                   4787:  
                   4788: 	    }
1.103     albertel 4789: 	    if (&canmodify($usec)) {
1.585     bisitz   4790:             $studentTable.=&gradeBox_start();
1.103     albertel 4791: 		foreach my $partid (@{$parts}) {
                   4792: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4793: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4794: 		    $question++;
                   4795: 		}
1.585     bisitz   4796:             $studentTable.=&gradeBox_end();
1.196     albertel 4797: 		$prob++;
1.71      ng       4798: 	    }
                   4799: 	    $studentTable.='</td></tr>';
1.68      ng       4800: 
1.103     albertel 4801: 	}
1.68      ng       4802:         $curRes = $iterator->next();
                   4803:     }
                   4804: 
1.589     bisitz   4805:     $studentTable.=
                   4806:         '</table>'."\n".
                   4807:         '<input type="button" value="'.&mt('Save').'" '.
                   4808:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4809:         '</form>'."\n";
1.71      ng       4810:     $request->print($studentTable);
                   4811: 
                   4812:     return '';
1.119     ng       4813: }
                   4814: 
                   4815: sub displaySubByDates {
1.148     albertel 4816:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4817:     my $isCODE=0;
1.335     albertel 4818:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4819:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4820:     my $studentTable=&Apache::loncommon::start_data_table().
                   4821: 	&Apache::loncommon::start_data_table_header_row().
                   4822: 	'<th>'.&mt('Date/Time').'</th>'.
                   4823: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4824:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4825: 	'<th>'.&mt('Submission').'</th>'.
                   4826: 	'<th>'.&mt('Status').'</th>'.
                   4827: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4828:     my ($version);
                   4829:     my %mark;
1.148     albertel 4830:     my %orders;
1.119     ng       4831:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4832:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4833: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4834:     }
1.335     albertel 4835: 
                   4836:     my $interaction;
1.525     raeburn  4837:     my $no_increment = 1;
1.640     raeburn  4838:     my %lastrndseed;
1.119     ng       4839:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4840: 	my $timestamp = 
                   4841: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4842: 	if (exists($$record{$version.':resource.0.version'})) {
                   4843: 	    $interaction = $$record{$version.':resource.0.version'};
                   4844: 	}
1.671     raeburn  4845:         if ($isTask && $env{'form.previousversion'}) {
                   4846:             next unless ($interaction == $env{'form.previousversion'});
                   4847:         }
1.335     albertel 4848: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4849: 		             : "$version:resource");
1.467     albertel 4850: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4851: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4852: 	if ($isCODE) {
                   4853: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4854: 	}
1.671     raeburn  4855:         if ($isTask) {
                   4856:             $studentTable.='<td>'.$interaction.'</td>';
                   4857:         }
1.119     ng       4858: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4859: 	my @displaySub = ();
                   4860: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4861:             my ($hidden,$type);
                   4862:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4863:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4864:                 $hidden = 1;
                   4865:             }
1.335     albertel 4866: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4867: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4868: 	    
1.122     ng       4869: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4870: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4871: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4872: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4873: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4874:                     
1.335     albertel 4875: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4876: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4877:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4878:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4879:                                    .' <span class="LC_internal_info">'
1.625     www      4880:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4881:                                    .'</span>'
                   4882:                                    .' <b>';
1.596     raeburn  4883:                     if ($hidden) {
                   4884:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4885:                     } else {
1.640     raeburn  4886:                         my ($trial,$rndseed,$newvariation);
                   4887:                         if ($type eq 'randomizetry') {
                   4888:                             $trial = $$record{"$where.$partid.tries"};
                   4889:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4890:                         }
1.596     raeburn  4891: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4892: 			    $displaySub[0].=&mt('Trial not counted');
                   4893: 		        } else {
                   4894: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4895: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4896:                             if ($rndseed || $lastrndseed{$partid}) {
                   4897:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4898:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4899:                                 }
                   4900:                             }
                   4901:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4902: 		        }
                   4903: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4904:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4905: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4906: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4907: 			    $orders{$partid}->{$responseId}=
                   4908: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4909:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4910: 		        }
1.640     raeburn  4911: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4912: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4913: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4914:                     }
1.147     albertel 4915: 		}
                   4916: 	    }
1.335     albertel 4917: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4918: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4919: 				    $$record{"$where.$partid.checkedin"},
                   4920: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4921: 					'<br />';
1.335     albertel 4922: 	    }
                   4923: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4924: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4925: 		    lc($$record{"$where.$partid.award"}).' '.
                   4926: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4927: 		    '<br />';
                   4928: 	    }
1.335     albertel 4929: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4930: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4931: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4932: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4933: 		$displaySub[2].=
                   4934: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4935: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4936: 	    }
                   4937: 	}
                   4938: 	# needed because old essay regrader has not parts info
                   4939: 	if (exists $$record{"$version:resource.regrader"}) {
                   4940: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4941: 	}
                   4942: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4943: 	if ($displaySub[2]) {
1.467     albertel 4944: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4945: 	}
1.467     albertel 4946: 	$studentTable.='&nbsp;</td>'.
                   4947: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4948:     }
1.467     albertel 4949:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4950:     return $studentTable;
1.71      ng       4951: }
                   4952: 
                   4953: sub updateGradeByPage {
1.608     www      4954:     my ($request,$symb) = @_;
1.71      ng       4955: 
1.257     albertel 4956:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4957:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4958:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4959:     my $pageTitle = $env{'form.page'};
1.103     albertel 4960:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4961:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4962:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4963:     if (!&canmodify($usec)) {
1.526     raeburn  4964: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4965: 	return;
                   4966:     }
1.398     albertel 4967:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4968:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4969: 	'</h3>'."\n";
1.70      ng       4970: 
1.68      ng       4971:     $request->print($result);
                   4972: 
1.582     raeburn  4973: 
1.132     bowersj2 4974:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4975:     unless (ref($navmap)) {
                   4976:         $request->print(&navmap_errormsg());
                   4977:         return;
                   4978:     }
1.257     albertel 4979:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4980:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4981:     if (!$map) {
1.527     raeburn  4982: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4983: 	return; 
                   4984:     }
1.71      ng       4985:     my $iterator = $navmap->getIterator($map->map_start(),
                   4986: 					$map->map_finish());
1.70      ng       4987: 
1.484     albertel 4988:     my $studentTable=
                   4989: 	&Apache::loncommon::start_data_table().
                   4990: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4991: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4992: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4993: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4994: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4995: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4996: 
                   4997:     $iterator->next(); # skip the first BEGIN_MAP
                   4998:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4999:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 5000:     while ($depth > 0) {
1.71      ng       5001:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5002:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5003: 
1.385     albertel 5004:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5005: 	    my $parts = $curRes->parts();
1.71      ng       5006:             my $title = $curRes->compTitle();
                   5007: 	    my $symbx = $curRes->symb();
1.484     albertel 5008: 	    $studentTable.=
                   5009: 		&Apache::loncommon::start_data_table_row().
                   5010: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5011: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5012:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5013: 		.')').'</td>';
1.71      ng       5014: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5015: 
                   5016: 	    my %newrecord=();
                   5017: 	    my @displayPts=();
1.269     raeburn  5018:             my %aggregate = ();
                   5019:             my $aggregateflag = 0;
1.71      ng       5020: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5021: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5022: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5023: 
1.257     albertel 5024: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5025: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5026: 		my $partial = $newpts/$wgt;
                   5027: 		my $score;
                   5028: 		if ($partial > 0) {
                   5029: 		    $score = 'correct_by_override';
1.125     ng       5030: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5031: 		    $score = 'incorrect_by_override';
                   5032: 		}
1.257     albertel 5033: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5034: 		if ($dropMenu eq 'excused') {
1.71      ng       5035: 		    $partial = '';
                   5036: 		    $score = 'excused';
1.125     ng       5037: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5038: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5039: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5040: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5041: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5042: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5043: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5044: 		    $changeflag++;
                   5045: 		    $newpts = '';
1.269     raeburn  5046:                     
                   5047:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5048:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5049:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5050:                     if ($aggtries > 0) {
                   5051:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5052:                         $aggregateflag = 1;
                   5053:                     }
1.71      ng       5054: 		}
1.324     albertel 5055: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5056: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5057: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5058: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5059: 		    '&nbsp;<br />';
1.526     raeburn  5060: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5061: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5062: 		    '&nbsp;<br />';
1.71      ng       5063: 		$question++;
1.380     albertel 5064: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5065: 
1.71      ng       5066: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5067: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5068: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5069: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5070: 
                   5071: 		$changeflag++;
                   5072: 	    }
                   5073: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5074: 		my %record = 
                   5075: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5076: 					     $udom,$uname);
                   5077: 
                   5078: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5079: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5080: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5081: 		    $newrecord{'resource.CODE'} = '';
                   5082: 		}
1.257     albertel 5083: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5084: 					$udom,$uname);
1.382     albertel 5085: 		%record = &Apache::lonnet::restore($symbx,
                   5086: 						   $env{'request.course.id'},
                   5087: 						   $udom,$uname);
1.380     albertel 5088: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5089: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5090: 	    }
1.380     albertel 5091: 	    
1.269     raeburn  5092:             if ($aggregateflag) {
                   5093:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5094:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5095:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5096:             }
1.125     ng       5097: 
1.71      ng       5098: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5099: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5100: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5101: 
1.196     albertel 5102: 	    $prob++;
1.68      ng       5103: 	}
1.71      ng       5104:         $curRes = $iterator->next();
1.68      ng       5105:     }
1.98      albertel 5106: 
1.484     albertel 5107:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5108:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5109: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5110: 		  $changeflag));
1.76      ng       5111:     $request->print($grademsg.$studentTable);
1.68      ng       5112: 
1.70      ng       5113:     return '';
                   5114: }
                   5115: 
1.72      ng       5116: #-------- end of section for handling grading by page/sequence ---------
                   5117: #
                   5118: #-------------------------------------------------------------------
                   5119: 
1.581     www      5120: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5121: #
                   5122: #------ start of section for handling grading by page/sequence ---------
                   5123: 
1.423     albertel 5124: =pod
                   5125: 
                   5126: =head1 Bubble sheet grading routines
                   5127: 
1.424     albertel 5128:   For this documentation:
                   5129: 
                   5130:    'scanline' refers to the full line of characters
                   5131:    from the file that we are parsing that represents one entire sheet
                   5132: 
                   5133:    'bubble line' refers to the data
1.659     raeburn  5134:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5135: 
                   5136: 
1.659     raeburn  5137: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5138: into a course. When a user wants to grade, they select a
1.659     raeburn  5139: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5140: one of the predefined configurations for what each scanline looks
                   5141: like.
                   5142: 
                   5143: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5144: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5145: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5146: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5147: invalid student/employee ID
1.424     albertel 5148: 
                   5149: If the CODE option is used that determines the randomization of the
1.556     weissno  5150: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5151: username:domain.
                   5152: 
                   5153: During the validation phase the instructor can choose to skip scanlines. 
                   5154: 
1.659     raeburn  5155: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5156: 
                   5157:   scantron_original_filename (unmodified original file)
                   5158:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5159:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5160: 
                   5161: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5162: correction information that isn't representable in the bubblesheet
1.424     albertel 5163: file (see &scantron_getfile() for more information)
                   5164: 
                   5165: After all scanlines are either valid, marked as valid or skipped, then
                   5166: foreach line foreach problem in the picked sequence, an ssi request is
                   5167: made that simulates a user submitting their selected letter(s) against
                   5168: the homework problem.
1.423     albertel 5169: 
                   5170: =over 4
                   5171: 
                   5172: 
                   5173: 
                   5174: =item defaultFormData
                   5175: 
                   5176:   Returns html hidden inputs used to hold context/default values.
                   5177: 
                   5178:  Arguments:
                   5179:   $symb - $symb of the current resource 
                   5180: 
                   5181: =cut
1.422     foxr     5182: 
1.81      albertel 5183: sub defaultFormData {
1.324     albertel 5184:     my ($symb)=@_;
1.613     www      5185:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5186: }
                   5187: 
1.447     foxr     5188: 
1.423     albertel 5189: =pod 
                   5190: 
                   5191: =item getSequenceDropDown
                   5192: 
                   5193:    Return html dropdown of possible sequences to grade
                   5194:  
                   5195:  Arguments:
1.582     raeburn  5196:    $symb - $symb of the current resource
                   5197:    $map_error - ref to scalar which will container error if
                   5198:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5199: 
                   5200: =cut
1.422     foxr     5201: 
1.75      albertel 5202: sub getSequenceDropDown {
1.582     raeburn  5203:     my ($symb,$map_error)=@_;
1.75      albertel 5204:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5205:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5206:     if (ref($map_error)) {
                   5207:         return if ($$map_error);
                   5208:     }
1.137     albertel 5209:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5210:     my $ctr=0;
                   5211:     foreach (@$titles) {
                   5212: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5213: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5214: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5215: 	    '>'.$showtitle.'</option>'."\n";
                   5216: 	$ctr++;
                   5217:     }
                   5218:     $result.= '</select>';
                   5219:     return $result;
                   5220: }
                   5221: 
1.495     albertel 5222: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5223:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5224: 
                   5225: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5226: 
1.509     raeburn  5227: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5228:                                    # matchresponse or rankresponse, where 
                   5229:                                    # an individual response can have multiple 
                   5230:                                    # lines
1.503     raeburn  5231: 
                   5232: my %responsetype_per_response;     # responsetype for each response
                   5233: 
1.691     raeburn  5234: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5235:                                    # numbered response. Needed when randomorder
                   5236:                                    # or randompick are in use. Key is ID, value 
                   5237:                                    # is response number.
                   5238: 
1.495     albertel 5239: # Save and restore the bubble lines array to the form env.
                   5240: 
                   5241: 
                   5242: sub save_bubble_lines {
                   5243:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5244: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5245: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5246: 	    $first_bubble_line{$line};
1.503     raeburn  5247:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5248:             $subdivided_bubble_lines{$line};
                   5249:         $env{"form.scantron.responsetype.$line"} =
                   5250:             $responsetype_per_response{$line};
1.495     albertel 5251:     }
1.691     raeburn  5252:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5253:         my $line = $masterseq_id_responsenum{$resid};
                   5254:         $env{"form.scantron.residpart.$line"} = $resid;
                   5255:     }
1.495     albertel 5256: }
                   5257: 
                   5258: 
                   5259: sub restore_bubble_lines {
                   5260:     my $line = 0;
                   5261:     %bubble_lines_per_response = ();
1.691     raeburn  5262:     %masterseq_id_responsenum = ();
1.495     albertel 5263:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5264: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5265: 	$bubble_lines_per_response{$line} = $value;
                   5266: 	$first_bubble_line{$line}  =
                   5267: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5268:         $subdivided_bubble_lines{$line} =
                   5269:             $env{"form.scantron.sub_bubblelines.$line"};
                   5270:         $responsetype_per_response{$line} =
                   5271:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5272:         my $id = $env{"form.scantron.residpart.$line"};
                   5273:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5274: 	$line++;
                   5275:     }
                   5276: }
                   5277: 
1.423     albertel 5278: =pod 
                   5279: 
                   5280: =item scantron_filenames
                   5281: 
                   5282:    Returns a list of the scantron files in the current course 
                   5283: 
                   5284: =cut
1.422     foxr     5285: 
1.202     albertel 5286: sub scantron_filenames {
1.257     albertel 5287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5288:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5289:     my $getpropath = 1;
1.662     raeburn  5290:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5291:                                                         $cname,$getpropath);
1.202     albertel 5292:     my @possiblenames;
1.662     raeburn  5293:     if (ref($dirlist) eq 'ARRAY') {
                   5294:         foreach my $filename (sort(@{$dirlist})) {
                   5295: 	    ($filename)=split(/&/,$filename);
                   5296: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5297: 	    $filename=~s/^scantron_orig_//;
                   5298: 	    push(@possiblenames,$filename);
                   5299:         }
1.202     albertel 5300:     }
                   5301:     return @possiblenames;
                   5302: }
                   5303: 
1.423     albertel 5304: =pod 
                   5305: 
                   5306: =item scantron_uploads
                   5307: 
                   5308:    Returns  html drop-down list of scantron files in current course.
                   5309: 
                   5310:  Arguments:
                   5311:    $file2grade - filename to set as selected in the dropdown
                   5312: 
                   5313: =cut
1.422     foxr     5314: 
1.202     albertel 5315: sub scantron_uploads {
1.209     ng       5316:     my ($file2grade) = @_;
1.202     albertel 5317:     my $result=	'<select name="scantron_selectfile">';
                   5318:     $result.="<option></option>";
                   5319:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5320: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5321:     }
                   5322:     $result.="</select>";
                   5323:     return $result;
                   5324: }
                   5325: 
1.423     albertel 5326: =pod 
                   5327: 
                   5328: =item scantron_scantab
                   5329: 
                   5330:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5331:   file.
                   5332: 
                   5333: =cut
1.422     foxr     5334: 
1.82      albertel 5335: sub scantron_scantab {
                   5336:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5337:     $result.='<option></option>'."\n";
1.518     raeburn  5338:     my @lines = &get_scantronformat_file();
                   5339:     if (@lines > 0) {
                   5340:         foreach my $line (@lines) {
                   5341:             next if (($line =~ /^\#/) || ($line eq ''));
                   5342: 	    my ($name,$descrip)=split(/:/,$line);
                   5343: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5344:         }
1.82      albertel 5345:     }
                   5346:     $result.='</select>'."\n";
1.518     raeburn  5347:     return $result;
                   5348: }
                   5349: 
                   5350: =pod
                   5351: 
                   5352: =item get_scantronformat_file
                   5353: 
                   5354:   Returns an array containing lines from the scantron format file for
                   5355:   the domain of the course.
                   5356: 
                   5357:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5358:   lines are from this file.
                   5359: 
                   5360:   Otherwise, if a default.tab has been published in RES space by the 
                   5361:   domainconfig user, lines are from this file.
                   5362: 
                   5363:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5364:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5365: 
1.518     raeburn  5366: =cut
                   5367: 
                   5368: sub get_scantronformat_file {
                   5369:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5370:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5371:     my $gottab = 0;
                   5372:     my @lines;
                   5373:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5374:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5375:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5376:             if ($formatfile ne '-1') {
                   5377:                 @lines = split("\n",$formatfile,-1);
                   5378:                 $gottab = 1;
                   5379:             }
                   5380:         }
                   5381:     }
                   5382:     if (!$gottab) {
                   5383:         my $confname = $cdom.'-domainconfig';
                   5384:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5385:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5386:         if ($formatfile ne '-1') {
                   5387:             @lines = split("\n",$formatfile,-1);
                   5388:             $gottab = 1;
                   5389:         }
                   5390:     }
                   5391:     if (!$gottab) {
1.519     raeburn  5392:         my @domains = &Apache::lonnet::current_machine_domains();
                   5393:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5394:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5395:             @lines = <$fh>;
                   5396:             close($fh);
                   5397:         } else {
                   5398:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5399:             @lines = <$fh>;
                   5400:             close($fh);
                   5401:         }
1.518     raeburn  5402:     }
                   5403:     return @lines;
1.82      albertel 5404: }
                   5405: 
1.423     albertel 5406: =pod 
                   5407: 
                   5408: =item scantron_CODElist
                   5409: 
                   5410:   Returns html drop down of the saved CODE lists from current course,
                   5411:   generated from earlier printings.
                   5412: 
                   5413: =cut
1.422     foxr     5414: 
1.186     albertel 5415: sub scantron_CODElist {
1.257     albertel 5416:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5417:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5418:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5419:     my $namechoice='<option></option>';
1.225     albertel 5420:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5421: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5422: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5423: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5424:     }
                   5425:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5426:     return $namechoice;
                   5427: }
                   5428: 
1.423     albertel 5429: =pod 
                   5430: 
                   5431: =item scantron_CODEunique
                   5432: 
                   5433:   Returns the html for "Each CODE to be used once" radio.
                   5434: 
                   5435: =cut
1.422     foxr     5436: 
1.186     albertel 5437: sub scantron_CODEunique {
1.532     bisitz   5438:     my $result='<span class="LC_nobreak">
1.272     albertel 5439:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5440:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5441:                 </span>
1.532     bisitz   5442:                 <span class="LC_nobreak">
1.272     albertel 5443:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5444:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5445:                 </span>';
1.186     albertel 5446:     return $result;
                   5447: }
1.423     albertel 5448: 
                   5449: =pod 
                   5450: 
                   5451: =item scantron_selectphase
                   5452: 
1.659     raeburn  5453:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5454:   Allows for - starting a grading run.
1.424     albertel 5455:              - downloading existing scan data (original, corrected
1.423     albertel 5456:                                                 or skipped info)
                   5457: 
                   5458:              - uploading new scan data
                   5459: 
                   5460:  Arguments:
                   5461:   $r          - The Apache request object
                   5462:   $file2grade - name of the file that contain the scanned data to score
                   5463: 
                   5464: =cut
1.186     albertel 5465: 
1.75      albertel 5466: sub scantron_selectphase {
1.608     www      5467:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5468:     if (!$symb) {return '';}
1.582     raeburn  5469:     my $map_error;
                   5470:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5471:     if ($map_error) {
                   5472:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5473:         return;
                   5474:     }
1.324     albertel 5475:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5476:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5477:     my $format_selector=&scantron_scantab();
1.186     albertel 5478:     my $CODE_selector=&scantron_CODElist();
                   5479:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5480:     my $result;
1.422     foxr     5481: 
1.513     foxr     5482:     $ssi_error = 0;
                   5483: 
1.606     wenzelju 5484:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5485:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5486: 
                   5487: 	# Chunk of form to prompt for a scantron file upload.
                   5488: 
                   5489:         $r->print('
                   5490:     <br />
                   5491:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5492:        '.&Apache::loncommon::start_data_table_header_row().'
                   5493:             <th>
                   5494:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5495:             </th>
                   5496:        '.&Apache::loncommon::end_data_table_header_row().'
                   5497:        '.&Apache::loncommon::start_data_table_row().'
                   5498:             <td>
                   5499: ');
1.608     www      5500:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5501:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5502:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5503:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5504:     function checkUpload(formname) {
                   5505: 	if (formname.upfile.value == "") {
                   5506: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5507: 	    return false;
                   5508: 	}
                   5509: 	formname.submit();
                   5510:     }'));
                   5511:     $r->print('
                   5512:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5513:                 '.$default_form_data.'
                   5514:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5515:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5516:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5517:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5518:                 <br />
                   5519:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5520:               </form>
                   5521: ');
                   5522: 
                   5523:         $r->print('
                   5524:             </td>
                   5525:        '.&Apache::loncommon::end_data_table_row().'
                   5526:        '.&Apache::loncommon::end_data_table().'
                   5527: ');
                   5528:     }
                   5529: 
1.422     foxr     5530:     # Chunk of form to prompt for a file to grade and how:
                   5531: 
1.489     albertel 5532:     $result.= '
                   5533:     <br />
                   5534:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5535:     <input type="hidden" name="command" value="scantron_warning" />
                   5536:     '.$default_form_data.'
                   5537:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5538:        '.&Apache::loncommon::start_data_table_header_row().'
                   5539:             <th colspan="2">
1.492     albertel 5540:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5541:             </th>
                   5542:        '.&Apache::loncommon::end_data_table_header_row().'
                   5543:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5544:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5545:        '.&Apache::loncommon::end_data_table_row().'
                   5546:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5547:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5548:        '.&Apache::loncommon::end_data_table_row().'
                   5549:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5550:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5551:        '.&Apache::loncommon::end_data_table_row().'
                   5552:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5553:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5554:        '.&Apache::loncommon::end_data_table_row().'
                   5555:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5556:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5557:        '.&Apache::loncommon::end_data_table_row().'
                   5558:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5559: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5560:             <td>
1.492     albertel 5561: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5562:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5563:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5564: 	    </td>
1.489     albertel 5565:        '.&Apache::loncommon::end_data_table_row().'
                   5566:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5567:             <td colspan="2">
1.572     www      5568:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5569:             </td>
1.489     albertel 5570:        '.&Apache::loncommon::end_data_table_row().'
                   5571:     '.&Apache::loncommon::end_data_table().'
                   5572:     </form>
                   5573: ';
1.162     albertel 5574:    
                   5575:     $r->print($result);
                   5576: 
1.422     foxr     5577: 
                   5578: 
                   5579:     # Chunk of the form that prompts to view a scoring office file,
                   5580:     # corrected file, skipped records in a file.
                   5581: 
1.489     albertel 5582:     $r->print('
                   5583:    <br />
                   5584:    <form action="/adm/grades" name="scantron_download">
                   5585:      '.$default_form_data.'
                   5586:      <input type="hidden" name="command" value="scantron_download" />
                   5587:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5588:        '.&Apache::loncommon::start_data_table_header_row().'
                   5589:               <th>
1.492     albertel 5590:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5591:               </th>
                   5592:        '.&Apache::loncommon::end_data_table_header_row().'
                   5593:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5594:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5595:                 <br />
1.492     albertel 5596:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5597:        '.&Apache::loncommon::end_data_table_row().'
                   5598:      '.&Apache::loncommon::end_data_table().'
                   5599:    </form>
                   5600:    <br />
                   5601: ');
1.162     albertel 5602: 
1.457     banghart 5603:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5604: 
1.694     bisitz   5605:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5606:              $default_form_data."\n".
                   5607:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5608:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5609:              '<th colspan="2">
1.572     www      5610:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5611:              '</th>'."\n".
                   5612:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5613:               &Apache::loncommon::start_data_table_row()."\n".
                   5614:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5615:               '<td> '.$sequence_selector.' </td>'.
                   5616:               &Apache::loncommon::end_data_table_row()."\n".
                   5617:               &Apache::loncommon::start_data_table_row()."\n".
                   5618:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5619:               '<td> '.$file_selector.' </td>'."\n".
                   5620:               &Apache::loncommon::end_data_table_row()."\n".
                   5621:               &Apache::loncommon::start_data_table_row()."\n".
                   5622:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5623:               '<td> '.$format_selector.' </td>'."\n".
                   5624:               &Apache::loncommon::end_data_table_row()."\n".
                   5625:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5626:               '<td> '.&mt('Options').' </td>'."\n".
                   5627:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5628:               &Apache::loncommon::end_data_table_row()."\n".
                   5629:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5630:               '<td colspan="2">'."\n".
                   5631:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5632:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5633:               '</td>'."\n".
                   5634:               &Apache::loncommon::end_data_table_row()."\n".
                   5635:               &Apache::loncommon::end_data_table()."\n".
                   5636:               '</form><br />');
                   5637:     return;
1.75      albertel 5638: }
                   5639: 
1.423     albertel 5640: =pod
                   5641: 
                   5642: =item get_scantron_config
                   5643: 
1.711     bisitz   5644:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5645:    hash of configuration file fields.
                   5646: 
                   5647:  Arguments:
                   5648:     which - the name of the configuration to parse from the file.
                   5649: 
                   5650: 
                   5651:  Returns:
                   5652:             If the named configuration is not in the file, an empty
                   5653:             hash is returned.
                   5654:     a hash with the fields
                   5655:       name         - internal name for the this configuration setup
                   5656:       description  - text to display to operator that describes this config
                   5657:       CODElocation - if 0 or the string 'none'
                   5658:                           - no CODE exists for this config
                   5659:                      if -1 || the string 'letter'
                   5660:                           - a CODE exists for this config and is
                   5661:                             a string of letters
                   5662:                      Unsupported value (but planned for future support)
                   5663:                           if a positive integer
                   5664:                                - The CODE exists as the first n items from
                   5665:                                  the question section of the form
                   5666:                           if the string 'number'
                   5667:                                - The CODE exists for this config and is
                   5668:                                  a string of numbers
                   5669:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5670:                      the CODE starts
                   5671:       CODElength  - length of the CODE
1.573     bisitz   5672:       IDstart     - column where the student/employee ID starts
1.556     weissno  5673:       IDlength    - length of the student/employee ID info
1.423     albertel 5674:       Qstart      - column where the information from the bubbled
                   5675:                     'questions' start
                   5676:       Qlength     - number of columns comprising a single bubble line from
                   5677:                     the sheet. (usually either 1 or 10)
1.424     albertel 5678:       Qon         - either a single character representing the character used
1.423     albertel 5679:                     to signal a bubble was chosen in the positional setup, or
                   5680:                     the string 'letter' if the letter of the chosen bubble is
                   5681:                     in the final, or 'number' if a number representing the
                   5682:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5683:       Qoff        - the character used to represent that a bubble was
                   5684:                     left blank
1.423     albertel 5685:       PaperID     - if the scanning process generates a unique number for each
                   5686:                     sheet scanned the column that this ID number starts in
                   5687:       PaperIDlength - number of columns that comprise the unique ID number
                   5688:                       for the sheet of paper
1.424     albertel 5689:       FirstName   - column that the first name starts in
1.423     albertel 5690:       FirstNameLength - number of columns that the first name spans
                   5691:  
                   5692:       LastName    - column that the last name starts in
                   5693:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5694:       BubblesPerRow - number of bubbles available in each row used to 
                   5695:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5696: 
1.423     albertel 5697: =cut
1.422     foxr     5698: 
1.82      albertel 5699: sub get_scantron_config {
                   5700:     my ($which) = @_;
1.518     raeburn  5701:     my @lines = &get_scantronformat_file();
1.82      albertel 5702:     my %config;
1.157     albertel 5703:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5704:     foreach my $line (@lines) {
1.82      albertel 5705: 	my ($name,$descrip)=split(/:/,$line);
                   5706: 	if ($name ne $which ) { next; }
                   5707: 	chomp($line);
                   5708: 	my @config=split(/:/,$line);
                   5709: 	$config{'name'}=$config[0];
                   5710: 	$config{'description'}=$config[1];
                   5711: 	$config{'CODElocation'}=$config[2];
                   5712: 	$config{'CODEstart'}=$config[3];
                   5713: 	$config{'CODElength'}=$config[4];
                   5714: 	$config{'IDstart'}=$config[5];
                   5715: 	$config{'IDlength'}=$config[6];
                   5716: 	$config{'Qstart'}=$config[7];
1.497     foxr     5717:  	$config{'Qlength'}=$config[8];
1.82      albertel 5718: 	$config{'Qoff'}=$config[9];
                   5719: 	$config{'Qon'}=$config[10];
1.157     albertel 5720: 	$config{'PaperID'}=$config[11];
                   5721: 	$config{'PaperIDlength'}=$config[12];
                   5722: 	$config{'FirstName'}=$config[13];
                   5723: 	$config{'FirstNamelength'}=$config[14];
                   5724: 	$config{'LastName'}=$config[15];
                   5725: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5726:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5727: 	last;
                   5728:     }
                   5729:     return %config;
                   5730: }
                   5731: 
1.423     albertel 5732: =pod 
                   5733: 
                   5734: =item username_to_idmap
                   5735: 
1.556     weissno  5736:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5737:     student username:domain.
                   5738: 
                   5739:   Arguments:
                   5740: 
                   5741:     $classlist - reference to the class list hash. This is a hash
                   5742:                  keyed by student name:domain  whose elements are references
1.424     albertel 5743:                  to arrays containing various chunks of information
1.423     albertel 5744:                  about the student. (See loncoursedata for more info).
                   5745: 
                   5746:   Returns
                   5747:     %idmap - the constructed hash
                   5748: 
                   5749: =cut
                   5750: 
1.82      albertel 5751: sub username_to_idmap {
                   5752:     my ($classlist)= @_;
                   5753:     my %idmap;
                   5754:     foreach my $student (keys(%$classlist)) {
                   5755: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5756: 	    $student;
                   5757:     }
                   5758:     return %idmap;
                   5759: }
1.423     albertel 5760: 
                   5761: =pod
                   5762: 
1.424     albertel 5763: =item scantron_fixup_scanline
1.423     albertel 5764: 
                   5765:    Process a requested correction to a scanline.
                   5766: 
                   5767:   Arguments:
                   5768:     $scantron_config   - hash from &get_scantron_config()
                   5769:     $scan_data         - hash of correction information 
                   5770:                           (see &scantron_getfile())
                   5771:     $line              - existing scanline
                   5772:     $whichline         - line number of the passed in scanline
                   5773:     $field             - type of change to process 
                   5774:                          (either 
1.573     bisitz   5775:                           'ID'     -> correct the student/employee ID
1.423     albertel 5776:                           'CODE'   -> correct the CODE
                   5777:                           'answer' -> fixup the submitted answers)
                   5778:     
                   5779:    $args               - hash of additional info,
                   5780:                           - 'ID' 
                   5781:                                'newid' -> studentID to use in replacement
1.424     albertel 5782:                                           of existing one
1.423     albertel 5783:                           - 'CODE' 
                   5784:                                'CODE_ignore_dup' - set to true if duplicates
                   5785:                                                    should be ignored.
                   5786: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5787:                                         if the existing unfound code should
1.423     albertel 5788:                                         be used as is
                   5789:                           - 'answer'
                   5790:                                'response' - new answer or 'none' if blank
                   5791:                                'question' - the bubble line to change
1.503     raeburn  5792:                                'questionnum' - the question identifier,
                   5793:                                                may include subquestion. 
1.423     albertel 5794: 
                   5795:   Returns:
                   5796:     $line - the modified scanline
                   5797: 
                   5798:   Side effects: 
                   5799:     $scan_data - may be updated
                   5800: 
                   5801: =cut
                   5802: 
1.82      albertel 5803: 
1.157     albertel 5804: sub scantron_fixup_scanline {
                   5805:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5806:     if ($field eq 'ID') {
                   5807: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5808: 	    return ($line,1,'New value too large');
1.157     albertel 5809: 	}
                   5810: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5811: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5812: 				     $args->{'newid'});
                   5813: 	}
                   5814: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5815: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5816: 	if ($args->{'newid'}=~/^\s*$/) {
                   5817: 	    &scan_data($scan_data,"$whichline.user",
                   5818: 		       $args->{'username'}.':'.$args->{'domain'});
                   5819: 	}
1.186     albertel 5820:     } elsif ($field eq 'CODE') {
1.192     albertel 5821: 	if ($args->{'CODE_ignore_dup'}) {
                   5822: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5823: 	}
                   5824: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5825: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5826: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5827: 		return ($line,1,'New CODE value too large');
                   5828: 	    }
                   5829: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5830: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5831: 	    }
                   5832: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5833: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5834: 	}
1.157     albertel 5835:     } elsif ($field eq 'answer') {
1.497     foxr     5836: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5837: 	my $off=$scantron_config->{'Qoff'};
                   5838: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5839: 	my $answer=${off}x$length;
                   5840: 	if ($args->{'response'} eq 'none') {
                   5841: 	    &scan_data($scan_data,
1.503     raeburn  5842: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5843: 	} else {
                   5844: 	    if ($on eq 'letter') {
                   5845: 		my @alphabet=('A'..'Z');
                   5846: 		$answer=$alphabet[$args->{'response'}];
                   5847: 	    } elsif ($on eq 'number') {
                   5848: 		$answer=$args->{'response'}+1;
                   5849: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5850: 	    } else {
1.497     foxr     5851: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5852: 	    }
1.497     foxr     5853: 	    &scan_data($scan_data,
1.503     raeburn  5854: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5855: 	}
1.497     foxr     5856: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5857: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5858:     }
                   5859:     return $line;
                   5860: }
1.423     albertel 5861: 
                   5862: =pod
                   5863: 
                   5864: =item scan_data
                   5865: 
                   5866:     Edit or look up  an item in the scan_data hash.
                   5867: 
                   5868:   Arguments:
                   5869:     $scan_data  - The hash (see scantron_getfile)
                   5870:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5871:                   scantronfilename_key).
1.423     albertel 5872:     $data        - New value of the hash entry.
                   5873:     $delete      - If true, the entry is removed from the hash.
                   5874: 
                   5875:   Returns:
                   5876:     The new value of the hash table field (undefined if deleted).
                   5877: 
                   5878: =cut
                   5879: 
                   5880: 
1.157     albertel 5881: sub scan_data {
                   5882:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5883:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5884:     if (defined($value)) {
                   5885: 	$scan_data->{$filename.'_'.$key} = $value;
                   5886:     }
                   5887:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5888:     return $scan_data->{$filename.'_'.$key};
                   5889: }
1.423     albertel 5890: 
1.495     albertel 5891: # ----- These first few routines are general use routines.----
                   5892: 
                   5893: # Return the number of occurences of a pattern in a string.
                   5894: 
                   5895: sub occurence_count {
                   5896:     my ($string, $pattern) = @_;
                   5897: 
                   5898:     my @matches = ($string =~ /$pattern/g);
                   5899: 
                   5900:     return scalar(@matches);
                   5901: }
                   5902: 
                   5903: 
                   5904: # Take a string known to have digits and convert all the
                   5905: # digits into letters in the range J,A..I.
                   5906: 
                   5907: sub digits_to_letters {
                   5908:     my ($input) = @_;
                   5909: 
                   5910:     my @alphabet = ('J', 'A'..'I');
                   5911: 
                   5912:     my @input    = split(//, $input);
                   5913:     my $output ='';
                   5914:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5915: 	if ($input[$i] =~ /\d/) {
                   5916: 	    $output .= $alphabet[$input[$i]];
                   5917: 	} else {
                   5918: 	    $output .= $input[$i];
                   5919: 	}
                   5920:     }
                   5921:     return $output;
                   5922: }
                   5923: 
1.423     albertel 5924: =pod 
                   5925: 
                   5926: =item scantron_parse_scanline
                   5927: 
1.711     bisitz   5928:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5929: 
                   5930:  Arguments:
1.711     bisitz   5931:     line             - The text of the bubblesheet file line to process
1.423     albertel 5932:     whichline        - Line number
1.711     bisitz   5933:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5934:     scan_data        - Hash of extra information about the scanline
                   5935:                        (see scantron_getfile for more information)
                   5936:     just_header      - True if should not process question answers but only
                   5937:                        the stuff to the left of the answers.
1.691     raeburn  5938:     randomorder      - True if randomorder in use
                   5939:     randompick       - True if randompick in use
                   5940:     sequence         - Exam folder URL
                   5941:     master_seq       - Ref to array containing symbs in exam folder
                   5942:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5943:                        (corresponding values are resource objects)
                   5944:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5945:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5946:                        are refs to an array of resource objects, ordered
                   5947:                        according to order used for CODE, when randomorder
                   5948:                        and or randompick are in use.
                   5949:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5950:                        for current line to question number used for same question
                   5951:                         in "Master Sequence" (as seen by Course Coordinator).
                   5952:     startline        - Ref to hash where key is question number (0 is first)
                   5953:                        and value is number of first bubble line for current 
                   5954:                        student or code-based randompick and/or randomorder.
                   5955:     totalref         - Ref of scalar used to score total number of bubble
                   5956:                        lines needed for responses in a scan line (used when
                   5957:                        randompick in use. 
                   5958:     
1.423     albertel 5959:  Returns:
                   5960:    Hash containing the result of parsing the scanline
                   5961: 
                   5962:    Keys are all proceeded by the string 'scantron.'
                   5963: 
                   5964:        CODE    - the CODE in use for this scanline
                   5965:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5966:                  by the operator
                   5967:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5968:                             CODEs were selected, but the usage has been
                   5969:                             forced by the operator
1.556     weissno  5970:        ID  - student/employee ID
1.423     albertel 5971:        PaperID - if used, the ID number printed on the sheet when the 
                   5972:                  paper was scanned
                   5973:        FirstName - first name from the sheet
                   5974:        LastName  - last name from the sheet
                   5975: 
                   5976:      if just_header was not true these key may also exist
                   5977: 
1.447     foxr     5978:        missingerror - a list of bubble ranges that are considered to be answers
                   5979:                       to a single question that don't have any bubbles filled in.
                   5980:                       Of the form questionnumber:firstbubblenumber:count.
                   5981:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5982:                       to a single question that have more than one bubble filled in.
                   5983:                       Of the form questionnumber::firstbubblenumber:count
                   5984:    
                   5985:                 In the above, count is the number of bubble responses in the
                   5986:                 input line needed to represent the possible answers to the question.
                   5987:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5988:                 per line would have count = 2.
                   5989: 
1.423     albertel 5990:        maxquest     - the number of the last bubble line that was parsed
                   5991: 
                   5992:        (<number> starts at 1)
                   5993:        <number>.answer - zero or more letters representing the selected
                   5994:                          letters from the scanline for the bubble line 
                   5995:                          <number>.
                   5996:                          if blank there was either no bubble or there where
                   5997:                          multiple bubbles, (consult the keys missingerror and
                   5998:                          doubleerror if this is an error condition)
                   5999: 
                   6000: =cut
                   6001: 
1.82      albertel 6002: sub scantron_parse_scanline {
1.691     raeburn  6003:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6004:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6005:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6006: 
1.82      albertel 6007:     my %record;
1.691     raeburn  6008:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6009:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6010: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6011: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6012: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6013: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6014: 	    $record{'scantron.CODE'}=substr($data,
                   6015: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6016: 					    $$scantron_config{'CODElength'});
1.191     albertel 6017: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6018: 		$record{'scantron.useCODE'}=1;
                   6019: 	    }
1.192     albertel 6020: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6021: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6022: 	    }
1.82      albertel 6023: 	} else {
                   6024: 	    #FIXME interpret first N questions
                   6025: 	}
                   6026:     }
1.83      albertel 6027:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6028: 				  $$scantron_config{'IDlength'});
1.157     albertel 6029:     $record{'scantron.PaperID'}=
                   6030: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6031: 	       $$scantron_config{'PaperIDlength'});
                   6032:     $record{'scantron.FirstName'}=
                   6033: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6034: 	       $$scantron_config{'FirstNamelength'});
                   6035:     $record{'scantron.LastName'}=
                   6036: 	substr($data,$$scantron_config{'LastName'}-1,
                   6037: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6038:     if ($just_header) { return \%record; }
1.194     albertel 6039: 
1.82      albertel 6040:     my @alphabet=('A'..'Z');
                   6041:     my $questnum=0;
1.447     foxr     6042:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6043: 
1.691     raeburn  6044:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6045:     if ($randompick || $randomorder) {
                   6046:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6047:                                          $master_seq,$symb_to_resource,
                   6048:                                          $partids_by_symb,$orderedforcode,
                   6049:                                          $respnumlookup,$startline);
                   6050:         if ($total) {
                   6051:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6052:         }
                   6053:         if (ref($totalref)) {
                   6054:             $$totalref = $total;
                   6055:         }
                   6056:     }
                   6057:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6058:     chomp($questions);		# Get rid of any trailing \n.
                   6059:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6060:     while (length($questions)) {
1.691     raeburn  6061:         my $answers_needed;
                   6062:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6063:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6064:         } else {
                   6065: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6066:         }
1.503     raeburn  6067:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6068:                              || 1;
                   6069:         $questnum++;
                   6070:         my $quest_id = $questnum;
                   6071:         my $currentquest = substr($questions,0,$answer_length);
                   6072:         $questions       = substr($questions,$answer_length);
                   6073:         if (length($currentquest) < $answer_length) { next; }
                   6074: 
1.691     raeburn  6075:         my $subdivided;
                   6076:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6077:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6078:         } else {
                   6079:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6080:         }
                   6081:         if ($subdivided =~ /,/) {
1.503     raeburn  6082:             my $subquestnum = 1;
                   6083:             my $subquestions = $currentquest;
1.691     raeburn  6084:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6085:             foreach my $subans (@subanswers_needed) {
                   6086:                 my $subans_length =
                   6087:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6088:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6089:                 $subquestions   = substr($subquestions,$subans_length);
                   6090:                 $quest_id = "$questnum.$subquestnum";
                   6091:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6092:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6093:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6094:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6095:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6096:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6097:                 } else {
                   6098:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6099:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6100:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6101:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6102:                 }
                   6103:                 $subquestnum ++;
                   6104:             }
                   6105:         } else {
                   6106:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6107:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6108:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6109:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6110:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6111:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6112:             } else {
                   6113:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6114:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6115:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6116:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6117:             }
                   6118:         }
                   6119:     }
                   6120:     $record{'scantron.maxquest'}=$questnum;
                   6121:     return \%record;
                   6122: }
1.447     foxr     6123: 
1.691     raeburn  6124: sub get_master_seq {
                   6125:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6126:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6127:                    (ref($symb_to_resource) eq 'HASH'));
                   6128:     my $resource_error;
                   6129:     foreach my $resource (@{$resources}) {
                   6130:         my $ressymb;
                   6131:         if (ref($resource)) {
                   6132:             $ressymb = $resource->symb();
                   6133:             push(@{$master_seq},$ressymb);
                   6134:             $symb_to_resource->{$ressymb} = $resource;
                   6135:         } else {
                   6136:             $resource_error = 1;
                   6137:             last;
                   6138:         }
                   6139:     }
                   6140:     return $resource_error;
                   6141: }
                   6142: 
                   6143: sub get_respnum_lookups {
                   6144:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6145:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6146:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6147:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6148:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6149:                    (ref($startline) eq 'HASH'));
                   6150:     my ($user,$scancode);
                   6151:     if ((exists($record->{'scantron.CODE'})) &&
                   6152:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6153:         $scancode = $record->{'scantron.CODE'};
                   6154:     } else {
                   6155:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6156:     }
                   6157:     my @mapresources =
                   6158:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6159:                      $orderedforcode);
                   6160:     my $total = 0;
                   6161:     my $count = 0;
                   6162:     foreach my $resource (@mapresources) {
                   6163:         my $id = $resource->id();
                   6164:         my $symb = $resource->symb();
                   6165:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6166:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6167:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6168:                 if ($respnum ne '') {
                   6169:                     $respnumlookup->{$count} = $respnum;
                   6170:                     $startline->{$count} = $total;
                   6171:                     $total += $bubble_lines_per_response{$respnum};
                   6172:                     $count ++;
                   6173:                 }
                   6174:             }
                   6175:         }
                   6176:     }
                   6177:     return $total;
                   6178: }
                   6179: 
1.503     raeburn  6180: sub scantron_validator_lettnum {
                   6181:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6182:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6183:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6184: 
                   6185:     # Qon 'letter' implies for each slot in currquest we have:
                   6186:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6187:     #    about anything else (esp. a value of Qoff) for missing
                   6188:     #    bubbles.
                   6189:     #
                   6190:     # Qon 'number' implies each slot gives a digit that indexes the
                   6191:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6192:     #    and * or ? for double bubbles on a single line.
                   6193:     #
1.447     foxr     6194: 
1.503     raeburn  6195:     my $matchon;
                   6196:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6197:         $matchon = '[A-Z]';
                   6198:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6199:         $matchon = '\d';
                   6200:     }
                   6201:     my $occurrences = 0;
1.691     raeburn  6202:     my $responsenum = $questnum-1;
                   6203:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6204:        $responsenum = $respnumlookup->{$questnum-1} 
                   6205:     }
                   6206:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6207:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6208:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6209:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6210:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6211:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6212:         my @singlelines = split('',$currquest);
                   6213:         foreach my $entry (@singlelines) {
                   6214:             $occurrences = &occurence_count($entry,$matchon);
                   6215:             if ($occurrences > 1) {
                   6216:                 last;
                   6217:             }
1.691     raeburn  6218:         }
1.503     raeburn  6219:     } else {
                   6220:         $occurrences = &occurence_count($currquest,$matchon); 
                   6221:     }
                   6222:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6223:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6224:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6225:             my $bubble = substr($currquest,$ans,1);
                   6226:             if ($bubble =~ /$matchon/ ) {
                   6227:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6228:                     if ($bubble == 0) {
                   6229:                         $bubble = 10; 
                   6230:                     }
                   6231:                     $record->{"scantron.$ansnum.answer"} = 
                   6232:                         $alphabet->[$bubble-1];
                   6233:                 } else {
                   6234:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6235:                 }
                   6236:             } else {
                   6237:                 $record->{"scantron.$ansnum.answer"}='';
                   6238:             }
                   6239:             $ansnum++;
                   6240:         }
                   6241:     } elsif (!defined($currquest)
                   6242:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6243:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6244:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6245:             $record->{"scantron.$ansnum.answer"}='';
                   6246:             $ansnum++;
                   6247:         }
                   6248:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6249:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6250:         }
                   6251:     } else {
                   6252:         if ($$scantron_config{'Qon'} eq 'number') {
                   6253:             $currquest = &digits_to_letters($currquest);            
                   6254:         }
                   6255:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6256:             my $bubble = substr($currquest,$ans,1);
                   6257:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6258:             $ansnum++;
                   6259:         }
                   6260:     }
                   6261:     return $ansnum;
                   6262: }
1.447     foxr     6263: 
1.503     raeburn  6264: sub scantron_validator_positional {
                   6265:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6266:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6267:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6268: 
1.503     raeburn  6269:     # Otherwise there's a positional notation;
                   6270:     # each bubble line requires Qlength items, and there are filled in
                   6271:     # bubbles for each case where there 'Qon' characters.
                   6272:     #
1.447     foxr     6273: 
1.503     raeburn  6274:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6275: 
1.503     raeburn  6276:     # If the split only gives us one element.. the full length of the
                   6277:     # answer string, no bubbles are filled in:
1.447     foxr     6278: 
1.507     raeburn  6279:     if ($answers_needed eq '') {
                   6280:         return;
                   6281:     }
                   6282: 
1.503     raeburn  6283:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6284:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6285:             $record->{"scantron.$ansnum.answer"}='';
                   6286:             $ansnum++;
                   6287:         }
                   6288:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6289:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6290:         }
                   6291:     } elsif (scalar(@array) == 2) {
                   6292:         my $location = length($array[0]);
                   6293:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6294:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6295:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6296:             if ($ans eq $line_num) {
                   6297:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6298:             } else {
                   6299:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6300:             }
                   6301:             $ansnum++;
                   6302:          }
                   6303:     } else {
                   6304:         #  If there's more than one instance of a bubble character
                   6305:         #  That's a double bubble; with positional notation we can
                   6306:         #  record all the bubbles filled in as well as the
                   6307:         #  fact this response consists of multiple bubbles.
                   6308:         #
1.691     raeburn  6309:         my $responsenum = $questnum-1;
                   6310:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6311:             $responsenum = $respnumlookup->{$questnum-1}
                   6312:         }
                   6313:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6314:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6315:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6316:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6317:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6318:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6319:             my $doubleerror = 0;
                   6320:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6321:                    (!$doubleerror)) {
                   6322:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6323:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6324:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6325:                if (length(@currarray) > 2) {
                   6326:                    $doubleerror = 1;
                   6327:                } 
                   6328:             }
                   6329:             if ($doubleerror) {
                   6330:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6331:             }
                   6332:         } else {
                   6333:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6334:         }
                   6335:         my $item = $ansnum;
                   6336:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6337:             $record->{"scantron.$item.answer"} = '';
                   6338:             $item ++;
                   6339:         }
1.447     foxr     6340: 
1.503     raeburn  6341:         my @ans=@array;
                   6342:         my $i=0;
                   6343:         my $increment = 0;
                   6344:         while ($#ans) {
                   6345:             $i+=length($ans[0]) + $increment;
                   6346:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6347:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6348:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6349:             shift(@ans);
                   6350:             $increment = 1;
                   6351:         }
                   6352:         $ansnum += $answers_needed;
1.82      albertel 6353:     }
1.503     raeburn  6354:     return $ansnum;
1.82      albertel 6355: }
                   6356: 
1.423     albertel 6357: =pod
                   6358: 
                   6359: =item scantron_add_delay
                   6360: 
                   6361:    Adds an error message that occurred during the grading phase to a
                   6362:    queue of messages to be shown after grading pass is complete
                   6363: 
                   6364:  Arguments:
1.424     albertel 6365:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6366:    $scanline    - the scanline that caused the error
                   6367:    $errormesage - the error message
                   6368:    $errorcode   - a numeric code for the error
                   6369: 
                   6370:  Side Effects:
1.424     albertel 6371:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6372: 
                   6373: =cut
                   6374: 
1.82      albertel 6375: sub scantron_add_delay {
1.140     albertel 6376:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6377:     push(@$delayqueue,
                   6378: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6379: 	  'ecode' => $errorcode }
                   6380: 	 );
1.82      albertel 6381: }
                   6382: 
1.423     albertel 6383: =pod
                   6384: 
                   6385: =item scantron_find_student
                   6386: 
1.424     albertel 6387:    Finds the username for the current scanline
                   6388: 
                   6389:   Arguments:
                   6390:    $scantron_record - hash result from scantron_parse_scanline
                   6391:    $scan_data       - hash of correction information 
                   6392:                       (see &scantron_getfile() form more information)
                   6393:    $idmap           - hash from &username_to_idmap()
                   6394:    $line            - number of current scanline
                   6395:  
                   6396:   Returns:
                   6397:    Either 'username:domain' or undef if unknown
                   6398: 
1.423     albertel 6399: =cut
                   6400: 
1.82      albertel 6401: sub scantron_find_student {
1.157     albertel 6402:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6403:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6404:     if ($scanID =~ /^\s*$/) {
                   6405:  	return &scan_data($scan_data,"$line.user");
                   6406:     }
1.83      albertel 6407:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6408:  	if (lc($id) eq lc($scanID)) {
                   6409:  	    return $$idmap{$id};
                   6410:  	}
1.83      albertel 6411:     }
                   6412:     return undef;
                   6413: }
                   6414: 
1.423     albertel 6415: =pod
                   6416: 
                   6417: =item scantron_filter
                   6418: 
1.424     albertel 6419:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6420:    hidden resources was selected
                   6421: 
1.423     albertel 6422: =cut
                   6423: 
1.83      albertel 6424: sub scantron_filter {
                   6425:     my ($curres)=@_;
1.331     albertel 6426: 
                   6427:     if (ref($curres) && $curres->is_problem()) {
                   6428: 	# if the user has asked to not have either hidden
                   6429: 	# or 'randomout' controlled resources to be graded
                   6430: 	# don't include them
                   6431: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6432: 	    && $curres->randomout) {
                   6433: 	    return 0;
                   6434: 	}
1.83      albertel 6435: 	return 1;
                   6436:     }
                   6437:     return 0;
1.82      albertel 6438: }
                   6439: 
1.423     albertel 6440: =pod
                   6441: 
                   6442: =item scantron_process_corrections
                   6443: 
1.424     albertel 6444:    Gets correction information out of submitted form data and corrects
                   6445:    the scanline
                   6446: 
1.423     albertel 6447: =cut
                   6448: 
1.157     albertel 6449: sub scantron_process_corrections {
                   6450:     my ($r) = @_;
1.257     albertel 6451:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6452:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6453:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6454:     my $which=$env{'form.scantron_line'};
1.200     albertel 6455:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6456:     my ($skip,$err,$errmsg);
1.257     albertel 6457:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6458: 	$skip=1;
1.257     albertel 6459:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6460: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6461: 	    $env{'form.scantron_domain'};
1.157     albertel 6462: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6463: 	($line,$err,$errmsg)=
                   6464: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6465: 				     'ID',{'newid'=>$newid,
1.257     albertel 6466: 				    'username'=>$env{'form.scantron_username'},
                   6467: 				    'domain'=>$env{'form.scantron_domain'}});
                   6468:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6469: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6470: 	my $newCODE;
1.192     albertel 6471: 	my %args;
1.190     albertel 6472: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6473: 	    $newCODE='use_unfound';
1.190     albertel 6474: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6475: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6476: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6477: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6478: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6479: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6480: 	}
1.257     albertel 6481: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6482: 	    $args{'CODE_ignore_dup'}=1;
                   6483: 	}
                   6484: 	$args{'CODE'}=$newCODE;
1.186     albertel 6485: 	($line,$err,$errmsg)=
                   6486: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6487: 				     'CODE',\%args);
1.257     albertel 6488:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6489: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6490: 	    ($line,$err,$errmsg)=
                   6491: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6492: 					 $which,'answer',
                   6493: 					 { 'question'=>$question,
1.503     raeburn  6494: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6495:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6496: 	    if ($err) { last; }
                   6497: 	}
                   6498:     }
                   6499:     if ($err) {
1.703     bisitz   6500:         $r->print(
                   6501:             '<p class="LC_error">'
                   6502:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6503:                 $errmsg)
1.704     raeburn  6504:            .'</p>');
1.157     albertel 6505:     } else {
1.200     albertel 6506: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6507: 	&scantron_putfile($scanlines,$scan_data);
                   6508:     }
                   6509: }
                   6510: 
1.423     albertel 6511: =pod
                   6512: 
                   6513: =item reset_skipping_status
                   6514: 
1.424     albertel 6515:    Forgets the current set of remember skipped scanlines (and thus
                   6516:    reverts back to considering all lines in the
                   6517:    scantron_skipped_<filename> file)
                   6518: 
1.423     albertel 6519: =cut
                   6520: 
1.200     albertel 6521: sub reset_skipping_status {
                   6522:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6523:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6524:     &scantron_putfile(undef,$scan_data);
                   6525: }
                   6526: 
1.423     albertel 6527: =pod
                   6528: 
                   6529: =item start_skipping
                   6530: 
1.424     albertel 6531:    Marks a scanline to be skipped. 
                   6532: 
1.423     albertel 6533: =cut
                   6534: 
1.376     albertel 6535: sub start_skipping {
1.200     albertel 6536:     my ($scan_data,$i)=@_;
                   6537:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6538:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6539: 	$remembered{$i}=2;
                   6540:     } else {
                   6541: 	$remembered{$i}=1;
                   6542:     }
1.200     albertel 6543:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6544: }
                   6545: 
1.423     albertel 6546: =pod
                   6547: 
                   6548: =item should_be_skipped
                   6549: 
1.424     albertel 6550:    Checks whether a scanline should be skipped.
                   6551: 
1.423     albertel 6552: =cut
                   6553: 
1.200     albertel 6554: sub should_be_skipped {
1.376     albertel 6555:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6556:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6557: 	# not redoing old skips
1.376     albertel 6558: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6559: 	return 0;
                   6560:     }
                   6561:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6562: 
                   6563:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6564: 	return 0;
                   6565:     }
1.200     albertel 6566:     return 1;
                   6567: }
                   6568: 
1.423     albertel 6569: =pod
                   6570: 
                   6571: =item remember_current_skipped
                   6572: 
1.424     albertel 6573:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6574:    file and remembers them into scan_data for later use.
                   6575: 
1.423     albertel 6576: =cut
                   6577: 
1.200     albertel 6578: sub remember_current_skipped {
                   6579:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6580:     my %to_remember;
                   6581:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6582: 	if ($scanlines->{'skipped'}[$i]) {
                   6583: 	    $to_remember{$i}=1;
                   6584: 	}
                   6585:     }
1.376     albertel 6586: 
1.200     albertel 6587:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6588:     &scantron_putfile(undef,$scan_data);
                   6589: }
                   6590: 
1.423     albertel 6591: =pod
                   6592: 
                   6593: =item check_for_error
                   6594: 
1.424     albertel 6595:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6596:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6597:     something went wrong.
                   6598: 
1.423     albertel 6599: =cut
                   6600: 
1.200     albertel 6601: sub check_for_error {
                   6602:     my ($r,$result)=@_;
                   6603:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6604: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6605:     }
                   6606: }
1.157     albertel 6607: 
1.423     albertel 6608: =pod
                   6609: 
                   6610: =item scantron_warning_screen
                   6611: 
1.424     albertel 6612:    Interstitial screen to make sure the operator has selected the
                   6613:    correct options before we start the validation phase.
                   6614: 
1.423     albertel 6615: =cut
                   6616: 
1.203     albertel 6617: sub scantron_warning_screen {
1.650     raeburn  6618:     my ($button_text,$symb)=@_;
1.257     albertel 6619:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6620:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6621:     my $CODElist;
1.284     albertel 6622:     if ($scantron_config{'CODElocation'} &&
                   6623: 	$scantron_config{'CODEstart'} &&
                   6624: 	$scantron_config{'CODElength'}) {
                   6625: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6626: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6627: 	$CODElist=
1.492     albertel 6628: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6629: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6630:     }
1.663     raeburn  6631:     my $lastbubblepoints;
                   6632:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6633:         $lastbubblepoints =
                   6634:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6635:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6636:     }
1.492     albertel 6637:     return ('
1.203     albertel 6638: <p>
1.492     albertel 6639: <span class="LC_warning">
1.705     raeburn  6640: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6641: </p>
                   6642: <table>
1.492     albertel 6643: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6644: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6645: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6646: </table>
1.680     raeburn  6647: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6648: '.&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 6649: 
                   6650: <br />
1.492     albertel 6651: ');
1.203     albertel 6652: }
                   6653: 
1.423     albertel 6654: =pod
                   6655: 
                   6656: =item scantron_do_warning
                   6657: 
1.424     albertel 6658:    Check if the operator has picked something for all required
                   6659:    fields. Error out if something is missing.
                   6660: 
1.423     albertel 6661: =cut
                   6662: 
1.203     albertel 6663: sub scantron_do_warning {
1.608     www      6664:     my ($r,$symb)=@_;
1.203     albertel 6665:     if (!$symb) {return '';}
1.324     albertel 6666:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6667:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6668:     if ( $env{'form.selectpage'} eq '' ||
                   6669: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6670: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6671: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6672: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6673: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6674: 	} 
1.257     albertel 6675: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6676: 	    $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 6677: 	} 
1.257     albertel 6678: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6679: 	    $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 6680: 	} 
                   6681:     } else {
1.650     raeburn  6682: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6683:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6684: 	$r->print('
1.663     raeburn  6685: '.$warning.$bubbledbyhand.'
1.492     albertel 6686: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6687: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6688: ');
1.237     albertel 6689:     }
1.614     www      6690:     $r->print("</form><br />");
1.203     albertel 6691:     return '';
                   6692: }
                   6693: 
1.423     albertel 6694: =pod
                   6695: 
                   6696: =item scantron_form_start
                   6697: 
1.424     albertel 6698:     html hidden input for remembering all selected grading options
                   6699: 
1.423     albertel 6700: =cut
                   6701: 
1.203     albertel 6702: sub scantron_form_start {
                   6703:     my ($max_bubble)=@_;
                   6704:     my $result= <<SCANTRONFORM;
                   6705: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6706:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6707:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6708:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6709:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6710:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6711:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6712:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6713:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6714:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6715: SCANTRONFORM
1.447     foxr     6716: 
                   6717:   my $line = 0;
                   6718:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6719:        my $chunk =
                   6720: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6721:        $chunk .=
                   6722: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6723:        $chunk .= 
                   6724:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6725:        $chunk .=
                   6726:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6727:        $chunk .=
                   6728:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6729:        $result .= $chunk;
                   6730:        $line++;
1.691     raeburn  6731:     }
1.203     albertel 6732:     return $result;
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_validate_file
                   6738: 
1.659     raeburn  6739:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6740: 
                   6741:     Also processes any necessary information resets that need to
                   6742:     occur before validation begins (ignore previous corrections,
                   6743:     restarting the skipped records processing)
                   6744: 
1.423     albertel 6745: =cut
                   6746: 
1.157     albertel 6747: sub scantron_validate_file {
1.608     www      6748:     my ($r,$symb) = @_;
1.157     albertel 6749:     if (!$symb) {return '';}
1.324     albertel 6750:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6751:     
1.703     bisitz   6752:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6753:     # them when doing the corrections reset
1.257     albertel 6754:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6755: 	&reset_skipping_status();
                   6756:     }
1.257     albertel 6757:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6758: 	&remember_current_skipped();
1.257     albertel 6759: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6760:     }
                   6761: 
1.257     albertel 6762:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6763: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6764: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6765: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6766: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6767:     }
1.200     albertel 6768: 
1.257     albertel 6769:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6770: 	&scantron_process_corrections($r);
                   6771:     }
1.503     raeburn  6772:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6773:     #get the student pick code ready
                   6774:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6775:     my $nav_error;
1.649     raeburn  6776:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6777:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6778:     if ($nav_error) {
                   6779:         $r->print(&navmap_errormsg());
                   6780:         return '';
                   6781:     }
1.203     albertel 6782:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6783:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6784:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6785:     }
1.157     albertel 6786:     $r->print($result);
                   6787:     
1.334     albertel 6788:     my @validate_phases=( 'sequence',
                   6789: 			  'ID',
1.157     albertel 6790: 			  'CODE',
                   6791: 			  'doublebubble',
                   6792: 			  'missingbubbles');
1.257     albertel 6793:     if (!$env{'form.validatepass'}) {
                   6794: 	$env{'form.validatepass'} = 0;
1.157     albertel 6795:     }
1.257     albertel 6796:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6797: 
1.448     foxr     6798: 
1.157     albertel 6799:     my $stop=0;
                   6800:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6801: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6802: 	$r->rflush();
1.691     raeburn  6803:      
1.157     albertel 6804: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6805: 	{
                   6806: 	    no strict 'refs';
                   6807: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6808: 	}
                   6809:     }
                   6810:     if (!$stop) {
1.650     raeburn  6811: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6812: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6813:                   $warning.
                   6814:                   &mt('Perform verification for each student after storage of submissions?').
                   6815:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6816:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6817:                   ('&nbsp;'x3).'<label>'.
                   6818:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6819:                   '</label></span><br />'.
                   6820:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6821:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6822:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6823:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6824:     } else {
                   6825: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6826: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6827:     }
                   6828:     if ($stop) {
1.334     albertel 6829: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6830: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6831: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6832: 
1.650     raeburn  6833: 	    $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 6834: 	} else {
1.503     raeburn  6835:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6836: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6837:             } else {
1.539     riegler  6838:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6839:             }
1.492     albertel 6840: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6841: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6842: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6843: 	}
1.157     albertel 6844:     }
1.614     www      6845:     $r->print(" </form><br />");
1.157     albertel 6846:     return '';
                   6847: }
                   6848: 
1.423     albertel 6849: 
                   6850: =pod
                   6851: 
                   6852: =item scantron_remove_file
                   6853: 
1.659     raeburn  6854:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6855:    scantron_original_<filename> is never removed
                   6856: 
                   6857: 
1.423     albertel 6858: =cut
                   6859: 
1.200     albertel 6860: sub scantron_remove_file {
1.192     albertel 6861:     my ($which)=@_;
1.257     albertel 6862:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6863:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6864:     my $file='scantron_';
1.200     albertel 6865:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6866: 	$file.=$which.'_';
1.192     albertel 6867:     } else {
                   6868: 	return 'refused';
                   6869:     }
1.257     albertel 6870:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6871:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6872: }
                   6873: 
1.423     albertel 6874: 
                   6875: =pod
                   6876: 
                   6877: =item scantron_remove_scan_data
                   6878: 
1.659     raeburn  6879:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6880:    data file.  (In the case that both the are doing skipped records we need
                   6881:    to remember the old skipped lines for the time being so that element
                   6882:    persists for a while.)
                   6883: 
1.423     albertel 6884: =cut
                   6885: 
1.200     albertel 6886: sub scantron_remove_scan_data {
1.257     albertel 6887:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6888:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6889:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6890:     my @todelete;
1.257     albertel 6891:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6892:     foreach my $key (@keys) {
                   6893: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6894: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6895: 		$key=~/remember_skipping/) {
                   6896: 		next;
                   6897: 	    }
1.192     albertel 6898: 	    push(@todelete,$key);
                   6899: 	}
                   6900:     }
1.200     albertel 6901:     my $result;
1.192     albertel 6902:     if (@todelete) {
1.491     albertel 6903: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6904: 				       \@todelete,$cdom,$cname);
                   6905:     } else {
                   6906: 	$result = 'ok';
1.192     albertel 6907:     }
                   6908:     return $result;
                   6909: }
                   6910: 
1.423     albertel 6911: 
                   6912: =pod
                   6913: 
                   6914: =item scantron_getfile
                   6915: 
1.659     raeburn  6916:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6917:     the scan_data hash
                   6918:   
                   6919:   Arguments:
                   6920:     None
                   6921: 
                   6922:   Returns:
                   6923:     2 hash references
                   6924: 
                   6925:      - first one has 
                   6926:          orig      -
                   6927:          corrected -
                   6928:          skipped   -  each of which points to an array ref of the specified
                   6929:                       file broken up into individual lines
                   6930:          count     - number of scanlines
                   6931:  
                   6932:      - second is the scan_data hash possible keys are
1.425     albertel 6933:        ($number refers to scanline numbered $number and thus the key affects
                   6934:         only that scanline
                   6935:         $bubline refers to the specific bubble line element and the aspects
                   6936:         refers to that specific bubble line element)
                   6937: 
                   6938:        $number.user - username:domain to use
                   6939:        $number.CODE_ignore_dup 
                   6940:                     - ignore the duplicate CODE error 
                   6941:        $number.useCODE
                   6942:                     - use the CODE in the scanline as is
                   6943:        $number.no_bubble.$bubline
                   6944:                     - it is valid that there is no bubbled in bubble
                   6945:                       at $number $bubline
                   6946:        remember_skipping
                   6947:                     - a frozen hash containing keys of $number and values
                   6948:                       of either 
                   6949:                         1 - we are on a 'do skipped records pass' and plan
                   6950:                             on processing this line
                   6951:                         2 - we are on a 'do skipped records pass' and this
                   6952:                             scanline has been marked to skip yet again
1.424     albertel 6953: 
1.423     albertel 6954: =cut
                   6955: 
1.157     albertel 6956: sub scantron_getfile {
1.200     albertel 6957:     #FIXME really would prefer a scantron directory
1.257     albertel 6958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6960:     my $lines;
                   6961:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6962: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6963:     my %scanlines;
                   6964:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6965:     my $temp=$scanlines{'orig'};
                   6966:     $scanlines{'count'}=$#$temp;
                   6967: 
                   6968:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6969: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6970:     if ($lines eq '-1') {
                   6971: 	$scanlines{'corrected'}=[];
                   6972:     } else {
                   6973: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6974:     }
                   6975:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6976: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6977:     if ($lines eq '-1') {
                   6978: 	$scanlines{'skipped'}=[];
                   6979:     } else {
                   6980: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6981:     }
1.175     albertel 6982:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6983:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6984:     my %scan_data = @tmp;
                   6985:     return (\%scanlines,\%scan_data);
                   6986: }
                   6987: 
1.423     albertel 6988: =pod
                   6989: 
                   6990: =item lonnet_putfile
                   6991: 
1.424     albertel 6992:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6993: 
                   6994:  Arguments:
                   6995:    $contents - data to store
                   6996:    $filename - filename to store $contents into
                   6997: 
                   6998:  Returns:
                   6999:    result value from &Apache::lonnet::finishuserfileupload
                   7000: 
1.423     albertel 7001: =cut
                   7002: 
1.157     albertel 7003: sub lonnet_putfile {
                   7004:     my ($contents,$filename)=@_;
1.257     albertel 7005:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7006:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7007:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7008:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7009: 
                   7010: }
                   7011: 
1.423     albertel 7012: =pod
                   7013: 
                   7014: =item scantron_putfile
                   7015: 
1.659     raeburn  7016:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7017:     scan_data hash. (Does not modify the original version only the
                   7018:     corrected and skipped versions.
                   7019: 
                   7020:  Arguments:
                   7021:     $scanlines - hash ref that looks like the first return value from
                   7022:                  &scantron_getfile()
                   7023:     $scan_data - hash ref that looks like the second return value from
                   7024:                  &scantron_getfile()
                   7025: 
1.423     albertel 7026: =cut
                   7027: 
1.157     albertel 7028: sub scantron_putfile {
                   7029:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7030:     #FIXME really would prefer a scantron directory
1.257     albertel 7031:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7033:     if ($scanlines) {
                   7034: 	my $prefix='scantron_';
1.157     albertel 7035: # no need to update orig, shouldn't change
                   7036: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7037: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7038: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7039: 			$prefix.'corrected_'.
1.257     albertel 7040: 			$env{'form.scantron_selectfile'});
1.200     albertel 7041: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7042: 			$prefix.'skipped_'.
1.257     albertel 7043: 			$env{'form.scantron_selectfile'});
1.200     albertel 7044:     }
1.175     albertel 7045:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7046: }
                   7047: 
1.423     albertel 7048: =pod
                   7049: 
                   7050: =item scantron_get_line
                   7051: 
1.424     albertel 7052:    Returns the correct version of the scanline
                   7053: 
                   7054:  Arguments:
                   7055:     $scanlines - hash ref that looks like the first return value from
                   7056:                  &scantron_getfile()
                   7057:     $scan_data - hash ref that looks like the second return value from
                   7058:                  &scantron_getfile()
                   7059:     $i         - number of the requested line (starts at 0)
                   7060: 
                   7061:  Returns:
                   7062:    A scanline, (either the original or the corrected one if it
                   7063:    exists), or undef if the requested scanline should be
                   7064:    skipped. (Either because it's an skipped scanline, or it's an
                   7065:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7066:    pass.
                   7067: 
1.423     albertel 7068: =cut
                   7069: 
1.157     albertel 7070: sub scantron_get_line {
1.200     albertel 7071:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7072:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7073:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7074:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7075:     return $scanlines->{'orig'}[$i]; 
                   7076: }
                   7077: 
1.423     albertel 7078: =pod
                   7079: 
                   7080: =item scantron_todo_count
                   7081: 
1.424     albertel 7082:     Counts the number of scanlines that need processing.
                   7083: 
                   7084:  Arguments:
                   7085:     $scanlines - hash ref that looks like the first return value from
                   7086:                  &scantron_getfile()
                   7087:     $scan_data - hash ref that looks like the second return value from
                   7088:                  &scantron_getfile()
                   7089: 
                   7090:  Returns:
                   7091:     $count - number of scanlines to process
                   7092: 
1.423     albertel 7093: =cut
                   7094: 
1.200     albertel 7095: sub get_todo_count {
                   7096:     my ($scanlines,$scan_data)=@_;
                   7097:     my $count=0;
                   7098:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7099: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7100: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7101: 	$count++;
                   7102:     }
                   7103:     return $count;
                   7104: }
                   7105: 
1.423     albertel 7106: =pod
                   7107: 
                   7108: =item scantron_put_line
                   7109: 
1.659     raeburn  7110:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7111:     data file.
                   7112: 
                   7113:  Arguments:
                   7114:     $scanlines - hash ref that looks like the first return value from
                   7115:                  &scantron_getfile()
                   7116:     $scan_data - hash ref that looks like the second return value from
                   7117:                  &scantron_getfile()
                   7118:     $i         - line number to update
                   7119:     $newline   - contents of the updated scanline
                   7120:     $skip      - if true make the line for skipping and update the
                   7121:                  'skipped' file
                   7122: 
1.423     albertel 7123: =cut
                   7124: 
1.157     albertel 7125: sub scantron_put_line {
1.200     albertel 7126:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7127:     if ($skip) {
                   7128: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7129: 	&start_skipping($scan_data,$i);
1.157     albertel 7130: 	return;
                   7131:     }
                   7132:     $scanlines->{'corrected'}[$i]=$newline;
                   7133: }
                   7134: 
1.423     albertel 7135: =pod
                   7136: 
                   7137: =item scantron_clear_skip
                   7138: 
1.424     albertel 7139:    Remove a line from the 'skipped' file
                   7140: 
                   7141:  Arguments:
                   7142:     $scanlines - hash ref that looks like the first return value from
                   7143:                  &scantron_getfile()
                   7144:     $scan_data - hash ref that looks like the second return value from
                   7145:                  &scantron_getfile()
                   7146:     $i         - line number to update
                   7147: 
1.423     albertel 7148: =cut
                   7149: 
1.376     albertel 7150: sub scantron_clear_skip {
                   7151:     my ($scanlines,$scan_data,$i)=@_;
                   7152:     if (exists($scanlines->{'skipped'}[$i])) {
                   7153: 	undef($scanlines->{'skipped'}[$i]);
                   7154: 	return 1;
                   7155:     }
                   7156:     return 0;
                   7157: }
                   7158: 
1.423     albertel 7159: =pod
                   7160: 
                   7161: =item scantron_filter_not_exam
                   7162: 
1.424     albertel 7163:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7164:    filter out resources that are not marked as 'exam' mode
                   7165: 
1.423     albertel 7166: =cut
                   7167: 
1.334     albertel 7168: sub scantron_filter_not_exam {
                   7169:     my ($curres)=@_;
                   7170:     
                   7171:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7172: 	# if the user has asked to not have either hidden
                   7173: 	# or 'randomout' controlled resources to be graded
                   7174: 	# don't include them
                   7175: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7176: 	    && $curres->randomout) {
                   7177: 	    return 0;
                   7178: 	}
                   7179: 	return 1;
                   7180:     }
                   7181:     return 0;
                   7182: }
                   7183: 
1.423     albertel 7184: =pod
                   7185: 
                   7186: =item scantron_validate_sequence
                   7187: 
1.424     albertel 7188:     Validates the selected sequence, checking for resource that are
                   7189:     not set to exam mode.
                   7190: 
1.423     albertel 7191: =cut
                   7192: 
1.334     albertel 7193: sub scantron_validate_sequence {
                   7194:     my ($r,$currentphase) = @_;
                   7195: 
                   7196:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7197:     unless (ref($navmap)) {
                   7198:         $r->print(&navmap_errormsg());
                   7199:         return (1,$currentphase);
                   7200:     }
1.334     albertel 7201:     my (undef,undef,$sequence)=
                   7202: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7203: 
                   7204:     my $map=$navmap->getResourceByUrl($sequence);
                   7205: 
                   7206:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7207:                                     value="ignore" />');
                   7208:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7209: 	my @resources=
                   7210: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7211: 	if (@resources) {
1.675     bisitz   7212: 	    $r->print(
                   7213:                 '<p class="LC_warning">'
                   7214:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7215:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7216:                    .' work correctly.')
                   7217:                .'</p>'
                   7218:             );
1.334     albertel 7219: 	    return (1,$currentphase);
                   7220: 	}
                   7221:     }
                   7222: 
                   7223:     return (0,$currentphase+1);
                   7224: }
                   7225: 
1.423     albertel 7226: 
                   7227: 
1.157     albertel 7228: sub scantron_validate_ID {
                   7229:     my ($r,$currentphase) = @_;
                   7230:     
                   7231:     #get student info
                   7232:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7233:     my %idmap=&username_to_idmap($classlist);
                   7234: 
                   7235:     #get scantron line setup
1.257     albertel 7236:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7237:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7238: 
                   7239:     my $nav_error;
1.649     raeburn  7240:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7241:     if ($nav_error) {
                   7242:         $r->print(&navmap_errormsg());
                   7243:         return(1,$currentphase);
                   7244:     }
1.157     albertel 7245: 
                   7246:     my %found=('ids'=>{},'usernames'=>{});
                   7247:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7248: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7249: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7250: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7251: 						 $scan_data);
                   7252: 	my $id=$$scan_record{'scantron.ID'};
                   7253: 	my $found;
                   7254: 	foreach my $checkid (keys(%idmap)) {
                   7255: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7256: 	}
                   7257: 	if ($found) {
                   7258: 	    my $username=$idmap{$found};
                   7259: 	    if ($found{'ids'}{$found}) {
                   7260: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7261: 					 $line,'duplicateID',$found);
1.194     albertel 7262: 		return(1,$currentphase);
1.157     albertel 7263: 	    } elsif ($found{'usernames'}{$username}) {
                   7264: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7265: 					 $line,'duplicateID',$username);
1.194     albertel 7266: 		return(1,$currentphase);
1.157     albertel 7267: 	    }
1.186     albertel 7268: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7269: 	    $found{'ids'}{$found}++;
                   7270: 	    $found{'usernames'}{$username}++;
                   7271: 	} else {
                   7272: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7273: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7274: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7275: 		    &scantron_get_correction($r,$i,$scan_record,
                   7276: 					     \%scantron_config,
                   7277: 					     $line,'duplicateID',$username);
1.194     albertel 7278: 		    return(1,$currentphase);
1.157     albertel 7279: 		} elsif (!defined($username)) {
                   7280: 		    &scantron_get_correction($r,$i,$scan_record,
                   7281: 					     \%scantron_config,
                   7282: 					     $line,'incorrectID');
1.194     albertel 7283: 		    return(1,$currentphase);
1.157     albertel 7284: 		}
                   7285: 		$found{'usernames'}{$username}++;
                   7286: 	    } else {
                   7287: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7288: 					 $line,'incorrectID');
1.194     albertel 7289: 		return(1,$currentphase);
1.157     albertel 7290: 	    }
                   7291: 	}
                   7292:     }
                   7293: 
                   7294:     return (0,$currentphase+1);
                   7295: }
                   7296: 
1.423     albertel 7297: 
1.157     albertel 7298: sub scantron_get_correction {
1.691     raeburn  7299:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7300:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7301: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7302: #to show both the current line and the previous one and allow skipping
                   7303: #the previous one or the current one
                   7304: 
1.333     albertel 7305:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7306:         $r->print(
                   7307:             '<p class="LC_warning">'
                   7308:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7309:                 "<b>$error</b>",
                   7310:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7311:            ."</p> \n");
1.157     albertel 7312:     } else {
1.658     bisitz   7313:         $r->print(
                   7314:             '<p class="LC_warning">'
                   7315:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7316:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7317:            ."</p> \n");
                   7318:     }
                   7319:     my $message =
                   7320:         '<p>'
                   7321:        .&mt('The ID on the form is [_1]',
                   7322:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7323:        .'<br />'
1.665     raeburn  7324:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7325:             $$scan_record{'scantron.LastName'},
                   7326:             $$scan_record{'scantron.FirstName'})
                   7327:        .'</p>';
1.242     albertel 7328: 
1.157     albertel 7329:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7330:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7331:                            # Array populated for doublebubble or
                   7332:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7333:                            # to validate radio button checking   
                   7334: 
1.157     albertel 7335:     if ($error =~ /ID$/) {
1.186     albertel 7336: 	if ($error eq 'incorrectID') {
1.658     bisitz   7337:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7338: 		      "</p>\n");
1.157     albertel 7339: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7340:             $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 7341: 	}
1.242     albertel 7342: 	$r->print($message);
1.492     albertel 7343: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7344: 	$r->print("\n<ul><li> ");
                   7345: 	#FIXME it would be nice if this sent back the user ID and
                   7346: 	#could do partial userID matches
                   7347: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7348: 				       'scantron_username','scantron_domain'));
                   7349: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7350: 	$r->print("\n:\n".
1.257     albertel 7351: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7352: 
                   7353: 	$r->print('</li>');
1.186     albertel 7354:     } elsif ($error =~ /CODE$/) {
                   7355: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7356: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7357: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7358: 	    $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 7359: 	}
1.658     bisitz   7360: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7361: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7362:                  ."</p>\n");
1.242     albertel 7363: 	$r->print($message);
1.658     bisitz   7364: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7365: 	$r->print("\n<br /> ");
1.194     albertel 7366: 	my $i=0;
1.273     albertel 7367: 	if ($error eq 'incorrectCODE' 
                   7368: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7369: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7370: 	    if ($closest > 0) {
                   7371: 		foreach my $testcode (@{$closest}) {
                   7372: 		    my $checked='';
1.569     bisitz   7373: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7374: 		    $r->print("
                   7375:    <label>
1.569     bisitz   7376:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7377:        ".&mt("Use the similar CODE [_1] instead.",
                   7378: 	    "<b><tt>".$testcode."</tt></b>")."
                   7379:     </label>
                   7380:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7381: 		    $r->print("\n<br />");
                   7382: 		    $i++;
                   7383: 		}
1.194     albertel 7384: 	    }
                   7385: 	}
1.273     albertel 7386: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7387: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7388: 	    $r->print("
                   7389:     <label>
1.569     bisitz   7390:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7391:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7392: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7393:     </label>");
1.273     albertel 7394: 	    $r->print("\n<br />");
                   7395: 	}
1.194     albertel 7396: 
1.597     wenzelju 7397: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7398: function change_radio(field) {
1.190     albertel 7399:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7400:     var i;
                   7401:     for (i=0;i<slct.length;i++) {
                   7402:         if (slct[i].value==field) { slct[i].checked=true; }
                   7403:     }
                   7404: }
                   7405: ENDSCRIPT
1.187     albertel 7406: 	my $href="/adm/pickcode?".
1.359     www      7407: 	   "form=".&escape("scantronupload").
                   7408: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7409: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7410: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7411: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7412: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7413: 	    $r->print("
                   7414:     <label>
                   7415:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7416:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7417: 	     "<a target='_blank' href='$href'>","</a>")."
                   7418:     </label> 
1.558     bisitz   7419:     ".&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 7420: 	    $r->print("\n<br />");
                   7421: 	}
1.492     albertel 7422: 	$r->print("
                   7423:     <label>
                   7424:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7425:        ".&mt("Use [_1] as the CODE.",
                   7426: 	     "</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 7427: 	$r->print("\n<br /><br />");
1.157     albertel 7428:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7429: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7430: 
                   7431: 	# The form field scantron_questions is acutally a list of line numbers.
                   7432: 	# represented by this form so:
                   7433: 
1.691     raeburn  7434: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7435:                                                 $respnumlookup,$startline);
1.497     foxr     7436: 
1.157     albertel 7437: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7438: 		  $line_list.'" />');
1.242     albertel 7439: 	$r->print($message);
1.492     albertel 7440: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7441: 	foreach my $question (@{$arg}) {
1.503     raeburn  7442: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7443:                                                    $scan_record, $error,
                   7444:                                                    $randomorder,$randompick,
                   7445:                                                    $respnumlookup,$startline);
1.524     raeburn  7446:             push(@lines_to_correct,@linenums);
1.157     albertel 7447: 	}
1.503     raeburn  7448:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7449:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7450: 	$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 7451: 	$r->print($message);
1.492     albertel 7452: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7453: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7454: 
1.503     raeburn  7455: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7456: 	# a list of question numbers. Therefore:
                   7457: 	#
1.691     raeburn  7458: 
                   7459: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7460:                                                 $respnumlookup,$startline);
1.497     foxr     7461: 
1.157     albertel 7462: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7463: 		  $line_list.'" />');
1.157     albertel 7464: 	foreach my $question (@{$arg}) {
1.503     raeburn  7465: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7466:                                                    $scan_record, $error,
                   7467:                                                    $randomorder,$randompick,
                   7468:                                                    $respnumlookup,$startline);
1.524     raeburn  7469:             push(@lines_to_correct,@linenums);
1.157     albertel 7470: 	}
1.503     raeburn  7471:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7472:     } else {
                   7473: 	$r->print("\n<ul>");
                   7474:     }
                   7475:     $r->print("\n</li></ul>");
1.497     foxr     7476: }
                   7477: 
1.503     raeburn  7478: sub verify_bubbles_checked {
                   7479:     my (@ansnums) = @_;
                   7480:     my $ansnumstr = join('","',@ansnums);
                   7481:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7482:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7483: function verify_bubble_radio(form) {
                   7484:     var ansnumArray = new Array ("$ansnumstr");
                   7485:     var need_bubble_count = 0;
                   7486:     for (var i=0; i<ansnumArray.length; i++) {
                   7487:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7488:             var bubble_picked = 0; 
                   7489:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7490:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7491:                     bubble_picked = 1;
                   7492:                 }
                   7493:             }
                   7494:             if (bubble_picked == 0) {
                   7495:                 need_bubble_count ++;
                   7496:             }
                   7497:         }
                   7498:     }
                   7499:     if (need_bubble_count) {
                   7500:         alert("$warning");
                   7501:         return;
                   7502:     }
                   7503:     form.submit(); 
                   7504: }
                   7505: ENDSCRIPT
                   7506:     return $output;
                   7507: }
                   7508: 
1.497     foxr     7509: =pod
                   7510: 
                   7511: =item  questions_to_line_list
1.157     albertel 7512: 
1.497     foxr     7513: Converts a list of questions into a string of comma separated
                   7514: line numbers in the answer sheet used by the questions.  This is
                   7515: used to fill in the scantron_questions form field.
                   7516: 
                   7517:   Arguments:
                   7518:      questions    - Reference to an array of questions.
1.691     raeburn  7519:      randomorder  - True if randomorder in use.
                   7520:      randompick   - True if randompick in use.
                   7521:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7522:                      for current line to question number used for same question
                   7523:                      in "Master Seqence" (as seen by Course Coordinator).
                   7524:      startline    - Reference to hash where key is question number (0 is first)
                   7525:                     and key is number of first bubble line for current student
                   7526:                     or code-based randompick and/or randomorder.
1.693     raeburn  7527: 
1.497     foxr     7528: =cut
                   7529: 
                   7530: 
                   7531: sub questions_to_line_list {
1.691     raeburn  7532:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7533:     my @lines;
                   7534: 
1.503     raeburn  7535:     foreach my $item (@{$questions}) {
                   7536:         my $question = $item;
                   7537:         my ($first,$count,$last);
                   7538:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7539:             $question = $1;
                   7540:             my $subquestion = $2;
1.691     raeburn  7541:             my $responsenum = $question-1;
                   7542:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7543:                 $responsenum = $respnumlookup->{$question-1};
                   7544:                 if (ref($startline) eq 'HASH') {
                   7545:                     $first = $startline->{$question-1} + 1;
                   7546:                 }
                   7547:             } else {
                   7548:                 $first = $first_bubble_line{$responsenum} + 1;
                   7549:             }
                   7550:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7551:             my $subcount = 1;
                   7552:             while ($subcount<$subquestion) {
                   7553:                 $first += $subans[$subcount-1];
                   7554:                 $subcount ++;
                   7555:             }
                   7556:             $count = $subans[$subquestion-1];
                   7557:         } else {
1.691     raeburn  7558:             my $responsenum = $question-1;
                   7559:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7560:                 $responsenum = $respnumlookup->{$question-1};
                   7561:                 if (ref($startline) eq 'HASH') {
                   7562:                     $first = $startline->{$question-1} + 1;
                   7563:                 }
                   7564:             } else {
                   7565:                 $first = $first_bubble_line{$responsenum} + 1;
                   7566:             }
                   7567: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7568:         }
1.506     raeburn  7569:         $last = $first+$count-1;
1.503     raeburn  7570:         push(@lines, ($first..$last));
1.497     foxr     7571:     }
                   7572:     return join(',', @lines);
                   7573: }
                   7574: 
                   7575: =pod 
                   7576: 
                   7577: =item prompt_for_corrections
                   7578: 
                   7579: Prompts for a potentially multiline correction to the
                   7580: user's bubbling (factors out common code from scantron_get_correction
                   7581: for multi and missing bubble cases).
                   7582: 
                   7583:  Arguments:
                   7584:    $r           - Apache request object.
                   7585:    $question    - The question number to prompt for.
                   7586:    $scan_config - The scantron file configuration hash.
                   7587:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7588:    $error       - Type of error
1.691     raeburn  7589:    $randomorder - True if randomorder in use.
                   7590:    $randompick  - True if randompick in use.
                   7591:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7592:                     for current line to question number used for same question
                   7593:                     in "Master Seqence" (as seen by Course Coordinator).
                   7594:    $startline   - Reference to hash where key is question number (0 is first)
                   7595:                   and value is number of first bubble line for current student
                   7596:                   or code-based randompick and/or randomorder.
                   7597: 
1.497     foxr     7598: 
                   7599:  Implicit inputs:
                   7600:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7601:                                   Numbered from 0 (but question numbers are from
                   7602:                                   1.
                   7603:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7604:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7605:                                   type problems render as separate sub-questions, 
1.503     raeburn  7606:                                   in exam mode. This hash contains a 
                   7607:                                   comma-separated list of the lines per 
                   7608:                                   sub-question.
1.510     raeburn  7609:    %responsetype_per_response   - essayresponse, formularesponse,
                   7610:                                   stringresponse, imageresponse, reactionresponse,
                   7611:                                   and organicresponse type problem parts can have
1.503     raeburn  7612:                                   multiple lines per response if the weight
                   7613:                                   assigned exceeds 10.  In this case, only
                   7614:                                   one bubble per line is permitted, but more 
                   7615:                                   than one line might contain bubbles, e.g.
                   7616:                                   bubbling of: line 1 - J, line 2 - J, 
                   7617:                                   line 3 - B would assign 22 points.  
1.497     foxr     7618: 
                   7619: =cut
                   7620: 
                   7621: sub prompt_for_corrections {
1.691     raeburn  7622:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7623:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7624:     my ($current_line,$lines);
                   7625:     my @linenums;
                   7626:     my $questionnum = $question;
1.691     raeburn  7627:     my ($first,$responsenum);
1.503     raeburn  7628:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7629:         $question = $1;
                   7630:         my $subquestion = $2;
1.691     raeburn  7631:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7632:             $responsenum = $respnumlookup->{$question-1};
                   7633:             if (ref($startline) eq 'HASH') {
                   7634:                 $first = $startline->{$question-1};
                   7635:             }
                   7636:         } else {
                   7637:             $responsenum = $question-1;
1.714     raeburn  7638:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7639:         }
                   7640:         $current_line = $first + 1 ;
                   7641:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7642:         my $subcount = 1;
                   7643:         while ($subcount<$subquestion) {
                   7644:             $current_line += $subans[$subcount-1];
                   7645:             $subcount ++;
                   7646:         }
                   7647:         $lines = $subans[$subquestion-1];
                   7648:     } else {
1.691     raeburn  7649:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7650:             $responsenum = $respnumlookup->{$question-1};
                   7651:             if (ref($startline) eq 'HASH') { 
                   7652:                 $first = $startline->{$question-1};
                   7653:             }
                   7654:         } else {
                   7655:             $responsenum = $question-1;
                   7656:             $first = $first_bubble_line{$responsenum};
                   7657:         }
                   7658:         $current_line = $first + 1;
                   7659:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7660:     }
1.497     foxr     7661:     if ($lines > 1) {
1.503     raeburn  7662:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7663:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7664:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7665:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7666:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7667:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7668:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7669:             $r->print(
                   7670:                 &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)
                   7671:                .'<br /><br />'
                   7672:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7673:                .'<br />'
                   7674:                .&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.')
                   7675:                .'<br />'
                   7676:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7677:                .'<br /><br />'
                   7678:             );
1.503     raeburn  7679:         } else {
                   7680:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7681:         }
1.497     foxr     7682:     }
                   7683:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7684:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7685: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7686: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7687:         push(@linenums,$current_line);
1.497     foxr     7688: 	$current_line++;
                   7689:     }
                   7690:     if ($lines > 1) {
                   7691: 	$r->print("<hr /><br />");
                   7692:     }
1.503     raeburn  7693:     return @linenums;
1.157     albertel 7694: }
1.423     albertel 7695: 
                   7696: =pod
                   7697: 
                   7698: =item scantron_bubble_selector
                   7699:   
                   7700:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7701:    possibly showing the existing the selected bubbles if known
1.423     albertel 7702: 
                   7703:  Arguments:
                   7704:     $r           - Apache request object
                   7705:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7706:     $line        - Number of the line being displayed.
1.503     raeburn  7707:     $questionnum - Question number (may include subquestion)
                   7708:     $error       - Type of error.
1.497     foxr     7709:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7710: 
                   7711: =cut
                   7712: 
1.157     albertel 7713: sub scantron_bubble_selector {
1.503     raeburn  7714:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7715:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7716: 
                   7717:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7718:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7719:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7720:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7721:             $max=$$scan_config{'BubblesPerRow'};
                   7722:             if (($scmode eq 'number') && ($max > 10)) {
                   7723:                 $max = 10;
                   7724:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7725:                 $max = 26;
                   7726:             }
                   7727:         } else {
                   7728:             $max = 10;
                   7729:         }
                   7730:     }
1.274     albertel 7731: 
1.157     albertel 7732:     my @alphabet=('A'..'Z');
1.503     raeburn  7733:     $r->print(&Apache::loncommon::start_data_table().
                   7734:               &Apache::loncommon::start_data_table_row());
                   7735:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7736:     for (my $i=0;$i<$max+1;$i++) {
                   7737: 	$r->print("\n".'<td align="center">');
                   7738: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7739: 	else { $r->print('&nbsp;'); }
                   7740: 	$r->print('</td>');
                   7741:     }
1.503     raeburn  7742:     $r->print(&Apache::loncommon::end_data_table_row().
                   7743:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7744:     for (my $i=0;$i<$max;$i++) {
                   7745: 	$r->print("\n".
                   7746: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7747: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7748:     }
1.503     raeburn  7749:     my $nobub_checked = ' ';
                   7750:     if ($error eq 'missingbubble') {
                   7751:         $nobub_checked = ' checked = "checked" ';
                   7752:     }
                   7753:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7754: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7755:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7756:               $line.'" value="'.$questionnum.'" /></td>');
                   7757:     $r->print(&Apache::loncommon::end_data_table_row().
                   7758:               &Apache::loncommon::end_data_table());
1.157     albertel 7759: }
                   7760: 
1.423     albertel 7761: =pod
                   7762: 
                   7763: =item num_matches
                   7764: 
1.424     albertel 7765:    Counts the number of characters that are the same between the two arguments.
                   7766: 
                   7767:  Arguments:
                   7768:    $orig - CODE from the scanline
                   7769:    $code - CODE to match against
                   7770: 
                   7771:  Returns:
                   7772:    $count - integer count of the number of same characters between the
                   7773:             two arguments
                   7774: 
1.423     albertel 7775: =cut
                   7776: 
1.194     albertel 7777: sub num_matches {
                   7778:     my ($orig,$code) = @_;
                   7779:     my @code=split(//,$code);
                   7780:     my @orig=split(//,$orig);
                   7781:     my $same=0;
                   7782:     for (my $i=0;$i<scalar(@code);$i++) {
                   7783: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7784:     }
                   7785:     return $same;
                   7786: }
                   7787: 
1.423     albertel 7788: =pod
                   7789: 
                   7790: =item scantron_get_closely_matching_CODEs
                   7791: 
1.424     albertel 7792:    Cycles through all CODEs and finds the set that has the greatest
                   7793:    number of same characters as the provided CODE
                   7794: 
                   7795:  Arguments:
                   7796:    $allcodes - hash ref returned by &get_codes()
                   7797:    $CODE     - CODE from the current scanline
                   7798: 
                   7799:  Returns:
                   7800:    2 element list
                   7801:     - first elements is number of how closely matching the best fit is 
                   7802:       (5 means best set has 5 matching characters)
                   7803:     - second element is an arrary ref containing the set of valid CODEs
                   7804:       that best fit the passed in CODE
                   7805: 
1.423     albertel 7806: =cut
                   7807: 
1.194     albertel 7808: sub scantron_get_closely_matching_CODEs {
                   7809:     my ($allcodes,$CODE)=@_;
                   7810:     my @CODEs;
                   7811:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7812: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7813:     }
                   7814: 
                   7815:     return ($#CODEs,$CODEs[-1]);
                   7816: }
                   7817: 
1.423     albertel 7818: =pod
                   7819: 
                   7820: =item get_codes
                   7821: 
1.424     albertel 7822:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7823:    set of remembered CODEs.
                   7824: 
                   7825:  Arguments:
                   7826:   $old_name - name of the set of remembered CODEs
                   7827:   $cdom     - domain of the course
                   7828:   $cnum     - internal course name
                   7829: 
                   7830:  Returns:
                   7831:   %allcodes - keys are the valid CODEs, values are all 1
                   7832: 
1.423     albertel 7833: =cut
                   7834: 
1.194     albertel 7835: sub get_codes {
1.280     foxr     7836:     my ($old_name, $cdom, $cnum) = @_;
                   7837:     if (!$old_name) {
                   7838: 	$old_name=$env{'form.scantron_CODElist'};
                   7839:     }
                   7840:     if (!$cdom) {
                   7841: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7842:     }
                   7843:     if (!$cnum) {
                   7844: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7845:     }
1.278     albertel 7846:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7847: 				    $cdom,$cnum);
                   7848:     my %allcodes;
                   7849:     if ($result{"type\0$old_name"} eq 'number') {
                   7850: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7851:     } else {
                   7852: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7853:     }
1.194     albertel 7854:     return %allcodes;
                   7855: }
                   7856: 
1.423     albertel 7857: =pod
                   7858: 
                   7859: =item scantron_validate_CODE
                   7860: 
1.424     albertel 7861:    Validates all scanlines in the selected file to not have any
                   7862:    invalid or underspecified CODEs and that none of the codes are
                   7863:    duplicated if this was requested.
                   7864: 
1.423     albertel 7865: =cut
                   7866: 
1.157     albertel 7867: sub scantron_validate_CODE {
                   7868:     my ($r,$currentphase) = @_;
1.257     albertel 7869:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7870:     if ($scantron_config{'CODElocation'} &&
                   7871: 	$scantron_config{'CODEstart'} &&
                   7872: 	$scantron_config{'CODElength'}) {
1.257     albertel 7873: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7874: 	    &FIXME_blow_up()
                   7875: 	}
                   7876:     } else {
                   7877: 	return (0,$currentphase+1);
                   7878:     }
                   7879:     
                   7880:     my %usedCODEs;
                   7881: 
1.194     albertel 7882:     my %allcodes=&get_codes();
1.186     albertel 7883: 
1.582     raeburn  7884:     my $nav_error;
1.649     raeburn  7885:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7886:     if ($nav_error) {
                   7887:         $r->print(&navmap_errormsg());
                   7888:         return(1,$currentphase);
                   7889:     }
1.447     foxr     7890: 
1.186     albertel 7891:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7892:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7893: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7894: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7895: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7896: 						 $scan_data);
                   7897: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7898: 	my $error=0;
1.224     albertel 7899: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7900: 	    &scantron_get_correction($r,$i,$scan_record,
                   7901: 				     \%scantron_config,
                   7902: 				     $line,'incorrectCODE',\%allcodes);
                   7903: 	    return(1,$currentphase);
                   7904: 	}
1.221     albertel 7905: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7906: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7907: 	    &scantron_get_correction($r,$i,$scan_record,
                   7908: 				     \%scantron_config,
1.194     albertel 7909: 				     $line,'incorrectCODE',\%allcodes);
                   7910: 	    return(1,$currentphase);
1.186     albertel 7911: 	}
1.214     albertel 7912: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7913: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7914: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7915: 	    &scantron_get_correction($r,$i,$scan_record,
                   7916: 				     \%scantron_config,
1.194     albertel 7917: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7918: 	    return(1,$currentphase);
1.186     albertel 7919: 	}
1.524     raeburn  7920: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7921:     }
1.157     albertel 7922:     return (0,$currentphase+1);
                   7923: }
                   7924: 
1.423     albertel 7925: =pod
                   7926: 
                   7927: =item scantron_validate_doublebubble
                   7928: 
1.424     albertel 7929:    Validates all scanlines in the selected file to not have any
                   7930:    bubble lines with multiple bubbles marked.
                   7931: 
1.423     albertel 7932: =cut
                   7933: 
1.157     albertel 7934: sub scantron_validate_doublebubble {
                   7935:     my ($r,$currentphase) = @_;
                   7936:     #get student info
                   7937:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7938:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7939:     my (undef,undef,$sequence)=
                   7940:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7941: 
                   7942:     #get scantron line setup
1.257     albertel 7943:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7944:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7945: 
                   7946:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7947:     unless (ref($navmap)) {
                   7948:         $r->print(&navmap_errormsg());
                   7949:         return(1,$currentphase);
                   7950:     }
                   7951:     my $map=$navmap->getResourceByUrl($sequence);
                   7952:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7953:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7954:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7955:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7956: 
1.583     raeburn  7957:     my $nav_error;
1.691     raeburn  7958:     if (ref($map)) {
                   7959:         $randomorder = $map->randomorder();
                   7960:         $randompick = $map->randompick();
                   7961:         if ($randomorder || $randompick) {
                   7962:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7963:             if ($nav_error) {
                   7964:                 $r->print(&navmap_errormsg());
                   7965:                 return(1,$currentphase);
                   7966:             }
                   7967:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7968:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7969:         }
                   7970:     } else {
                   7971:         $r->print(&navmap_errormsg());
                   7972:         return(1,$currentphase);
                   7973:     }
                   7974: 
1.649     raeburn  7975:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7976:     if ($nav_error) {
                   7977:         $r->print(&navmap_errormsg());
                   7978:         return(1,$currentphase);
                   7979:     }
1.447     foxr     7980: 
1.157     albertel 7981:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7982: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7983: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7984: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7985: 						 $scan_data,undef,\%idmap,$randomorder,
                   7986:                                                  $randompick,$sequence,\@master_seq,
                   7987:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7988:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7989: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7990: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7991: 				 'doublebubble',
1.691     raeburn  7992: 				 $$scan_record{'scantron.doubleerror'},
                   7993:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7994:     	return (1,$currentphase);
                   7995:     }
                   7996:     return (0,$currentphase+1);
                   7997: }
                   7998: 
1.423     albertel 7999: 
1.503     raeburn  8000: sub scantron_get_maxbubble {
1.649     raeburn  8001:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8002:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8003: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8004: 	&restore_bubble_lines();
1.257     albertel 8005: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8006:     }
1.330     albertel 8007: 
1.447     foxr     8008:     my (undef, undef, $sequence) =
1.257     albertel 8009: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8010: 
1.447     foxr     8011:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8012:     unless (ref($navmap)) {
                   8013:         if (ref($nav_error)) {
                   8014:             $$nav_error = 1;
                   8015:         }
1.591     raeburn  8016:         return;
1.582     raeburn  8017:     }
1.191     albertel 8018:     my $map=$navmap->getResourceByUrl($sequence);
                   8019:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8020:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8021: 
                   8022:     &Apache::lonxml::clear_problem_counter();
                   8023: 
1.557     raeburn  8024:     my $uname       = $env{'user.name'};
                   8025:     my $udom        = $env{'user.domain'};
1.435     foxr     8026:     my $cid         = $env{'request.course.id'};
                   8027:     my $total_lines = 0;
                   8028:     %bubble_lines_per_response = ();
1.447     foxr     8029:     %first_bubble_line         = ();
1.503     raeburn  8030:     %subdivided_bubble_lines   = ();
                   8031:     %responsetype_per_response = ();
1.691     raeburn  8032:     %masterseq_id_responsenum  = ();
1.554     raeburn  8033: 
1.447     foxr     8034:     my $response_number = 0;
                   8035:     my $bubble_line     = 0;
1.191     albertel 8036:     foreach my $resource (@resources) {
1.691     raeburn  8037:         my $resid = $resource->id(); 
1.672     raeburn  8038:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8039:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8040:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8041: 	    foreach my $part_id (@{$parts}) {
                   8042:                 my $lines;
                   8043: 
                   8044: 	        # TODO - make this a persistent hash not an array.
                   8045: 
                   8046:                 # optionresponse, matchresponse and rankresponse type items 
                   8047:                 # render as separate sub-questions in exam mode.
                   8048:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8049:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8050:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8051:                     my ($numbub,$numshown);
                   8052:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8053:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8054:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8055:                         }
                   8056:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8057:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8058:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8059:                         }
                   8060:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8061:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8062:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8063:                         }
                   8064:                     }
                   8065:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8066:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8067:                     }
1.649     raeburn  8068:                     my $bubbles_per_row =
                   8069:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8070:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8071:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8072:                         $inner_bubble_lines++;
                   8073:                     }
                   8074:                     for (my $i=0; $i<$numshown; $i++) {
                   8075:                         $subdivided_bubble_lines{$response_number} .= 
                   8076:                             $inner_bubble_lines.',';
                   8077:                     }
                   8078:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8079:                     $lines = $numshown * $inner_bubble_lines;
                   8080:                 } else {
                   8081:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8082:                 }
1.542     raeburn  8083: 
                   8084:                 $first_bubble_line{$response_number} = $bubble_line;
                   8085: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8086:                 $responsetype_per_response{$response_number} = 
                   8087:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8088:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8089: 	        $response_number++;
                   8090: 
                   8091: 	        $bubble_line +=  $lines;
                   8092: 	        $total_lines +=  $lines;
                   8093: 	    }
                   8094:         }
                   8095:     }
1.552     raeburn  8096:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8097: 
                   8098:     &save_bubble_lines();
                   8099:     $env{'form.scantron_maxbubble'} =
                   8100: 	$total_lines;
                   8101:     return $env{'form.scantron_maxbubble'};
                   8102: }
1.523     raeburn  8103: 
1.649     raeburn  8104: sub bubblesheet_bubbles_per_row {
                   8105:     my ($scantron_config) = @_;
                   8106:     my $bubbles_per_row;
                   8107:     if (ref($scantron_config) eq 'HASH') {
                   8108:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8109:     }
                   8110:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8111:         $bubbles_per_row = 10;
                   8112:     }
                   8113:     return $bubbles_per_row;
                   8114: }
                   8115: 
1.157     albertel 8116: sub scantron_validate_missingbubbles {
                   8117:     my ($r,$currentphase) = @_;
                   8118:     #get student info
                   8119:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8120:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8121:     my (undef,undef,$sequence)=
                   8122:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8123: 
                   8124:     #get scantron line setup
1.257     albertel 8125:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8126:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8127: 
                   8128:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8129:     unless (ref($navmap)) {
                   8130:         $r->print(&navmap_errormsg());
                   8131:         return(1,$currentphase);
                   8132:     }
                   8133: 
                   8134:     my $map=$navmap->getResourceByUrl($sequence);
                   8135:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8136:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8137:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8138:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8139: 
1.582     raeburn  8140:     my $nav_error;
1.691     raeburn  8141:     if (ref($map)) {
                   8142:         $randomorder = $map->randomorder();
                   8143:         $randompick = $map->randompick();
                   8144:         if ($randomorder || $randompick) {
                   8145:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8146:             if ($nav_error) {
                   8147:                 $r->print(&navmap_errormsg());
                   8148:                 return(1,$currentphase);
                   8149:             }
                   8150:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8151:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8152:         }
                   8153:     } else {
                   8154:         $r->print(&navmap_errormsg());
                   8155:         return(1,$currentphase);
                   8156:     }
                   8157: 
                   8158: 
1.649     raeburn  8159:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8160:     if ($nav_error) {
1.691     raeburn  8161:         $r->print(&navmap_errormsg());
1.693     raeburn  8162:         return(1,$currentphase);
1.582     raeburn  8163:     }
1.691     raeburn  8164: 
1.157     albertel 8165:     if (!$max_bubble) { $max_bubble=2**31; }
                   8166:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8167: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8168: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8169: 	my $scan_record =
                   8170:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8171: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8172:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8173:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8174: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8175: 	my @to_correct;
1.470     foxr     8176: 	
                   8177: 	# Probably here's where the error is...
                   8178: 
1.157     albertel 8179: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8180:             my $lastbubble;
                   8181:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8182:                my $question = $1;
                   8183:                my $subquestion = $2;
1.691     raeburn  8184:                my ($first,$responsenum);
                   8185:                if ($randomorder || $randompick) {
                   8186:                    $responsenum = $respnumlookup{$question-1};
                   8187:                    $first = $startline{$question-1};
                   8188:                } else {
                   8189:                    $responsenum = $question-1; 
                   8190:                    $first = $first_bubble_line{$responsenum};
                   8191:                }
                   8192:                if (!defined($first)) { next; }
                   8193:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8194:                my $subcount = 1;
                   8195:                while ($subcount<$subquestion) {
                   8196:                    $first += $subans[$subcount-1];
                   8197:                    $subcount ++;
                   8198:                }
                   8199:                my $count = $subans[$subquestion-1];
                   8200:                $lastbubble = $first + $count;
                   8201:             } else {
1.691     raeburn  8202:                my ($first,$responsenum);
                   8203:                if ($randomorder || $randompick) {
                   8204:                    $responsenum = $respnumlookup{$missing-1};
                   8205:                    $first = $startline{$missing-1};
                   8206:                } else {
                   8207:                    $responsenum = $missing-1;
                   8208:                    $first = $first_bubble_line{$responsenum};
                   8209:                }
                   8210:                if (!defined($first)) { next; }
                   8211:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8212:             }
                   8213:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8214: 	    push(@to_correct,$missing);
                   8215: 	}
                   8216: 	if (@to_correct) {
                   8217: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8218: 				     $line,'missingbubble',\@to_correct,
                   8219:                                      $randomorder,$randompick,\%respnumlookup,
                   8220:                                      \%startline);
1.157     albertel 8221: 	    return (1,$currentphase);
                   8222: 	}
                   8223: 
                   8224:     }
                   8225:     return (0,$currentphase+1);
                   8226: }
                   8227: 
1.663     raeburn  8228: sub hand_bubble_option {
                   8229:     my (undef, undef, $sequence) =
                   8230:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8231:     return if ($sequence eq '');
                   8232:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8233:     unless (ref($navmap)) {
                   8234:         return;
                   8235:     }
                   8236:     my $needs_hand_bubbles;
                   8237:     my $map=$navmap->getResourceByUrl($sequence);
                   8238:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8239:     foreach my $res (@resources) {
                   8240:         if (ref($res)) {
                   8241:             if ($res->is_problem()) {
                   8242:                 my $partlist = $res->parts();
                   8243:                 foreach my $part (@{ $partlist }) {
                   8244:                     my @types = $res->responseType($part);
                   8245:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8246:                         $needs_hand_bubbles = 1;
                   8247:                         last;
                   8248:                     }
                   8249:                 }
                   8250:             }
                   8251:         }
                   8252:     }
                   8253:     if ($needs_hand_bubbles) {
                   8254:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8255:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8256:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8257:                &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 />').
                   8258:                '<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  8259:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8260:     }
                   8261:     return;
                   8262: }
1.423     albertel 8263: 
1.82      albertel 8264: sub scantron_process_students {
1.608     www      8265:     my ($r,$symb) = @_;
1.513     foxr     8266: 
1.257     albertel 8267:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8268:     if (!$symb) {
                   8269: 	return '';
                   8270:     }
1.324     albertel 8271:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8272: 
1.257     albertel 8273:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8274:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8275:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8276:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8277:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8278:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8279:     unless (ref($navmap)) {
                   8280:         $r->print(&navmap_errormsg());
                   8281:         return '';
1.691     raeburn  8282:     }
1.83      albertel 8283:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8284:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8285:         %grader_randomlists_by_symb);
1.677     raeburn  8286:     if (ref($map)) {
                   8287:         $randomorder = $map->randomorder();
1.689     raeburn  8288:         $randompick = $map->randompick();
1.691     raeburn  8289:     } else {
                   8290:         $r->print(&navmap_errormsg());
                   8291:         return '';
1.677     raeburn  8292:     }
1.691     raeburn  8293:     my $nav_error;
1.83      albertel 8294:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8295:     if ($randomorder || $randompick) {
                   8296:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8297:         if ($nav_error) {
                   8298:             $r->print(&navmap_errormsg());
                   8299:             return '';
                   8300:         }
                   8301:     }
1.557     raeburn  8302:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8303:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8304: 
1.554     raeburn  8305:     my ($uname,$udom);
1.82      albertel 8306:     my $result= <<SCANTRONFORM;
1.81      albertel 8307: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8308:   <input type="hidden" name="command" value="scantron_configphase" />
                   8309:   $default_form_data
                   8310: SCANTRONFORM
1.82      albertel 8311:     $r->print($result);
                   8312: 
                   8313:     my @delayqueue;
1.542     raeburn  8314:     my (%completedstudents,%scandata);
1.140     albertel 8315:     
1.520     www      8316:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8317:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8318:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8319:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8320:     $r->print('<br />');
1.140     albertel 8321:     my $start=&Time::HiRes::time();
1.158     albertel 8322:     my $i=-1;
1.542     raeburn  8323:     my $started;
1.447     foxr     8324: 
1.649     raeburn  8325:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8326:     if ($nav_error) {
                   8327:         $r->print(&navmap_errormsg());
                   8328:         return '';
                   8329:     }
                   8330: 
1.513     foxr     8331:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8332:     # the user and return.
                   8333: 
                   8334:     if ($ssi_error) {
                   8335: 	$r->print("</form>");
                   8336: 	&ssi_print_error($r);
1.520     www      8337:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8338: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8339:     }
1.447     foxr     8340: 
1.542     raeburn  8341:     my %lettdig = &letter_to_digits();
                   8342:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8343:     my %orderedforcode;
1.542     raeburn  8344: 
1.157     albertel 8345:     while ($i<$scanlines->{'count'}) {
                   8346:  	($uname,$udom)=('','');
                   8347:  	$i++;
1.200     albertel 8348:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8349:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8350: 	if ($started) {
1.667     www      8351: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8352: 	}
                   8353: 	$started=1;
1.691     raeburn  8354:         my %respnumlookup = ();
                   8355:         my %startline = ();
                   8356:         my $total;
1.157     albertel 8357:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8358:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8359:                                                  $randompick,$sequence,\@master_seq,
                   8360:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8361:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8362:                                                  \$total);
1.157     albertel 8363:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8364:  					      \%idmap,$i)) {
                   8365:   	    &scantron_add_delay(\@delayqueue,$line,
                   8366:  				'Unable to find a student that matches',1);
                   8367:  	    next;
                   8368:   	}
                   8369:  	if (exists $completedstudents{$uname}) {
                   8370:  	    &scantron_add_delay(\@delayqueue,$line,
                   8371:  				'Student '.$uname.' has multiple sheets',2);
                   8372:  	    next;
                   8373:  	}
1.677     raeburn  8374:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8375:         my $user = $uname.':'.$usec;
1.157     albertel 8376:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8377: 
1.677     raeburn  8378:         my $scancode;
                   8379:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8380:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8381:             $scancode = $scan_record->{'scantron.CODE'};
                   8382:         } else {
                   8383:             $scancode = '';
                   8384:         }
                   8385: 
                   8386:         my @mapresources = @resources;
1.689     raeburn  8387:         if ($randomorder || $randompick) {
1.678     raeburn  8388:             @mapresources = 
1.691     raeburn  8389:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8390:                              \%orderedforcode);
1.677     raeburn  8391:         }
1.586     raeburn  8392:         my (%partids_by_symb,$res_error);
1.677     raeburn  8393:         foreach my $resource (@mapresources) {
1.586     raeburn  8394:             my $ressymb;
                   8395:             if (ref($resource)) {
                   8396:                 $ressymb = $resource->symb();
                   8397:             } else {
                   8398:                 $res_error = 1;
                   8399:                 last;
                   8400:             }
1.557     raeburn  8401:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8402:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8403:                 my ($analysis,$parts) =
1.672     raeburn  8404:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8405:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8406:                 $partids_by_symb{$ressymb} = $parts;
                   8407:             } else {
                   8408:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8409:             }
1.554     raeburn  8410:         }
                   8411: 
1.586     raeburn  8412:         if ($res_error) {
                   8413:             &scantron_add_delay(\@delayqueue,$line,
                   8414:                                 'An error occurred while grading student '.$uname,2);
                   8415:             next;
                   8416:         }
                   8417: 
1.330     albertel 8418: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8419:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8420: 
                   8421: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8422: 	    &scantron_putfile($scanlines,$scan_data);
                   8423: 	}
1.161     albertel 8424: 	
1.542     raeburn  8425:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8426:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8427:                                    $bubbles_per_row,$randomorder,$randompick,
                   8428:                                    \%respnumlookup,\%startline) 
                   8429:             eq 'ssi_error') {
1.542     raeburn  8430:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8431:             $r->print("</form>");
                   8432:             &ssi_print_error($r);
                   8433:             &Apache::lonnet::remove_lock($lock);
                   8434:             return '';      # Why return ''?  Beats me.
                   8435:         }
1.513     foxr     8436: 
1.692     raeburn  8437:         if (($scancode) && ($randomorder || $randompick)) {
                   8438:             my $parmresult =
                   8439:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8440:                                                        '0_examcode',2,$scancode,
                   8441:                                                        'string_examcode',$uname,
                   8442:                                                        $udom);
                   8443:         }
1.140     albertel 8444: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8445:         if ($env{'form.verifyrecord'}) {
                   8446:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8447:             if ($randompick) {
                   8448:                 if ($total) {
                   8449:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8450:                 }
                   8451:             }
                   8452: 
1.542     raeburn  8453:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8454:             chomp($studentdata);
                   8455:             $studentdata =~ s/\r$//;
                   8456:             my $studentrecord = '';
                   8457:             my $counter = -1;
1.677     raeburn  8458:             foreach my $resource (@mapresources) {
1.554     raeburn  8459:                 my $ressymb = $resource->symb();
1.542     raeburn  8460:                 ($counter,my $recording) =
                   8461:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8462:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8463:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8464:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8465:                 $studentrecord .= $recording;
                   8466:             }
                   8467:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8468:                 &Apache::lonxml::clear_problem_counter();
                   8469:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8470:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8471:                                            $bubbles_per_row,$randomorder,$randompick,
                   8472:                                            \%respnumlookup,\%startline) 
                   8473:                     eq 'ssi_error') {
1.554     raeburn  8474:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8475:                     $r->print("</form>");
                   8476:                     &ssi_print_error($r);
                   8477:                     &Apache::lonnet::remove_lock($lock);
                   8478:                     delete($completedstudents{$uname});
                   8479:                     return '';
                   8480:                 }
1.542     raeburn  8481:                 $counter = -1;
                   8482:                 $studentrecord = '';
1.677     raeburn  8483:                 foreach my $resource (@mapresources) {
1.554     raeburn  8484:                     my $ressymb = $resource->symb();
1.542     raeburn  8485:                     ($counter,my $recording) =
                   8486:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8487:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8488:                                                  \%scantron_config,\%lettdig,$numletts,
                   8489:                                                  $randomorder,$randompick,\%respnumlookup,
                   8490:                                                  \%startline);
1.542     raeburn  8491:                     $studentrecord .= $recording;
                   8492:                 }
                   8493:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8494:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8495:                     if ($scancode eq '') {
1.658     bisitz   8496:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8497:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8498:                     } else {
1.658     bisitz   8499:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8500:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8501:                     }
                   8502:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8503:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8504:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8505:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8506:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8507:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8508:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8509:                               &Apache::loncommon::end_data_table_row().
                   8510:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8511:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8512:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8513:                               &Apache::loncommon::end_data_table_row().
                   8514:                               &Apache::loncommon::end_data_table().'</p>');
                   8515:                 } else {
                   8516:                     $r->print('<br /><span class="LC_warning">'.
                   8517:                              &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 />'.
                   8518:                              &mt("As a consequence, this user's submission history records two tries.").
                   8519:                                  '</span><br />');
                   8520:                 }
                   8521:             }
                   8522:         }
1.543     raeburn  8523:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8524:     } continue {
1.330     albertel 8525: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8526: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8527:     }
1.140     albertel 8528:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8529:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8530: #    my $lasttime = &Time::HiRes::time()-$start;
                   8531: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8532: 
1.200     albertel 8533:     $r->print("</form>");
1.157     albertel 8534:     return '';
1.75      albertel 8535: }
1.157     albertel 8536: 
1.557     raeburn  8537: sub graders_resources_pass {
1.649     raeburn  8538:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8539:         $bubbles_per_row) = @_;
1.557     raeburn  8540:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8541:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8542:         foreach my $resource (@{$resources}) {
                   8543:             my $ressymb = $resource->symb();
                   8544:             my ($analysis,$parts) =
                   8545:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8546:                                           $env{'user.name'},$env{'user.domain'},
                   8547:                                           1,$bubbles_per_row);
1.557     raeburn  8548:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8549:             if (ref($analysis) eq 'HASH') {
                   8550:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8551:                     $grader_randomlists_by_symb->{$ressymb} =
                   8552:                         $analysis->{'parts_withrandomlist'};
                   8553:                 }
                   8554:             }
                   8555:         }
                   8556:     }
                   8557:     return;
                   8558: }
                   8559: 
1.678     raeburn  8560: =pod
                   8561: 
                   8562: =item users_order
                   8563: 
                   8564:   Returns array of resources in current map, ordered based on either CODE,
                   8565:   if this is a CODEd exam, or based on student's identity if this is a 
                   8566:   "NAMEd" exam.
                   8567: 
1.691     raeburn  8568:   Should be used when randomorder and/or randompick applied when the 
                   8569:   corresponding exam was printed, prior to students completing bubblesheets 
                   8570:   for the version of the exam the student received.
1.678     raeburn  8571: 
                   8572: =cut
                   8573: 
                   8574: sub users_order  {
1.691     raeburn  8575:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8576:     my @mapresources;
1.691     raeburn  8577:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8578:         return @mapresources;
1.691     raeburn  8579:     }
                   8580:     if ($scancode) {
                   8581:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8582:             @mapresources = @{$orderedforcode->{$scancode}};
                   8583:         } else {
                   8584:             $env{'form.CODE'} = $scancode;
                   8585:             my $actual_seq =
                   8586:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8587:                                                                $master_seq,
                   8588:                                                                $user,$scancode,1);
                   8589:             if (ref($actual_seq) eq 'ARRAY') {
                   8590:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8591:                 if (ref($orderedforcode) eq 'HASH') {
                   8592:                     if (@mapresources > 0) { 
                   8593:                         $orderedforcode->{$scancode} = \@mapresources;
                   8594:                     }
                   8595:                 }
                   8596:             }
                   8597:             delete($env{'form.CODE'});
1.678     raeburn  8598:         }
                   8599:     } else {
                   8600:         my $actual_seq =
                   8601:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8602:                                                            $master_seq,
1.688     raeburn  8603:                                                            $user,undef,1);
1.678     raeburn  8604:         if (ref($actual_seq) eq 'ARRAY') {
                   8605:             @mapresources = 
                   8606:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8607:         }
1.691     raeburn  8608:     }
                   8609:     return @mapresources;
1.678     raeburn  8610: }
                   8611: 
1.542     raeburn  8612: sub grade_student_bubbles {
1.691     raeburn  8613:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8614:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8615:     my $uselookup = 0;
                   8616:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8617:         (ref($startline) eq 'HASH')) {
                   8618:         $uselookup = 1;
                   8619:     }
                   8620: 
1.554     raeburn  8621:     if (ref($resources) eq 'ARRAY') {
                   8622:         my $count = 0;
                   8623:         foreach my $resource (@{$resources}) {
                   8624:             my $ressymb = $resource->symb();
                   8625:             my %form = ('submitted'      => 'scantron',
                   8626:                         'grade_target'   => 'grade',
                   8627:                         'grade_username' => $uname,
                   8628:                         'grade_domain'   => $udom,
                   8629:                         'grade_courseid' => $env{'request.course.id'},
                   8630:                         'grade_symb'     => $ressymb,
                   8631:                         'CODE'           => $scancode
                   8632:                        );
1.649     raeburn  8633:             if ($bubbles_per_row ne '') {
                   8634:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8635:             }
1.663     raeburn  8636:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8637:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8638:             }
1.554     raeburn  8639:             if (ref($parts) eq 'HASH') {
                   8640:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8641:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8642:                         if ($uselookup) {
                   8643:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8644:                         } else {
                   8645:                             $form{'scantron_questnum_start.'.$part} =
                   8646:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8647:                         }
1.554     raeburn  8648:                         $count++;
                   8649:                     }
                   8650:                 }
                   8651:             }
                   8652:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8653:             return 'ssi_error' if ($ssi_error);
                   8654:             last if (&Apache::loncommon::connection_aborted($r));
                   8655:         }
1.542     raeburn  8656:     }
                   8657:     return;
                   8658: }
                   8659: 
1.157     albertel 8660: sub scantron_upload_scantron_data {
1.608     www      8661:     my ($r,$symb)=@_;
1.565     raeburn  8662:     my $dom = $env{'request.role.domain'};
                   8663:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8664:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8665:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8666: 							  'domainid',
1.565     raeburn  8667: 							  'coursename',$dom);
                   8668:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8669:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8670:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8671:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8672:     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.597     wenzelju 8673:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8674:     function checkUpload(formname) {
                   8675: 	if (formname.upfile.value == "") {
1.579     raeburn  8676: 	    alert("'.$nofile_alert.'");
1.157     albertel 8677: 	    return false;
                   8678: 	}
1.565     raeburn  8679:         if (formname.courseid.value == "") {
1.579     raeburn  8680:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8681:             return false;
                   8682:         }
1.157     albertel 8683: 	formname.submit();
                   8684:     }
1.565     raeburn  8685: 
                   8686:     function ToSyllabus() {
                   8687:         var cdom = '."'$dom'".';
                   8688:         var cnum = document.rules.courseid.value;
                   8689:         if (cdom == "" || cdom == null) {
                   8690:             return;
                   8691:         }
                   8692:         if (cnum == "" || cnum == null) {
                   8693:            return;
                   8694:         }
                   8695:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8696:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8697:         return;
                   8698:     }
                   8699: 
1.597     wenzelju 8700: '));
                   8701:     $r->print('
1.648     bisitz   8702: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8703: 
1.492     albertel 8704: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8705: '.$default_form_data.
                   8706:   &Apache::lonhtmlcommon::start_pick_box().
                   8707:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8708:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8709:   &Apache::lonhtmlcommon::row_closure().
                   8710:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8711:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8712:   &Apache::lonhtmlcommon::row_closure().
                   8713:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8714:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8715:   &Apache::lonhtmlcommon::row_closure().
                   8716:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8717:   '<input type="file" name="upfile" size="50" />'.
                   8718:   &Apache::lonhtmlcommon::row_closure(1).
                   8719:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8720: 
1.492     albertel 8721: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8722: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8723: </form>
1.492     albertel 8724: ');
1.157     albertel 8725:     return '';
                   8726: }
                   8727: 
1.423     albertel 8728: 
1.157     albertel 8729: sub scantron_upload_scantron_data_save {
1.608     www      8730:     my($r,$symb)=@_;
1.182     albertel 8731:     my $doanotherupload=
                   8732: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8733: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8734: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8735: 	'</form>'."\n";
1.257     albertel 8736:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8737: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8738: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8739: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8740: 	unless ($symb) {
1.182     albertel 8741: 	    $r->print($doanotherupload);
                   8742: 	}
1.162     albertel 8743: 	return '';
                   8744:     }
1.257     albertel 8745:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8746:     my $uploadedfile;
1.710     bisitz   8747:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8748:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8749:         $r->print(
                   8750:             &Apache::lonhtmlcommon::confirm_success(
                   8751:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8752:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8753:     } else {
1.568     raeburn  8754:         my $result = 
                   8755:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8756:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8757:         if ($result =~ m{^/uploaded/}) {
                   8758:             $r->print(
                   8759:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8760:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8761:                         (length($env{'form.upfile'})-1),
                   8762:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8763:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8764:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8765:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8766:         } else {
                   8767:             $r->print(
                   8768:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8769:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8770:                           $result,
1.568     raeburn  8771: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8772: 	}
                   8773:     }
1.174     albertel 8774:     if ($symb) {
1.612     www      8775: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8776:     } else {
1.182     albertel 8777: 	$r->print($doanotherupload);
1.174     albertel 8778:     }
1.157     albertel 8779:     return '';
                   8780: }
                   8781: 
1.567     raeburn  8782: sub validate_uploaded_scantron_file {
                   8783:     my ($cdom,$cname,$fname) = @_;
                   8784:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8785:     my @lines;
                   8786:     if ($scanlines ne '-1') {
                   8787:         @lines=split("\n",$scanlines,-1);
                   8788:     }
                   8789:     my $output;
                   8790:     if (@lines) {
                   8791:         my (%counts,$max_match_format);
1.710     bisitz   8792:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8793:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8794:         my %idmap = &username_to_idmap($classlist);
                   8795:         foreach my $key (keys(%idmap)) {
                   8796:             my $lckey = lc($key);
                   8797:             $idmap{$lckey} = $idmap{$key};
                   8798:         }
                   8799:         my %unique_formats;
                   8800:         my @formatlines = &get_scantronformat_file();
                   8801:         foreach my $line (@formatlines) {
                   8802:             chomp($line);
                   8803:             my @config = split(/:/,$line);
                   8804:             my $idstart = $config[5];
                   8805:             my $idlength = $config[6];
                   8806:             if (($idstart ne '') && ($idlength > 0)) {
                   8807:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8808:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8809:                 } else {
                   8810:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8811:                 }
                   8812:             }
                   8813:         }
                   8814:         foreach my $key (keys(%unique_formats)) {
                   8815:             my ($idstart,$idlength) = split(':',$key);
                   8816:             %{$counts{$key}} = (
                   8817:                                'found'   => 0,
                   8818:                                'total'   => 0,
                   8819:                               );
                   8820:             foreach my $line (@lines) {
                   8821:                 next if ($line =~ /^#/);
                   8822:                 next if ($line =~ /^[\s\cz]*$/);
                   8823:                 my $id = substr($line,$idstart-1,$idlength);
                   8824:                 $id = lc($id);
                   8825:                 if (exists($idmap{$id})) {
                   8826:                     $counts{$key}{'found'} ++;
                   8827:                 }
                   8828:                 $counts{$key}{'total'} ++;
                   8829:             }
                   8830:             if ($counts{$key}{'total'}) {
                   8831:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8832:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8833:                     $max_match_pct = $percent_match;
                   8834:                     $max_match_format = $key;
1.710     bisitz   8835:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8836:                     $max_match_count = $counts{$key}{'total'};
                   8837:                 }
                   8838:             }
                   8839:         }
                   8840:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8841:             my $format_descs;
                   8842:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8843:             for (my $i=0; $i<$numwithformat; $i++) {
                   8844:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8845:                 if ($i<$numwithformat-2) {
                   8846:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8847:                 } elsif ($i==$numwithformat-2) {
                   8848:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8849:                 } elsif ($i==$numwithformat-1) {
                   8850:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8851:                 }
                   8852:             }
                   8853:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8854:             $output .= '<br />';
                   8855:             if ($found_match_count == $max_match_count) {
                   8856:                 # 100% matching entries
                   8857:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8858:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8859:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8860:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8861:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8862:                     ' in the file (for the format defined for [_3]).',
                   8863:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8864:             } else {
                   8865:                 # Not all entries matching? -> Show warning and additional info
                   8866:                 $output .=
                   8867:                     &Apache::lonhtmlcommon::confirm_success(
                   8868:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8869:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8870:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8871:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8872:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8873:                         ' in the file (for the format defined for [_3]).',
                   8874:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8875:                     '<p class="LC_info">'.
                   8876:                     &mt('A low percentage of matches results from one of the following:').
                   8877:                     '</p><ul>'.
                   8878:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8879:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8880:                                '<i>'.$cdom.'</i>').'</li>'.
                   8881:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8882:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8883:                     '</ul>';
                   8884:             }
1.567     raeburn  8885:         }
                   8886:     } else {
1.710     bisitz   8887:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8888:     }
                   8889:     return $output;
                   8890: }
                   8891: 
1.202     albertel 8892: sub valid_file {
                   8893:     my ($requested_file)=@_;
                   8894:     foreach my $filename (sort(&scantron_filenames())) {
                   8895: 	if ($requested_file eq $filename) { return 1; }
                   8896:     }
                   8897:     return 0;
                   8898: }
                   8899: 
                   8900: sub scantron_download_scantron_data {
1.608     www      8901:     my ($r,$symb)=@_;
                   8902:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8903:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8904:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8905:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8906:     if (! &valid_file($file)) {
1.492     albertel 8907: 	$r->print('
1.202     albertel 8908: 	<p>
1.686     bisitz   8909: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8910:         </p>
1.492     albertel 8911: ');
1.202     albertel 8912: 	return;
                   8913:     }
                   8914:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8915:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8916:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8917:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8918:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8919:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8920:     $r->print('
1.202     albertel 8921:     <p>
1.723     raeburn  8922: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 8923: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8924:     </p>
                   8925:     <p>
1.492     albertel 8926: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8927: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8928:     </p>
                   8929:     <p>
1.492     albertel 8930: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8931: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8932:     </p>
1.492     albertel 8933: ');
1.202     albertel 8934:     return '';
                   8935: }
1.157     albertel 8936: 
1.523     raeburn  8937: sub checkscantron_results {
1.608     www      8938:     my ($r,$symb) = @_;
1.523     raeburn  8939:     if (!$symb) {return '';}
                   8940:     my $cid = $env{'request.course.id'};
1.542     raeburn  8941:     my %lettdig = &letter_to_digits();
1.523     raeburn  8942:     my $numletts = scalar(keys(%lettdig));
                   8943:     my $cnum = $env{'course.'.$cid.'.num'};
                   8944:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8945:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8946:     my %record;
                   8947:     my %scantron_config =
                   8948:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8949:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8950:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8951:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8952:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8953:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8954:     unless (ref($navmap)) {
                   8955:         $r->print(&navmap_errormsg());
                   8956:         return '';
                   8957:     }
1.523     raeburn  8958:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8959:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8960:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8961:     if (ref($map)) { 
                   8962:         $randomorder=$map->randomorder();
1.689     raeburn  8963:         $randompick=$map->randompick();
1.677     raeburn  8964:     }
1.557     raeburn  8965:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8966:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8967:     if ($nav_error) {
                   8968:         $r->print(&navmap_errormsg());
                   8969:         return '';
1.678     raeburn  8970:     }
1.673     raeburn  8971:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8972:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8973:     my ($uname,$udom);
1.523     raeburn  8974:     my (%scandata,%lastname,%bylast);
                   8975:     $r->print('
                   8976: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8977: 
                   8978:     my @delayqueue;
                   8979:     my %completedstudents;
                   8980: 
1.691     raeburn  8981:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8982:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8983:     my ($username,$domain,$started);
1.649     raeburn  8984:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8985:     if ($nav_error) {
                   8986:         $r->print(&navmap_errormsg());
                   8987:         return '';
                   8988:     }
1.523     raeburn  8989: 
1.667     www      8990:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8991:     my $start=&Time::HiRes::time();
                   8992:     my $i=-1;
                   8993: 
                   8994:     while ($i<$scanlines->{'count'}) {
                   8995:         ($username,$domain,$uname)=('','','');
                   8996:         $i++;
                   8997:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8998:         if ($line=~/^[\s\cz]*$/) { next; }
                   8999:         if ($started) {
1.667     www      9000:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9001:         }
                   9002:         $started=1;
                   9003:         my $scan_record=
                   9004:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9005:                                                      $scan_data);
1.693     raeburn  9006:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9007:                                               \%idmap,$i)) {
1.523     raeburn  9008:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9009:                                 'Unable to find a student that matches',1);
                   9010:             next;
                   9011:         }
                   9012:         if (exists $completedstudents{$uname}) {
                   9013:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9014:                                 'Student '.$uname.' has multiple sheets',2);
                   9015:             next;
                   9016:         }
                   9017:         my $pid = $scan_record->{'scantron.ID'};
                   9018:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9019:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9020:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9021:         my $user = $uname.':'.$usec;
1.523     raeburn  9022:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9023: 
1.678     raeburn  9024:         my $scancode;
1.677     raeburn  9025:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9026:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9027:             $scancode = $scan_record->{'scantron.CODE'};
                   9028:         } else {
                   9029:             $scancode = '';
                   9030:         }
                   9031: 
                   9032:         my @mapresources = @resources;
1.691     raeburn  9033:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9034:         my %respnumlookup=();
                   9035:         my %startline=();
1.689     raeburn  9036:         if ($randomorder || $randompick) {
1.678     raeburn  9037:             @mapresources =
1.691     raeburn  9038:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9039:                              \%orderedforcode);
                   9040:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9041:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9042:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9043:                                              \%respnumlookup,\%startline);
                   9044:             if ($randompick && $total) {
                   9045:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9046:             }
1.677     raeburn  9047:         }
1.691     raeburn  9048:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9049:         chomp($scandata{$pid});
                   9050:         $scandata{$pid} =~ s/\r$//;
                   9051: 
1.523     raeburn  9052:         my $counter = -1;
1.677     raeburn  9053:         foreach my $resource (@mapresources) {
1.557     raeburn  9054:             my $parts;
1.554     raeburn  9055:             my $ressymb = $resource->symb();
1.557     raeburn  9056:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9057:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9058:                 (my $analysis,$parts) =
1.672     raeburn  9059:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9060:                                               $username,$domain,undef,
                   9061:                                               $bubbles_per_row);
1.557     raeburn  9062:             } else {
                   9063:                 $parts = $grader_partids_by_symb{$ressymb};
                   9064:             }
1.542     raeburn  9065:             ($counter,my $recording) =
                   9066:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9067:                                          $scandata{$pid},$parts,
1.691     raeburn  9068:                                          \%scantron_config,\%lettdig,$numletts,
                   9069:                                          $randomorder,$randompick,
                   9070:                                          \%respnumlookup,\%startline);
1.542     raeburn  9071:             $record{$pid} .= $recording;
1.523     raeburn  9072:         }
                   9073:     }
                   9074:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9075:     $r->print('<br />');
                   9076:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9077:     $passed = 0;
                   9078:     $failed = 0;
                   9079:     $numstudents = 0;
                   9080:     foreach my $last (sort(keys(%bylast))) {
                   9081:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9082:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9083:                 my $showscandata = $scandata{$pid};
                   9084:                 my $showrecord = $record{$pid};
                   9085:                 $showscandata =~ s/\s/&nbsp;/g;
                   9086:                 $showrecord =~ s/\s/&nbsp;/g;
                   9087:                 if ($scandata{$pid} eq $record{$pid}) {
                   9088:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9089:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9090: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9091: '</tr>'."\n".
                   9092: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9093: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9094:                     $passed ++;
                   9095:                 } else {
                   9096:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9097:                     $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  9098: '</tr>'."\n".
                   9099: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9100: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9101: '</tr>'."\n";
                   9102:                     $failed ++;
                   9103:                 }
                   9104:                 $numstudents ++;
                   9105:             }
                   9106:         }
                   9107:     }
1.648     bisitz   9108:     $r->print(
                   9109:         '<p>'
                   9110:        .&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).',
                   9111:             '<b>',
                   9112:             $numstudents,
                   9113:             '</b>',
                   9114:             $env{'form.scantron_maxbubble'})
                   9115:        .'</p>'
                   9116:     );
1.682     raeburn  9117:     $r->print('<p>'
1.683     raeburn  9118:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9119:              .'<br />'
                   9120:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9121:              .'</p>'
                   9122:     );
1.523     raeburn  9123:     if ($passed) {
1.572     www      9124:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9125:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9126:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9127:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9128:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9129:                  $okstudents."\n".
                   9130:                  &Apache::loncommon::end_data_table().'<br />');
                   9131:     }
                   9132:     if ($failed) {
1.572     www      9133:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9134:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9135:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9136:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9137:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9138:                  $badstudents."\n".
                   9139:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9140:                  &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  9141:     }
1.614     www      9142:     $r->print('</form><br />');
1.523     raeburn  9143:     return;
                   9144: }
                   9145: 
1.542     raeburn  9146: sub verify_scantron_grading {
1.554     raeburn  9147:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9148:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9149:         $respnumlookup,$startline) = @_;
1.542     raeburn  9150:     my ($record,%expected,%startpos);
                   9151:     return ($counter,$record) if (!ref($resource));
                   9152:     return ($counter,$record) if (!$resource->is_problem());
                   9153:     my $symb = $resource->symb();
1.554     raeburn  9154:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9155:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9156:         $counter ++;
                   9157:         $expected{$part_id} = 0;
1.691     raeburn  9158:         my $respnum = $counter;
                   9159:         if ($randomorder || $randompick) {
                   9160:             $respnum = $respnumlookup->{$counter};
                   9161:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9162:         } else {
                   9163:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9164:         }
                   9165:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9166:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9167:             foreach my $item (@sub_lines) {
                   9168:                 $expected{$part_id} += $item;
                   9169:             }
                   9170:         } else {
1.691     raeburn  9171:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9172:         }
                   9173:     }
                   9174:     if ($symb) {
                   9175:         my %recorded;
                   9176:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9177:         if ($returnhash{'version'}) {
                   9178:             my %lasthash=();
                   9179:             my $version;
                   9180:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9181:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9182:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9183:                 }
                   9184:             }
                   9185:             foreach my $key (keys(%lasthash)) {
                   9186:                 if ($key =~ /\.scantron$/) {
                   9187:                     my $value = &unescape($lasthash{$key});
                   9188:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9189:                     if ($value eq '') {
                   9190:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9191:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9192:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9193:                             }
                   9194:                         }
                   9195:                     } else {
                   9196:                         my @tocheck;
                   9197:                         my @items = split(//,$value);
                   9198:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9199:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9200:                             if (@items < $expected{$part_id}) {
                   9201:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9202:                                 my @singles = split(//,$fragment);
                   9203:                                 foreach my $pos (@singles) {
                   9204:                                     if ($pos eq ' ') {
                   9205:                                         push(@tocheck,$pos);
                   9206:                                     } else {
                   9207:                                         my $next = shift(@items);
                   9208:                                         push(@tocheck,$next);
                   9209:                                     }
                   9210:                                 }
                   9211:                             } else {
                   9212:                                 @tocheck = @items;
                   9213:                             }
                   9214:                             foreach my $letter (@tocheck) {
                   9215:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9216:                                     if ($letter !~ /^[A-J]$/) {
                   9217:                                         $letter = $scantron_config->{'Qoff'};
                   9218:                                     }
                   9219:                                     $recorded{$part_id} .= $letter;
                   9220:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9221:                                     my $digit;
                   9222:                                     if ($letter !~ /^[A-J]$/) {
                   9223:                                         $digit = $scantron_config->{'Qoff'};
                   9224:                                     } else {
                   9225:                                         $digit = $lettdig->{$letter};
                   9226:                                     }
                   9227:                                     $recorded{$part_id} .= $digit;
                   9228:                                 }
                   9229:                             }
                   9230:                         } else {
                   9231:                             @tocheck = @items;
                   9232:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9233:                                 my $curr_sub = shift(@tocheck);
                   9234:                                 my $digit;
                   9235:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9236:                                     $digit = $lettdig->{$curr_sub}-1;
                   9237:                                 }
                   9238:                                 if ($curr_sub eq 'J') {
                   9239:                                     $digit += scalar($numletts);
                   9240:                                 }
                   9241:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9242:                                     if ($j == $digit) {
                   9243:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9244:                                     } else {
                   9245:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9246:                                     }
                   9247:                                 }
                   9248:                             }
                   9249:                         }
                   9250:                     }
                   9251:                 }
                   9252:             }
                   9253:         }
1.554     raeburn  9254:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9255:             if ($recorded{$part_id} eq '') {
                   9256:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9257:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9258:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9259:                     }
                   9260:                 }
                   9261:             }
                   9262:             $record .= $recorded{$part_id};
                   9263:         }
                   9264:     }
                   9265:     return ($counter,$record);
                   9266: }
                   9267: 
1.691     raeburn  9268: sub letter_to_digits {
1.542     raeburn  9269:     my %lettdig = (
                   9270:                     A => 1,
                   9271:                     B => 2,
                   9272:                     C => 3,
                   9273:                     D => 4,
                   9274:                     E => 5,
                   9275:                     F => 6,
                   9276:                     G => 7,
                   9277:                     H => 8,
                   9278:                     I => 9,
                   9279:                     J => 0,
                   9280:                   );
                   9281:     return %lettdig;
                   9282: }
                   9283: 
1.423     albertel 9284: 
1.75      albertel 9285: #-------- end of section for handling grading scantron forms -------
                   9286: #
                   9287: #-------------------------------------------------------------------
                   9288: 
1.72      ng       9289: #-------------------------- Menu interface -------------------------
                   9290: #
1.614     www      9291: #--- Href with symb and command ---
                   9292: 
                   9293: sub href_symb_cmd {
                   9294:     my ($symb,$cmd)=@_;
1.669     raeburn  9295:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9296: }
                   9297: 
1.443     banghart 9298: sub grading_menu {
1.608     www      9299:     my ($request,$symb) = @_;
1.443     banghart 9300:     if (!$symb) {return '';}
                   9301: 
                   9302:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9303:                   'command'=>'individual');
1.538     schulted 9304:     
1.598     www      9305:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9306: 
                   9307:     $fields{'command'}='ungraded';
                   9308:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9309: 
                   9310:     $fields{'command'}='table';
                   9311:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9312: 
                   9313:     $fields{'command'}='all_for_one';
                   9314:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9315: 
1.621     www      9316:     $fields{'command'}='downloadfilesselect';
                   9317:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9318: 
1.443     banghart 9319:     $fields{'command'} = 'csvform';
1.538     schulted 9320:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9321:     
1.443     banghart 9322:     $fields{'command'} = 'processclicker';
1.538     schulted 9323:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9324:     
1.443     banghart 9325:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9326:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9327: 
                   9328:     $fields{'command'} = 'initialverifyreceipt';
                   9329:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9330:     
1.598     www      9331:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9332:             items =>[
1.598     www      9333:                         {	linktext => 'Select individual students to grade',
                   9334:                     		url => $url1a,
1.538     schulted 9335:                     		permission => 'F',
1.636     wenzelju 9336:                     		icon => 'grade_students.png',
1.598     www      9337:                     		linktitle => 'Grade current resource for a selection of students.'
                   9338:                         }, 
                   9339:                         {       linktext => 'Grade ungraded submissions.',
                   9340:                                 url => $url1b,
                   9341:                                 permission => 'F',
1.636     wenzelju 9342:                                 icon => 'ungrade_sub.png',
1.598     www      9343:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9344:                         },
1.598     www      9345: 
                   9346:                         {       linktext => 'Grading table',
                   9347:                                 url => $url1c,
                   9348:                                 permission => 'F',
1.636     wenzelju 9349:                                 icon => 'grading_table.png',
1.598     www      9350:                                 linktitle => 'Grade current resource for all students.'
                   9351:                         },
1.615     www      9352:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9353:                                 url => $url1d,
                   9354:                                 permission => 'F',
1.636     wenzelju 9355:                                 icon => 'grade_PageFolder.png',
1.598     www      9356:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9357:                         },
                   9358:                         {       linktext => 'Download submissions',
                   9359:                                 url => $url1e,
                   9360:                                 permission => 'F',
1.636     wenzelju 9361:                                 icon => 'download_sub.png',
1.621     www      9362:                                 linktitle => 'Download all students submissions.'
1.598     www      9363:                         }]},
                   9364:                          { categorytitle=>'Automated Grading',
                   9365:                items =>[
                   9366: 
1.538     schulted 9367:                 	    {	linktext => 'Upload Scores',
                   9368:                     		url => $url2,
                   9369:                     		permission => 'F',
                   9370:                     		icon => 'uploadscores.png',
                   9371:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9372:                 	    },
                   9373:                 	    {	linktext => 'Process Clicker',
                   9374:                     		url => $url3,
                   9375:                     		permission => 'F',
                   9376:                     		icon => 'addClickerInfoFile.png',
                   9377:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9378:                 	    },
1.587     raeburn  9379:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9380:                     		url => $url4,
                   9381:                     		permission => 'F',
1.636     wenzelju 9382:                     		icon => 'bubblesheet.png',
1.648     bisitz   9383:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9384:                 	    },
1.616     www      9385:                             {   linktext => 'Verify Receipt Number',
1.602     www      9386:                                 url => $url5,
                   9387:                                 permission => 'F',
1.636     wenzelju 9388:                                 icon => 'receipt_number.png',
1.602     www      9389:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9390:                             }
                   9391: 
1.538     schulted 9392:                     ]
                   9393:             });
                   9394: 
1.443     banghart 9395:     # Create the menu
                   9396:     my $Str;
1.445     banghart 9397:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9398:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9399:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9400: 
1.602     www      9401:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9402:     return $Str;    
                   9403: }
                   9404: 
1.598     www      9405: 
                   9406: sub ungraded {
                   9407:     my ($request)=@_;
                   9408:     &submit_options($request);
                   9409: }
                   9410: 
1.599     www      9411: sub submit_options_sequence {
1.608     www      9412:     my ($request,$symb) = @_;
1.599     www      9413:     if (!$symb) {return '';}
1.600     www      9414:     &commonJSfunctions($request);
                   9415:     my $result;
1.599     www      9416: 
1.600     www      9417:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9418:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9419:     $result.=&selectfield(0).
1.601     www      9420:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9421:             <div>
                   9422:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9423:             </div>
                   9424:         </div>
                   9425:   </form>';
                   9426:     return $result;
                   9427: }
                   9428: 
                   9429: sub submit_options_table {
1.608     www      9430:     my ($request,$symb) = @_;
1.600     www      9431:     if (!$symb) {return '';}
1.599     www      9432:     &commonJSfunctions($request);
                   9433:     my $result;
                   9434: 
                   9435:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9436:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9437: 
1.632     www      9438:     $result.=&selectfield(0).
1.601     www      9439:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9440:             <div>
                   9441:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9442:             </div>
                   9443:         </div>
                   9444:   </form>';
                   9445:     return $result;
                   9446: }
1.443     banghart 9447: 
1.621     www      9448: sub submit_options_download {
                   9449:     my ($request,$symb) = @_;
                   9450:     if (!$symb) {return '';}
                   9451: 
                   9452:     &commonJSfunctions($request);
                   9453: 
                   9454:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9455:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9456:     $result.='
                   9457: <h2>
                   9458:   '.&mt('Select Students for Which to Download Submissions').'
                   9459: </h2>'.&selectfield(1).'
                   9460:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9461:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9462:             </div>
                   9463:           </div>
1.600     www      9464: 
                   9465: 
1.621     www      9466:   </form>';
                   9467:     return $result;
                   9468: }
                   9469: 
1.443     banghart 9470: #--- Displays the submissions first page -------
                   9471: sub submit_options {
1.608     www      9472:     my ($request,$symb) = @_;
1.72      ng       9473:     if (!$symb) {return '';}
                   9474: 
1.118     ng       9475:     &commonJSfunctions($request);
1.473     albertel 9476:     my $result;
1.533     bisitz   9477: 
1.72      ng       9478:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9479: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9480:     $result.=&selectfield(1).'
1.601     www      9481:                 <input type="hidden" name="command" value="submission" /> 
                   9482: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9483:             </div>
                   9484:           </div>
                   9485: 
                   9486: 
                   9487:   </form>';
                   9488:     return $result;
                   9489: }
1.533     bisitz   9490: 
1.601     www      9491: sub selectfield {
                   9492:    my ($full)=@_;
1.635     raeburn  9493:    my %options = 
                   9494:           (&Apache::lonlocal::texthash(
                   9495:              'yes'       => 'with submissions',
                   9496:              'queued'    => 'in grading queue',
                   9497:              'graded'    => 'with ungraded submissions',
                   9498:              'incorrect' => 'with incorrect submissions',
                   9499:              'all'       => 'with any status'),
                   9500:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9501:    my $result='<div class="LC_columnSection">
1.537     harmsja  9502:   
1.533     bisitz   9503:     <fieldset>
                   9504:       <legend>
                   9505:        '.&mt('Sections').'
                   9506:       </legend>
1.601     www      9507:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9508:     </fieldset>
1.537     harmsja  9509:   
1.533     bisitz   9510:     <fieldset>
                   9511:       <legend>
                   9512:         '.&mt('Groups').'
                   9513:       </legend>
                   9514:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9515:     </fieldset>
1.537     harmsja  9516:   
1.533     bisitz   9517:     <fieldset>
                   9518:       <legend>
                   9519:         '.&mt('Access Status').'
                   9520:       </legend>
1.601     www      9521:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9522:     </fieldset>';
                   9523:     if ($full) {
                   9524:        $result.='
1.533     bisitz   9525:     <fieldset>
                   9526:       <legend>
                   9527:         '.&mt('Submission Status').'
1.601     www      9528:       </legend>'.
1.635     raeburn  9529:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9530:    '</fieldset>';
                   9531:     }
                   9532:     $result.='</div><br />';
1.44      ng       9533:     return $result;
1.2       albertel 9534: }
                   9535: 
1.285     albertel 9536: sub reset_perm {
                   9537:     undef(%perm);
                   9538: }
                   9539: 
                   9540: sub init_perm {
                   9541:     &reset_perm();
1.300     albertel 9542:     foreach my $test_perm ('vgr','mgr','opa') {
                   9543: 
                   9544: 	my $scope = $env{'request.course.id'};
                   9545: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9546: 
                   9547: 	    $scope .= '/'.$env{'request.course.sec'};
                   9548: 	    if ( $perm{$test_perm}=
                   9549: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9550: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9551: 	    } else {
                   9552: 		delete($perm{$test_perm});
                   9553: 	    }
1.285     albertel 9554: 	}
                   9555:     }
                   9556: }
                   9557: 
1.674     raeburn  9558: sub init_old_essays {
                   9559:     my ($symb,$apath,$adom,$aname) = @_;
                   9560:     if ($symb ne '') {
                   9561:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9562:         if (keys(%essays) > 0) {
                   9563:             $old_essays{$symb} = \%essays;
                   9564:         }
                   9565:     }
                   9566:     return;
                   9567: }
                   9568: 
                   9569: sub reset_old_essays {
                   9570:     undef(%old_essays);
                   9571: }
                   9572: 
1.400     www      9573: sub gather_clicker_ids {
1.408     albertel 9574:     my %clicker_ids;
1.400     www      9575: 
                   9576:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9577: 
                   9578:     # Set up a couple variables.
1.407     albertel 9579:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9580:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9581:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9582: 
1.407     albertel 9583:     foreach my $student (keys(%$classlist)) {
1.438     www      9584:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9585:         my $username = $classlist->{$student}->[$username_idx];
                   9586:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9587:         my $clickers =
1.408     albertel 9588: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9589:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9590:             $id=~s/^[\#0]+//;
1.421     www      9591:             $id=~s/[\-\:]//g;
1.407     albertel 9592:             if (exists($clicker_ids{$id})) {
1.408     albertel 9593: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9594:             } else {
1.408     albertel 9595: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9596:             }
                   9597:         }
                   9598:     }
1.407     albertel 9599:     return %clicker_ids;
1.400     www      9600: }
                   9601: 
1.402     www      9602: sub gather_adv_clicker_ids {
1.408     albertel 9603:     my %clicker_ids;
1.402     www      9604:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9605:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9606:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9607:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9608:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9609:             my ($puname,$pudom)=split(/\:/,$person);
                   9610:             my $clickers =
1.408     albertel 9611: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9612:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9613: 		$id=~s/^[\#0]+//;
1.421     www      9614:                 $id=~s/[\-\:]//g;
1.408     albertel 9615: 		if (exists($clicker_ids{$id})) {
                   9616: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9617: 		} else {
                   9618: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9619: 		}
1.405     www      9620:             }
1.402     www      9621:         }
                   9622:     }
1.407     albertel 9623:     return %clicker_ids;
1.402     www      9624: }
                   9625: 
1.413     www      9626: sub clicker_grading_parameters {
                   9627:     return ('gradingmechanism' => 'scalar',
                   9628:             'upfiletype' => 'scalar',
                   9629:             'specificid' => 'scalar',
                   9630:             'pcorrect' => 'scalar',
                   9631:             'pincorrect' => 'scalar');
                   9632: }
                   9633: 
1.400     www      9634: sub process_clicker {
1.608     www      9635:     my ($r,$symb)=@_;
1.400     www      9636:     if (!$symb) {return '';}
                   9637:     my $result=&checkforfile_js();
1.632     www      9638:     $result.=&Apache::loncommon::start_data_table().
                   9639:              &Apache::loncommon::start_data_table_header_row().
                   9640:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9641:              &Apache::loncommon::end_data_table_header_row().
                   9642:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9643: # Attempt to restore parameters from last session, set defaults if not present
                   9644:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9645:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9646:                                                  \%Saveable_Parameters);
                   9647:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9648:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9649:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9650:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9651: 
                   9652:     my %checked;
1.521     www      9653:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9654:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9655:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9656:        }
                   9657:     }
                   9658: 
1.632     www      9659:     my $upload=&mt("Evaluate File");
1.400     www      9660:     my $type=&mt("Type");
1.402     www      9661:     my $attendance=&mt("Award points just for participation");
                   9662:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9663:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9664:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9665:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9666:     my $pcorrect=&mt("Percentage points for correct solution");
                   9667:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9668:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9669: 						   {'iclicker' => 'i>clicker',
1.666     www      9670:                                                     'interwrite' => 'interwrite PRS',
                   9671:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9672:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9673:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9674: function sanitycheck() {
                   9675: // Accept only integer percentages
                   9676:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9677:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9678: // Find out grading choice
                   9679:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9680:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9681:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9682:       }
                   9683:    }
                   9684: // By default, new choice equals user selection
                   9685:    newgradingchoice=gradingchoice;
                   9686: // Not good to give more points for false answers than correct ones
                   9687:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9688:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9689:    }
                   9690: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9691:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9692:       document.forms.gradesupload.pcorrect.value=100;
                   9693:       document.forms.gradesupload.pincorrect.value=100;
                   9694:    }
                   9695: // If the values are different, cannot be attendance only
                   9696:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9697:        (gradingchoice=='attendance')) {
                   9698:        newgradingchoice='personnel';
                   9699:    }
                   9700: // Change grading choice to new one
                   9701:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9702:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9703:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9704:       } else {
                   9705:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9706:       }
                   9707:    }
                   9708: // Remember the old state
                   9709:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9710: }
1.597     wenzelju 9711: ENDUPFORM
                   9712:     $result.= <<ENDUPFORM;
1.400     www      9713: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9714: <input type="hidden" name="symb" value="$symb" />
                   9715: <input type="hidden" name="command" value="processclickerfile" />
                   9716: <input type="file" name="upfile" size="50" />
                   9717: <br /><label>$type: $selectform</label>
1.632     www      9718: ENDUPFORM
                   9719:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9720:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9721:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9722: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9723: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9724: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9725: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9726: <br />&nbsp;&nbsp;&nbsp;
                   9727: <input type="text" name="givenanswer" size="50" />
1.413     www      9728: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9729: ENDGRADINGFORM
                   9730:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9731:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9732:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9733: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9734: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9735: </form>'
1.632     www      9736: ENDPERCFORM
                   9737:     $result.='</td>'.
                   9738:              &Apache::loncommon::end_data_table_row().
                   9739:              &Apache::loncommon::end_data_table();
1.400     www      9740:     return $result;
                   9741: }
                   9742: 
                   9743: sub process_clicker_file {
1.608     www      9744:     my ($r,$symb)=@_;
1.400     www      9745:     if (!$symb) {return '';}
1.413     www      9746: 
                   9747:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9748:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9749:                                               \%Saveable_Parameters);
1.598     www      9750:     my $result='';
1.404     www      9751:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9752: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9753: 	return $result;
1.404     www      9754:     }
1.522     www      9755:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9756:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9757:         return $result;
1.521     www      9758:     }
1.522     www      9759:     my $foundgiven=0;
1.521     www      9760:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9761:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9762:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9763:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9764:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9765:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9766:         $foundgiven=$#answers+1;
1.521     www      9767:     }
1.407     albertel 9768:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9769:     my %correct_ids;
1.404     www      9770:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9771: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9772:     }
                   9773:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9774: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9775: 	   $correct_id=~tr/a-z/A-Z/;
                   9776: 	   $correct_id=~s/\s//gs;
                   9777: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9778:            $correct_id=~s/[\-\:]//g;
1.414     www      9779:            if ($correct_id) {
                   9780: 	      $correct_ids{$correct_id}='specified';
                   9781:            }
                   9782:         }
1.400     www      9783:     }
1.404     www      9784:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9785: 	$result.=&mt('Score based on attendance only');
1.521     www      9786:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9787:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9788:     } else {
1.408     albertel 9789: 	my $number=0;
1.411     www      9790: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9791: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9792: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9793: 	    if ($correct_ids{$id} eq 'specified') {
                   9794: 		$result.=&mt('specified');
                   9795: 	    } else {
                   9796: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9797: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9798: 	    }
                   9799: 	    $number++;
                   9800: 	}
1.411     www      9801:         $result.="</p>\n";
1.710     bisitz   9802:         if ($number==0) {
                   9803:             $result .=
                   9804:                  &Apache::lonhtmlcommon::confirm_success(
                   9805:                      &mt('No IDs found to determine correct answer'),1);
                   9806:             return $result;
                   9807:         }
1.404     www      9808:     }
1.405     www      9809:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9810:         $result .=
                   9811:             &Apache::lonhtmlcommon::confirm_success(
                   9812:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9813:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9814:         return $result;
1.405     www      9815:     }
1.410     www      9816: 
                   9817: # Were able to get all the info needed, now analyze the file
                   9818: 
1.411     www      9819:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9820:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9821:     $result.=&Apache::loncommon::start_data_table().
                   9822:              &Apache::loncommon::start_data_table_header_row().
                   9823:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9824:              &Apache::loncommon::end_data_table_header_row().
                   9825:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9826: <td>
1.410     www      9827: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9828: <input type="hidden" name="symb" value="$symb" />
                   9829: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9830: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9831: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9832: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9833: ENDHEADER
1.522     www      9834:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9835:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9836:     } 
1.408     albertel 9837:     my %responses;
                   9838:     my @questiontitles;
1.405     www      9839:     my $errormsg='';
                   9840:     my $number=0;
                   9841:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9842: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9843:     }
1.419     www      9844:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9845:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9846:     }
1.666     www      9847:     if ($env{'form.upfiletype'} eq 'turning') {
                   9848:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9849:     }
1.411     www      9850:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9851:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9852:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9853:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9854:              '<br />';
1.522     www      9855:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9856:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9857:        return $result;
1.522     www      9858:     } 
1.414     www      9859: # Remember Question Titles
                   9860: # FIXME: Possibly need delimiter other than ":"
                   9861:     for (my $i=0;$i<$number;$i++) {
                   9862:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9863:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9864:     }
1.411     www      9865:     my $correct_count=0;
                   9866:     my $student_count=0;
                   9867:     my $unknown_count=0;
1.414     www      9868: # Match answers with usernames
                   9869: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9870:     foreach my $id (keys(%responses)) {
1.410     www      9871:        if ($correct_ids{$id}) {
1.414     www      9872:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9873:           $correct_count++;
1.410     www      9874:        } elsif ($clicker_ids{$id}) {
1.437     www      9875:           if ($clicker_ids{$id}=~/\,/) {
                   9876: # More than one user with the same clicker!
1.632     www      9877:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9878:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9879:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9880:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9881:                            "<select name='multi".$id."'>";
                   9882:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9883:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9884:              }
                   9885:              $result.='</select>';
                   9886:              $unknown_count++;
                   9887:           } else {
                   9888: # Good: found one and only one user with the right clicker
                   9889:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9890:              $student_count++;
                   9891:           }
1.410     www      9892:        } else {
1.632     www      9893:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9894:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9895:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9896:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9897:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9898:                    "\n".&mt("Domain").": ".
                   9899:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9900:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9901:           $unknown_count++;
1.410     www      9902:        }
1.405     www      9903:     }
1.412     www      9904:     $result.='<hr />'.
                   9905:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9906:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9907:        if ($correct_count==0) {
1.696     bisitz   9908:           $errormsg.="Found no correct answers for grading!";
1.412     www      9909:        } elsif ($correct_count>1) {
1.414     www      9910:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9911:        }
                   9912:     }
1.428     www      9913:     if ($number<1) {
                   9914:        $errormsg.="Found no questions.";
                   9915:     }
1.412     www      9916:     if ($errormsg) {
                   9917:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9918:     } else {
                   9919:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9920:     }
1.632     www      9921:     $result.='</form></td>'.
                   9922:              &Apache::loncommon::end_data_table_row().
                   9923:              &Apache::loncommon::end_data_table();
1.614     www      9924:     return $result;
1.400     www      9925: }
                   9926: 
1.405     www      9927: sub iclicker_eval {
1.406     www      9928:     my ($questiontitles,$responses)=@_;
1.405     www      9929:     my $number=0;
                   9930:     my $errormsg='';
                   9931:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9932:         my %components=&Apache::loncommon::record_sep($line);
                   9933:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9934: 	if ($entries[0] eq 'Question') {
                   9935: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9936: 		$$questiontitles[$number]=$entries[$i];
                   9937: 		$number++;
                   9938: 	    }
                   9939: 	}
                   9940: 	if ($entries[0]=~/^\#/) {
                   9941: 	    my $id=$entries[0];
                   9942: 	    my @idresponses;
                   9943: 	    $id=~s/^[\#0]+//;
                   9944: 	    for (my $i=0;$i<$number;$i++) {
                   9945: 		my $idx=3+$i*6;
1.644     www      9946:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9947: 		push(@idresponses,$entries[$idx]);
                   9948: 	    }
                   9949: 	    $$responses{$id}=join(',',@idresponses);
                   9950: 	}
1.405     www      9951:     }
                   9952:     return ($errormsg,$number);
                   9953: }
                   9954: 
1.419     www      9955: sub interwrite_eval {
                   9956:     my ($questiontitles,$responses)=@_;
                   9957:     my $number=0;
                   9958:     my $errormsg='';
1.420     www      9959:     my $skipline=1;
                   9960:     my $questionnumber=0;
                   9961:     my %idresponses=();
1.419     www      9962:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9963:         my %components=&Apache::loncommon::record_sep($line);
                   9964:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9965:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9966:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9967:         next if $skipline;
                   9968:         if ($entries[0]!=$questionnumber) {
                   9969:            $questionnumber=$entries[0];
                   9970:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9971:            $number++;
1.419     www      9972:         }
1.420     www      9973:         my $id=$entries[4];
                   9974:         $id=~s/^[\#0]+//;
1.421     www      9975:         $id=~s/^v\d*\://i;
                   9976:         $id=~s/[\-\:]//g;
1.420     www      9977:         $idresponses{$id}[$number]=$entries[6];
                   9978:     }
1.524     raeburn  9979:     foreach my $id (keys(%idresponses)) {
1.420     www      9980:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9981:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9982:     }
                   9983:     return ($errormsg,$number);
                   9984: }
                   9985: 
1.666     www      9986: sub turning_eval {
                   9987:     my ($questiontitles,$responses)=@_;
                   9988:     my $number=0;
                   9989:     my $errormsg='';
                   9990:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9991:         my %components=&Apache::loncommon::record_sep($line);
                   9992:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9993:         if ($#entries>$number) { $number=$#entries; }
                   9994:         my $id=$entries[0];
                   9995:         my @idresponses;
                   9996:         $id=~s/^[\#0]+//;
                   9997:         unless ($id) { next; }
                   9998:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9999:             $entries[$idx]=~s/\,/\;/g;
                   10000:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10001:             push(@idresponses,$entries[$idx]);
                   10002:         }
                   10003:         $$responses{$id}=join(',',@idresponses);
                   10004:     }
                   10005:     for (my $i=1; $i<=$number; $i++) {
                   10006:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10007:     }
                   10008:     return ($errormsg,$number);
                   10009: }
                   10010: 
                   10011: 
1.414     www      10012: sub assign_clicker_grades {
1.608     www      10013:     my ($r,$symb)=@_;
1.414     www      10014:     if (!$symb) {return '';}
1.416     www      10015: # See which part we are saving to
1.582     raeburn  10016:     my $res_error;
                   10017:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10018:     if ($res_error) {
                   10019:         return &navmap_errormsg();
                   10020:     }
1.416     www      10021: # FIXME: This should probably look for the first handgradeable part
                   10022:     my $part=$$partlist[0];
                   10023: # Start screen output
1.632     www      10024:     my $result=&Apache::loncommon::start_data_table().
                   10025:              &Apache::loncommon::start_data_table_header_row().
                   10026:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10027:              &Apache::loncommon::end_data_table_header_row().
                   10028:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10029: # Get correct result
                   10030: # FIXME: Possibly need delimiter other than ":"
                   10031:     my @correct=();
1.415     www      10032:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10033:     my $number=$env{'form.number'};
                   10034:     if ($gradingmechanism ne 'attendance') {
1.414     www      10035:        foreach my $key (keys(%env)) {
                   10036:           if ($key=~/^form\.correct\:/) {
                   10037:              my @input=split(/\,/,$env{$key});
                   10038:              for (my $i=0;$i<=$#input;$i++) {
                   10039:                  if (($correct[$i]) && ($input[$i]) &&
                   10040:                      ($correct[$i] ne $input[$i])) {
                   10041:                     $result.='<br /><span class="LC_warning">'.
                   10042:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10043:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10044:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10045:                     $correct[$i]=$input[$i];
                   10046:                  }
                   10047:              }
                   10048:           }
                   10049:        }
1.415     www      10050:        for (my $i=0;$i<$number;$i++) {
1.644     www      10051:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10052:              $result.='<br /><span class="LC_error">'.
                   10053:                       &mt('No correct result given for question "[_1]"!',
                   10054:                           $env{'form.question:'.$i}).'</span>';
                   10055:           }
                   10056:        }
1.644     www      10057:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10058:     }
                   10059: # Start grading
1.415     www      10060:     my $pcorrect=$env{'form.pcorrect'};
                   10061:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10062:     my $storecount=0;
1.632     www      10063:     my %users=();
1.415     www      10064:     foreach my $key (keys(%env)) {
1.420     www      10065:        my $user='';
1.415     www      10066:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10067:           $user=$1;
                   10068:        }
                   10069:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10070:           my $id=$1;
                   10071:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10072:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10073:           } elsif ($env{'form.multi'.$id}) {
                   10074:              $user=$env{'form.multi'.$id};
1.420     www      10075:           }
                   10076:        }
1.632     www      10077:        if ($user) {
                   10078:           if ($users{$user}) {
                   10079:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10080:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10081:                       '</span><br />';
                   10082:           }
                   10083:           $users{$user}=1; 
1.415     www      10084:           my @answer=split(/\,/,$env{$key});
                   10085:           my $sum=0;
1.522     www      10086:           my $realnumber=$number;
1.415     www      10087:           for (my $i=0;$i<$number;$i++) {
1.576     www      10088:              if  ($correct[$i] eq '-') {
                   10089:                 $realnumber--;
1.644     www      10090:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10091:                 if ($gradingmechanism eq 'attendance') {
                   10092:                    $sum+=$pcorrect;
1.576     www      10093:                 } elsif ($correct[$i] eq '*') {
1.522     www      10094:                    $sum+=$pcorrect;
1.415     www      10095:                 } else {
1.644     www      10096: # We actually grade if correct or not
                   10097:                    my $increment=$pincorrect;
                   10098: # Special case: numerical answer "0"
                   10099:                    if ($correct[$i] eq '0') {
                   10100:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10101:                          $increment=$pcorrect;
                   10102:                       }
                   10103: # General numerical answer, both evaluate to something non-zero
                   10104:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10105:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10106:                          $increment=$pcorrect;
                   10107:                       }
                   10108: # Must be just alphanumeric
                   10109:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10110:                       $increment=$pcorrect;
1.415     www      10111:                    }
1.644     www      10112:                    $sum+=$increment;
1.415     www      10113:                 }
                   10114:              }
                   10115:           }
1.522     www      10116:           my $ave=$sum/(100*$realnumber);
1.416     www      10117: # Store
                   10118:           my ($username,$domain)=split(/\:/,$user);
                   10119:           my %grades=();
                   10120:           $grades{"resource.$part.solved"}='correct_by_override';
                   10121:           $grades{"resource.$part.awarded"}=$ave;
                   10122:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10123:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10124:                                                  $env{'request.course.id'},
                   10125:                                                  $domain,$username);
                   10126:           if ($returncode ne 'ok') {
                   10127:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10128:           } else {
                   10129:              $storecount++;
                   10130:           }
1.415     www      10131:        }
                   10132:     }
                   10133: # We are done
1.549     hauer    10134:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10135:              '</td>'.
                   10136:              &Apache::loncommon::end_data_table_row().
                   10137:              &Apache::loncommon::end_data_table();
1.614     www      10138:     return $result;
1.414     www      10139: }
                   10140: 
1.582     raeburn  10141: sub navmap_errormsg {
                   10142:     return '<div class="LC_error">'.
                   10143:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10144:            &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  10145:            '</div>';
                   10146: }
1.607     droeschl 10147: 
1.609     www      10148: sub startpage {
1.671     raeburn  10149:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10150:     if ($nomenu) {
                   10151:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10152:     } else {
                   10153:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10154:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10155:                                                  {'bread_crumbs' => $crumbs}));
                   10156:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10157:     }
1.613     www      10158:     unless ($nodisplayflag) {
1.671     raeburn  10159:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10160:     }
1.607     droeschl 10161: }
1.582     raeburn  10162: 
1.622     www      10163: sub select_problem {
                   10164:     my ($r)=@_;
1.632     www      10165:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10166:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10167:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10168:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10169: }
                   10170: 
1.1       albertel 10171: sub handler {
1.41      ng       10172:     my $request=$_[0];
1.434     albertel 10173:     &reset_caches();
1.646     raeburn  10174:     if ($request->header_only) {
                   10175:         &Apache::loncommon::content_type($request,'text/html');
                   10176:         $request->send_http_header;
                   10177:         return OK;
                   10178:     }
                   10179:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10180: 
1.664     raeburn  10181: # see what command we need to execute
                   10182: 
                   10183:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10184:     my $command=$commands[0];
                   10185: 
1.646     raeburn  10186:     &init_perm();
                   10187:     if (!$env{'request.course.id'}) {
1.664     raeburn  10188:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10189:                 ($command =~ /^scantronupload/)) {
                   10190:             # Not in a course.
                   10191:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10192:             return HTTP_NOT_ACCEPTABLE;
                   10193:         }
1.646     raeburn  10194:     } elsif (!%perm) {
                   10195:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10196:         return OK;
1.41      ng       10197:     }
1.646     raeburn  10198:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10199:     $request->send_http_header;
1.646     raeburn  10200: 
1.160     albertel 10201:     if ($#commands > 0) {
                   10202: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10203:     }
1.608     www      10204: 
                   10205: # see what the symb is
                   10206: 
                   10207:     my $symb=$env{'form.symb'};
                   10208:     unless ($symb) {
                   10209:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10210:        $symb=&Apache::lonnet::symbread($url);
                   10211:     }
1.646     raeburn  10212:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10213: 
1.513     foxr     10214:     $ssi_error = 0;
1.637     www      10215:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10216: #
1.637     www      10217: # Not called from a resource, but inside a course
1.601     www      10218: #    
1.622     www      10219:         &startpage($request,undef,[],1,1);
                   10220:         &select_problem($request);
1.41      ng       10221:     } else {
1.104     albertel 10222: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10223:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10224:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10225:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10226:                     &choose_task_version_form($symb,$env{'form.student'},
                   10227:                                               $env{'form.userdom'});
                   10228:             }
                   10229:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10230:             if ($versionform) {
                   10231:                 $request->print($versionform);
                   10232:             }
                   10233:             $request->print('<br clear="all" />');
1.611     www      10234: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10235:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10236:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10237:                 &choose_task_version_form($symb,$env{'form.student'},
                   10238:                                           $env{'form.userdom'},
                   10239:                                           $env{'form.inhibitmenu'});
                   10240:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10241:             if ($versionform) {
                   10242:                 $request->print($versionform);
                   10243:             }
                   10244:             $request->print('<br clear="all" />');
                   10245:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10246: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10247:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10248:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10249: 	    &pickStudentPage($request,$symb);
1.103     albertel 10250: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10251:             &startpage($request,$symb,
                   10252:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10253:                                        {href=>'',text=>'Select student'},
                   10254:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10255: 	    &displayPage($request,$symb);
1.104     albertel 10256: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10257:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10258:                                        {href=>'',text=>'Select student'},
                   10259:                                        {href=>'',text=>'Grade student'},
                   10260:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10261: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10262: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10263:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10264:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10265: 	    &processGroup($request,$symb);
1.104     albertel 10266: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10267:             &startpage($request,$symb);
                   10268: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10269: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10270:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10271: 	    $request->print(&submit_options($request,$symb));
1.598     www      10272:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10273:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10274:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10275:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10276:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10277:             $request->print(&submit_options_table($request,$symb));
1.598     www      10278:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10279:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10280:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10281: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10282:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10283: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10284: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10285:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10286:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10287: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10288: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10289:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10290:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10291:                                                                              text=>"Modify grades"},
                   10292:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10293: 	    $request->print(&editgrades($request,$symb));
1.602     www      10294:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10295:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10296:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10297: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10298:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10299:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10300: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10301:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10302:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10303:             $request->print(&process_clicker($request,$symb));
1.400     www      10304:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10305:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10306:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10307:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10308:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10309:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10310:                                        {href=>'', text=>'Process clicker file'},
                   10311:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10312:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10313: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10314:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10315: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10316: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10317:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10318: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10319: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10320:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10321: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10322: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10323: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10324:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10325: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10326: 	    } else {
1.257     albertel 10327: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10328: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10329: 		} else {
1.257     albertel 10330: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10331: 		}
1.627     www      10332:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10333: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10334: 	    }
1.246     albertel 10335: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10336:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10337: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10338: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10339:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10340: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10341:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10342:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10343:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10344: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10345:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10346: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10347: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10348:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10349: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10350:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10351:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10352: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10353:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10354:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10355:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10356:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10357: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10358:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10359:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10360:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10361: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10362:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10363:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10364:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10365:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10366:             $request->print(&checkscantron_results($request,$symb));
                   10367:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10368:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10369:             $request->print(&submit_options_download($request,$symb));
                   10370:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10371:             &startpage($request,$symb,
                   10372:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10373:     {href=>'', text=>'Download submissions'}]);
                   10374:             &submit_download_link($request,$symb);
1.106     albertel 10375: 	} elsif ($command) {
1.620     www      10376:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10377: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10378: 	}
1.2       albertel 10379:     }
1.513     foxr     10380:     if ($ssi_error) {
                   10381: 	&ssi_print_error($request);
                   10382:     }
1.671     raeburn  10383:     if ($env{'form.inhibitmenu'}) {
                   10384:         $request->print(&Apache::loncommon::end_page());
                   10385:     } else {
                   10386:         &Apache::lonquickgrades::endGradeScreen($request);
                   10387:     }
1.434     albertel 10388:     &reset_caches();
1.646     raeburn  10389:     return OK;
1.44      ng       10390: }
                   10391: 
1.1       albertel 10392: 1;
                   10393: 
1.13      albertel 10394: __END__;
1.531     jms      10395: 
                   10396: 
                   10397: =head1 NAME
                   10398: 
                   10399: Apache::grades
                   10400: 
                   10401: =head1 SYNOPSIS
                   10402: 
                   10403: Handles the viewing of grades.
                   10404: 
                   10405: This is part of the LearningOnline Network with CAPA project
                   10406: described at http://www.lon-capa.org.
                   10407: 
                   10408: =head1 OVERVIEW
                   10409: 
                   10410: Do an ssi with retries:
1.715     bisitz   10411: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10412: 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
                   10413: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10414: 
                   10415: At least the logic that drives this has been pulled out into loncommon.
                   10416: 
                   10417: 
                   10418: 
                   10419: ssi_with_retries - Does the server side include of a resource.
                   10420:                      if the ssi call returns an error we'll retry it up to
                   10421:                      the number of times requested by the caller.
1.715     bisitz   10422:                      If we still have a problem, no text is appended to the
1.531     jms      10423:                      output and we set some global variables.
                   10424:                      to indicate to the caller an SSI error occurred.  
                   10425:                      All of this is supposed to deal with the issues described
1.715     bisitz   10426:                      in LON-CAPA BZ 5631 see:
1.531     jms      10427:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10428:                      by informing the user that this happened.
                   10429: 
                   10430: Parameters:
                   10431:   resource   - The resource to include.  This is passed directly, without
                   10432:                interpretation to lonnet::ssi.
                   10433:   form       - The form hash parameters that guide the interpretation of the resource
                   10434:                
                   10435:   retries    - Number of retries allowed before giving up completely.
                   10436: Returns:
                   10437:   On success, returns the rendered resource identified by the resource parameter.
                   10438: Side Effects:
                   10439:   The following global variables can be set:
                   10440:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10441:                               It is up to the caller to initialize this to false
                   10442:                               if desired.
                   10443:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10444:                               of the resource that could not be rendered by the ssi
                   10445:                               call.
                   10446:    ssi_error_message   - The error string fetched from the ssi response
                   10447:                               in the event of an error.
                   10448: 
                   10449: 
                   10450: =head1 HANDLER SUBROUTINE
                   10451: 
                   10452: ssi_with_retries()
                   10453: 
                   10454: =head1 SUBROUTINES
                   10455: 
                   10456: =over
                   10457: 
1.671     raeburn  10458: =head1 Routines to display previous version of a Task for a specific student
                   10459: 
                   10460: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10461: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10462: requires a proctor to check-in the student, a new version of the Task will
                   10463: be created when the student is checked in to the new opportunity.
                   10464: 
                   10465: If a particular student has tried two or more versions of a particular task,
                   10466: the submission screen provides a user with vgr privileges (e.g., a Course
                   10467: Coordinator) the ability to display a previous version worked on by the
                   10468: student.  By default, the current version is displayed. If a previous version
                   10469: has been selected for display, submission data are only shown that pertain
                   10470: to that particular version, and the interface to submit grades is not shown.
                   10471: 
                   10472: =over 4
                   10473: 
                   10474: =item show_previous_task_version()
                   10475: 
                   10476: Displays a specified version of a student's Task, as the student sees it.
                   10477: 
                   10478: Inputs: 2
                   10479:         request - request object
                   10480:         symb    - unique symb for current instance of resource
                   10481: 
                   10482: Output: None.
                   10483: 
                   10484: Side Effects: calls &show_problem() to print version of Task, with
                   10485:               version contained in form item: $env{'form.previousversion'}
                   10486: 
                   10487: =item choose_task_version_form()
                   10488: 
                   10489: Displays a web form used to select which version of a student's view of a
                   10490: Task should be displayed.  Either launches a pop-up window, or replaces
                   10491: content in existing pop-up, or replaces page in main window.
                   10492: 
                   10493: Inputs: 4
                   10494:         symb    - unique symb for current instance of resource
                   10495:         uname   - username of student
                   10496:         udom    - domain of student
                   10497:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10498:                   breadcrumbs etc., are displayed
                   10499: 
                   10500: Output: 4
                   10501:         current   - student's current version
                   10502:         displayed - student's version being displayed
                   10503:         result    - scalar containing HTML for web form used to switch to
                   10504:                     a different version (or a link to close window, if pop-up).
                   10505:         js        - javascript for processing selection in versions web form
                   10506: 
                   10507: Side Effects: None.
                   10508: 
                   10509: =item previous_display_javascript()
                   10510: 
                   10511: Inputs: 2
                   10512:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10513:                   breadcrumbs etc., are displayed.
                   10514:         current - student's current version number.
                   10515: 
                   10516: Output: 1
                   10517:         js      - javascript for processing selection in versions web form.
                   10518: 
                   10519: Side Effects: None.
                   10520: 
                   10521: =back
                   10522: 
                   10523: =head1 Routines to process bubblesheet data.
                   10524: 
                   10525: =over 4
                   10526: 
1.531     jms      10527: =item scantron_get_correction() : 
                   10528: 
                   10529:    Builds the interface screen to interact with the operator to fix a
                   10530:    specific error condition in a specific scanline
                   10531: 
                   10532:  Arguments:
                   10533:     $r           - Apache request object
                   10534:     $i           - number of the current scanline
                   10535:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10536:     $scan_config - hash ref as returned from &get_scantron_config()
                   10537:     $line        - full contents of the current scanline
                   10538:     $error       - error condition, valid values are
                   10539:                    'incorrectCODE', 'duplicateCODE',
                   10540:                    'doublebubble', 'missingbubble',
                   10541:                    'duplicateID', 'incorrectID'
                   10542:     $arg         - extra information needed
                   10543:        For errors:
                   10544:          - duplicateID   - paper number that this studentID was seen before on
                   10545:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10546:                            seen on before
                   10547:          - incorrectCODE - current incorrect CODE 
                   10548:          - doublebubble  - array ref of the bubble lines that have double
                   10549:                            bubble errors
                   10550:          - missingbubble - array ref of the bubble lines that have missing
                   10551:                            bubble errors
                   10552: 
1.691     raeburn  10553:    $randomorder - True if exam folder has randomorder set
                   10554:    $randompick  - True if exam folder has randompick set
                   10555:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10556:                      for current line to question number used for same question
                   10557:                      in "Master Seqence" (as seen by Course Coordinator).
                   10558:    $startline   - Reference to hash where key is question number (0 is first)
                   10559:                   and value is number of first bubble line for current student
                   10560:                   or code-based randompick and/or randomorder.
                   10561: 
                   10562: 
                   10563: 
1.531     jms      10564: =item  scantron_get_maxbubble() : 
                   10565: 
1.582     raeburn  10566:    Arguments:
                   10567:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10568:                       failure to retrieve a navmap object.
                   10569:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10570:        calling routine should trap the error condition and display the warning
                   10571:        found in &navmap_errormsg().
                   10572: 
1.649     raeburn  10573:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10574: 
1.531     jms      10575:    Returns the maximum number of bubble lines that are expected to
                   10576:    occur. Does this by walking the selected sequence rendering the
                   10577:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10578:    for what the current value of the problem counter is.
                   10579: 
                   10580:    Caches the results to $env{'form.scantron_maxbubble'},
                   10581:    $env{'form.scantron.bubble_lines.n'}, 
                   10582:    $env{'form.scantron.first_bubble_line.n'} and
                   10583:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10584:    which are the total number of bubble lines, the number of bubble
1.531     jms      10585:    lines for response n and number of the first bubble line for response n,
                   10586:    and a comma separated list of numbers of bubble lines for sub-questions
                   10587:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10588: 
                   10589: 
                   10590: =item  scantron_validate_missingbubbles() : 
                   10591: 
                   10592:    Validates all scanlines in the selected file to not have any
                   10593:     answers that don't have bubbles that have not been verified
                   10594:     to be bubble free.
                   10595: 
                   10596: =item  scantron_process_students() : 
                   10597: 
1.659     raeburn  10598:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10599: 
                   10600:    The parsed scanline hash is added to %env 
                   10601: 
                   10602:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10603:    foreach resource , with the form data of
                   10604: 
                   10605: 	'submitted'     =>'scantron' 
                   10606: 	'grade_target'  =>'grade',
                   10607: 	'grade_username'=> username of student
                   10608: 	'grade_domain'  => domain of student
                   10609: 	'grade_courseid'=> of course
                   10610: 	'grade_symb'    => symb of resource to grade
                   10611: 
                   10612:     This triggers a grading pass. The problem grading code takes care
                   10613:     of converting the bubbled letter information (now in %env) into a
                   10614:     valid submission.
                   10615: 
                   10616: =item  scantron_upload_scantron_data() :
                   10617: 
1.659     raeburn  10618:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10619: 
                   10620: =item  scantron_upload_scantron_data_save() : 
                   10621: 
                   10622:    Adds a provided bubble information data file to the course if user
                   10623:    has the correct privileges to do so. 
                   10624: 
                   10625: =item  valid_file() :
                   10626: 
                   10627:    Validates that the requested bubble data file exists in the course.
                   10628: 
                   10629: =item  scantron_download_scantron_data() : 
                   10630: 
                   10631:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10632:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10633:    course.
                   10634: 
                   10635: =item  scantron_validate_ID() : 
                   10636: 
                   10637:    Validates all scanlines in the selected file to not have any
1.556     weissno  10638:    invalid or underspecified student/employee IDs
1.531     jms      10639: 
1.582     raeburn  10640: =item navmap_errormsg() :
                   10641: 
                   10642:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10643:    Should be called whenever the request to instantiate a navmap object fails.
                   10644: 
                   10645: =back
1.582     raeburn  10646: 
1.531     jms      10647: =back
                   10648: 
                   10649: =cut

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