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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.718   ! bisitz      4: # $Id: grades.pm,v 1.717 2014/01/30 19:11:05 bisitz 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);
                    333: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    334: 	my ($toprow,$bottomrow);
                    335: 	foreach my $foil (@$order) {
                    336: 	    if ($grading{$foil} == 1) {
                    337: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    338: 	    } else {
                    339: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  342: 	}
                    343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   346: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  347:     } elsif ($response eq 'match') {
                    348: 	my %answer=&Apache::lonnet::str2hash($answer);
                    349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    350: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    351: 	my ($toprow,$middlerow,$bottomrow);
                    352: 	foreach my $foil (@$order) {
                    353: 	    my $item=shift(@items);
                    354: 	    if ($grading{$foil} == 1) {
                    355: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  356: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  357: 	    } else {
                    358: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  359: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  360: 	    }
1.398     albertel  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        362: 	}
1.126     ng        363: 	return '<blockquote><table border="1">'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  366: 	    $middlerow.'</tr>'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   368: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  369:     } elsif ($response eq 'radiobutton') {
                    370: 	my %answer=&Apache::lonnet::str2hash($answer);
                    371: 	my ($toprow,$bottomrow);
1.434     albertel  372: 	my $correct = 
1.640     raeburn   373: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  374: 	foreach my $foil (@$order) {
1.148     albertel  375: 	    if (exists($answer{$foil})) {
1.434     albertel  376: 		if ($foil eq $correct) {
1.466     albertel  377: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  378: 		} else {
1.466     albertel  379: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  380: 		}
                    381: 	    } else {
1.466     albertel  382: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  383: 	    }
1.398     albertel  384: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  385: 	}
                    386: 	return '<blockquote><table border="1">'.
1.466     albertel  387: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    388: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   389: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  390:     } elsif ($response eq 'essay') {
1.257     albertel  391: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        392: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  393: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    394: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        395: 
1.257     albertel  396: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    397: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    398: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    399: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    400: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    401: 	    $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        402: 	}
1.166     albertel  403: 	$answer =~ s-\n-<br />-g;
                    404: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  405:     } elsif ( $response eq 'organic') {
                    406: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    407: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    408: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    409: 	return $result;
1.335     albertel  410:     } elsif ( $response eq 'Task') {
                    411: 	if ( $answer eq 'SUBMITTED') {
                    412: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  413: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  414: 	    return $result;
                    415: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    416: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    417: 			       keys(%{$record}));
                    418: 	    return join('<br />',($version,@matches));
                    419: 			       
                    420: 			       
                    421: 	} else {
                    422: 	    my $result =
                    423: 		'<p>'
                    424: 		.&mt('Overall result: [_1]',
                    425: 		     $record->{$version."resource.$respid.$partid.status"})
                    426: 		.'</p>';
                    427: 	    
                    428: 	    $result .= '<ul>';
                    429: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    430: 			     keys(%{$record}));
                    431: 	    foreach my $grade (sort(@grade)) {
                    432: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    433: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    434: 				     $dim, $record->{$grade}).
                    435: 			  '</li>';
                    436: 	    }
                    437: 	    $result.='</ul>';
                    438: 	    return $result;
                    439: 	}
1.716     bisitz    440:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    441:         # Respect multiple input fields, see Bug #5409
1.440     albertel  442: 	$answer = 
                    443: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    444: 							      $answer);
1.122     ng        445:     }
1.118     ng        446:     return $answer;
                    447: }
                    448: 
                    449: #-- A couple of common js functions
                    450: sub commonJSfunctions {
                    451:     my $request = shift;
1.597     wenzelju  452:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        453:     function radioSelection(radioButton) {
                    454: 	var selection=null;
                    455: 	if (radioButton.length > 1) {
                    456: 	    for (var i=0; i<radioButton.length; i++) {
                    457: 		if (radioButton[i].checked) {
                    458: 		    return radioButton[i].value;
                    459: 		}
                    460: 	    }
                    461: 	} else {
                    462: 	    if (radioButton.checked) return radioButton.value;
                    463: 	}
                    464: 	return selection;
                    465:     }
                    466: 
                    467:     function pullDownSelection(selectOne) {
                    468: 	var selection="";
                    469: 	if (selectOne.length > 1) {
                    470: 	    for (var i=0; i<selectOne.length; i++) {
                    471: 		if (selectOne[i].selected) {
                    472: 		    return selectOne[i].value;
                    473: 		}
                    474: 	    }
                    475: 	} else {
1.138     albertel  476:             // only one value it must be the selected one
                    477: 	    return selectOne.value;
1.118     ng        478: 	}
                    479:     }
                    480: COMMONJSFUNCTIONS
                    481: }
                    482: 
1.44      ng        483: #--- Dumps the class list with usernames,list of sections,
                    484: #--- section, ids and fullnames for each user.
                    485: sub getclasslist {
1.449     banghart  486:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  487:     my @getsec;
1.450     banghart  488:     my @getgroup;
1.442     banghart  489:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  490:     if (!ref($getsec)) {
                    491: 	if ($getsec ne '' && $getsec ne 'all') {
                    492: 	    @getsec=($getsec);
                    493: 	}
                    494:     } else {
                    495: 	@getsec=@{$getsec};
                    496:     }
                    497:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  498:     if (!ref($getgroup)) {
                    499: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    500: 	    @getgroup=($getgroup);
                    501: 	}
                    502:     } else {
                    503: 	@getgroup=@{$getgroup};
                    504:     }
                    505:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  506: 
1.449     banghart  507:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  508:     # Bail out if we were unable to get the classlist
1.56      matthew   509:     return if (! defined($classlist));
1.449     banghart  510:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   511:     #
                    512:     my %sections;
                    513:     my %fullnames;
1.205     matthew   514:     foreach my $student (keys(%$classlist)) {
                    515:         my $end      = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    517:         my $start    = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    519:         my $id       = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    521:         my $section  = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    523:         my $fullname = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    525:         my $status   = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  527:         my $group   = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        529: 	# filter students according to status selected
1.442     banghart  530: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    531: 	    if (!($stu_status =~ $status)) {
1.450     banghart  532: 		delete($classlist->{$student});
1.76      ng        533: 		next;
                    534: 	    }
                    535: 	}
1.450     banghart  536: 	# filter students according to groups selected
1.453     banghart  537: 	my @stu_groups = split(/,/,$group);
1.450     banghart  538: 	if (@getgroup) {
                    539: 	    my $exclude = 1;
1.454     banghart  540: 	    foreach my $grp (@getgroup) {
                    541: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  542: 	            if ($stu_group eq $grp) {
                    543: 	                $exclude = 0;
                    544:     	            } 
1.450     banghart  545: 	        }
1.453     banghart  546:     	        if (($grp eq 'none') && !$group) {
                    547:         	        $exclude = 0;
                    548:         	}
1.450     banghart  549: 	    }
                    550: 	    if ($exclude) {
                    551: 	        delete($classlist->{$student});
                    552: 	    }
                    553: 	}
1.205     matthew   554: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  555: 	if (&canview($section)) {
1.291     albertel  556: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  557: 		$sections{$section}++;
1.450     banghart  558: 		if ($classlist->{$student}) {
                    559: 		    $fullnames{$student}=$fullname;
                    560: 		}
1.103     albertel  561: 	    } else {
1.205     matthew   562: 		delete($classlist->{$student});
1.103     albertel  563: 	    }
                    564: 	} else {
1.205     matthew   565: 	    delete($classlist->{$student});
1.103     albertel  566: 	}
1.44      ng        567:     }
                    568:     my %seen = ();
1.56      matthew   569:     my @sections = sort(keys(%sections));
                    570:     return ($classlist,\@sections,\%fullnames);
1.44      ng        571: }
                    572: 
1.103     albertel  573: sub canmodify {
                    574:     my ($sec)=@_;
                    575:     if ($perm{'mgr'}) {
                    576: 	if (!defined($perm{'mgr_section'})) {
                    577: 	    # can modify whole class
                    578: 	    return 1;
                    579: 	} else {
                    580: 	    if ($sec eq $perm{'mgr_section'}) {
                    581: 		#can modify the requested section
                    582: 		return 1;
                    583: 	    } else {
                    584: 		# can't modify the request section
                    585: 		return 0;
                    586: 	    }
                    587: 	}
                    588:     }
                    589:     #can't modify
                    590:     return 0;
                    591: }
                    592: 
                    593: sub canview {
                    594:     my ($sec)=@_;
                    595:     if ($perm{'vgr'}) {
                    596: 	if (!defined($perm{'vgr_section'})) {
                    597: 	    # can modify whole class
                    598: 	    return 1;
                    599: 	} else {
                    600: 	    if ($sec eq $perm{'vgr_section'}) {
                    601: 		#can modify the requested section
                    602: 		return 1;
                    603: 	    } else {
                    604: 		# can't modify the request section
                    605: 		return 0;
                    606: 	    }
                    607: 	}
                    608:     }
                    609:     #can't modify
                    610:     return 0;
                    611: }
                    612: 
1.44      ng        613: #--- Retrieve the grade status of a student for all the parts
                    614: sub student_gradeStatus {
1.324     albertel  615:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  616:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        617:     my %partstatus = ();
                    618:     foreach (@$partlist) {
1.128     ng        619: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        620: 	$status              = 'nothing' if ($status eq '');
                    621: 	$partstatus{$_}      = $status;
                    622: 	my $subkey           = "resource.$_.submitted_by";
                    623: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    624:     }
                    625:     return %partstatus;
                    626: }
                    627: 
1.45      ng        628: # hidden form and javascript that calls the form
                    629: # Use by verifyscript and viewgrades
                    630: # Shows a student's view of problem and submission
                    631: sub jscriptNform {
1.324     albertel  632:     my ($symb) = @_;
1.442     banghart  633:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  634:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        635: 	'    function viewOneStudent(user,domain) {'."\n".
                    636: 	'	document.onestudent.student.value = user;'."\n".
                    637: 	'	document.onestudent.userdom.value = domain;'."\n".
                    638: 	'	document.onestudent.submit();'."\n".
                    639: 	'    }'."\n".
1.597     wenzelju  640: 	"\n");
1.45      ng        641:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  642: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  643: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        644: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    645: 	'<input type="hidden" name="student" value="" />'."\n".
                    646: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    647: 	'</form>'."\n";
                    648:     return $jscript;
                    649: }
1.39      ng        650: 
1.447     foxr      651: 
                    652: 
1.315     bowersj2  653: # Given the score (as a number [0-1] and the weight) what is the final
                    654: # point value? This function will round to the nearest tenth, third,
                    655: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  656: sub compute_points {
1.315     bowersj2  657:     my ($score, $weight) = @_;
                    658:     
                    659:     my $tolerance = .00001;
                    660:     my $points = $score * $weight;
                    661: 
                    662:     # Check for nearness to 1/x.
                    663:     my $check_for_nearness = sub {
                    664:         my ($factor) = @_;
                    665:         my $num = ($points * $factor) + $tolerance;
                    666:         my $floored_num = floor($num);
1.316     albertel  667:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  668:             return $floored_num / $factor;
                    669:         }
                    670:         return $points;
                    671:     };
                    672: 
                    673:     $points = $check_for_nearness->(10);
                    674:     $points = $check_for_nearness->(3);
                    675:     $points = $check_for_nearness->(4);
                    676:     
                    677:     return $points;
                    678: }
                    679: 
1.44      ng        680: #------------------ End of general use routines --------------------
1.87      www       681: 
                    682: #
                    683: # Find most similar essay
                    684: #
                    685: 
                    686: sub most_similar {
1.674     raeburn   687:     my ($uname,$udom,$symb,$uessay)=@_;
                    688: 
                    689:     unless ($symb) { return ''; }
                    690: 
                    691:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       692: 
                    693: # ignore spaces and punctuation
                    694: 
                    695:     $uessay=~s/\W+/ /gs;
                    696: 
1.282     www       697: # ignore empty submissions (occuring when only files are sent)
                    698: 
1.598     www       699:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       700: 
1.87      www       701: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       702:     my $limit=0.6;
1.87      www       703:     my $sname='';
                    704:     my $sdom='';
                    705:     my $scrsid='';
                    706:     my $sessay='';
                    707: # go through all essays ...
1.674     raeburn   708:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  709: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       710: # ... except the same student
1.426     albertel  711:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   712: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  713: 	$tessay=~s/\W+/ /gs;
1.87      www       714: # String similarity gives up if not even limit
1.426     albertel  715: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       716: # Found one
1.426     albertel  717: 	if ($tsimilar>$limit) {
                    718: 	    $limit=$tsimilar;
                    719: 	    $sname=$tname;
                    720: 	    $sdom=$tdom;
                    721: 	    $scrsid=$tcrsid;
1.674     raeburn   722: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  723: 	}
1.87      www       724:     }
1.88      www       725:     if ($limit>0.6) {
1.87      www       726:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    727:     } else {
                    728:        return ('','','','',0);
                    729:     }
                    730: }
                    731: 
1.44      ng        732: #-------------------------------------------------------------------
                    733: 
                    734: #------------------------------------ Receipt Verification Routines
1.45      ng        735: #
1.602     www       736: 
                    737: sub initialverifyreceipt {
1.608     www       738:    my ($request,$symb) = @_;
1.602     www       739:    &commonJSfunctions($request);
1.694     bisitz    740:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       741:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    742:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       743:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    744:         '<input type="hidden" name="command" value="verify" />'.
                    745:         "</form>\n";
1.602     www       746: }
                    747: 
1.44      ng        748: #--- Check whether a receipt number is valid.---
                    749: sub verifyreceipt {
1.608     www       750:     my ($request,$symb)  = @_;
1.44      ng        751: 
1.257     albertel  752:     my $courseid = $env{'request.course.id'};
1.184     www       753:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  754: 	$env{'form.receipt'};
1.44      ng        755:     $receipt     =~ s/[^\-\d]//g;
                    756: 
1.487     albertel  757:     my $title.=
                    758: 	'<h3><span class="LC_info">'.
1.605     www       759: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    760: 	'</span></h3>'."\n";
1.44      ng        761: 
                    762:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   763:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  764:     
                    765:     my $receiptparts=0;
1.390     albertel  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  768:     my $parts=['0'];
1.582     raeburn   769:     if ($receiptparts) {
                    770:         my $res_error; 
                    771:         ($parts)=&response_type($symb,\$res_error);
                    772:         if ($res_error) {
                    773:             return &navmap_errormsg();
                    774:         } 
                    775:     }
1.486     albertel  776:     
                    777:     my $header = 
                    778: 	&Apache::loncommon::start_data_table().
                    779: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  780: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    781: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    782: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  783:     if ($receiptparts) {
1.487     albertel  784: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  785:     }
                    786:     $header.=
                    787: 	&Apache::loncommon::end_data_table_header_row();
                    788: 
1.294     albertel  789:     foreach (sort 
                    790: 	     {
                    791: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    792: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    793: 		 }
                    794: 		 return $a cmp $b;
                    795: 	     } (keys(%$fullname))) {
1.44      ng        796: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  797: 	foreach my $part (@$parts) {
                    798: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  799: 		$contents.=
                    800: 		    &Apache::loncommon::start_data_table_row().
                    801: 		    '<td>&nbsp;'."\n".
1.177     albertel  802: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  803: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  804: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    805: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    806: 		if ($receiptparts) {
                    807: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    808: 		}
1.486     albertel  809: 		$contents.= 
                    810: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  811: 		
                    812: 		$matches++;
                    813: 	    }
1.44      ng        814: 	}
                    815:     }
                    816:     if ($matches == 0) {
1.584     bisitz    817:         $string = $title
                    818:                  .'<p class="LC_warning">'
                    819:                  .&mt('No match found for the above receipt number.')
                    820:                  .'</p>';
1.44      ng        821:     } else {
1.324     albertel  822: 	$string = &jscriptNform($symb).$title.
1.487     albertel  823: 	    '<p>'.
1.584     bisitz    824: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  825: 	    '</p>'.
1.486     albertel  826: 	    $header.
                    827: 	    $contents.
                    828: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        829:     }
1.614     www       830:     return $string;
1.44      ng        831: }
                    832: 
                    833: #--- This is called by a number of programs.
                    834: #--- Called from the Grading Menu - View/Grade an individual student
                    835: #--- Also called directly when one clicks on the subm button 
                    836: #    on the problem page.
1.30      ng        837: sub listStudents {
1.617     www       838:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  839: 
1.257     albertel  840:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    841:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    842:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  843:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       844:     unless ($submitonly) {
                    845:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    846:     }
1.49      albertel  847: 
1.632     www       848:     my $result='';
1.623     www       849:     my $res_error;
                    850:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  851: 
1.559     raeburn   852:     my %lt = &Apache::lonlocal::texthash (
                    853: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    854: 		'single'   => 'Please select the student before clicking on the Next button.',
                    855: 	     );
1.597     wenzelju  856:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        857:     function checkSelect(checkBox) {
                    858: 	var ctr=0;
                    859: 	var sense="";
                    860: 	if (checkBox.length > 1) {
                    861: 	    for (var i=0; i<checkBox.length; i++) {
                    862: 		if (checkBox[i].checked) {
                    863: 		    ctr++;
                    864: 		}
                    865: 	    }
1.485     albertel  866: 	    sense = '$lt{'multiple'}';
1.110     ng        867: 	} else {
                    868: 	    if (checkBox.checked) {
                    869: 		ctr = 1;
                    870: 	    }
1.485     albertel  871: 	    sense = '$lt{'single'}';
1.110     ng        872: 	}
                    873: 	if (ctr == 0) {
1.485     albertel  874: 	    alert(sense);
1.110     ng        875: 	    return false;
                    876: 	}
                    877: 	document.gradesub.submit();
                    878:     }
                    879: 
                    880:     function reLoadList(formname) {
1.112     ng        881: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        882: 	formname.command.value = 'submission';
                    883: 	formname.submit();
                    884:     }
1.45      ng        885: LISTJAVASCRIPT
                    886: 
1.118     ng        887:     &commonJSfunctions($request);
1.41      ng        888:     $request->print($result);
1.39      ng        889: 
1.154     albertel  890:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       891: 	"\n";
1.485     albertel  892: 	
1.561     bisitz    893:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    894:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    895:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    897:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    898:                   .&Apache::lonhtmlcommon::row_closure();
                    899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    900:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    903:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  904: 
                    905:     my $submission_options;
1.442     banghart  906:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    907:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  908:     $env{'form.Status'} = $saveStatus;
1.485     albertel  909:     $submission_options.=
1.592     bisitz    910:         '<span class="LC_nobreak">'.
1.624     www       911:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     912:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    913:         '<span class="LC_nobreak">'.
                    914:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     915:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    916:         '<span class="LC_nobreak">'.
1.628     www       917:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     918:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    919:         '<span class="LC_nobreak">'.
                    920:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     921:         &mt('all submissions with details').'</label></span>';
                    922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    923:                   .$submission_options
                    924:                   .&Apache::lonhtmlcommon::row_closure();
                    925: 
                    926:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    927:                   .'<select name="increment">'
                    928:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    929:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    930:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    931:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    932:                   .'</select>'
                    933:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  934: 
                    935:     $gradeTable .= 
1.432     banghart  936:         &build_section_inputs().
1.45      ng        937: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  938: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        939: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    940: 
1.618     www       941:     if (exists($env{'form.Status'})) {
1.561     bisitz    942: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        943:     } else {
1.561     bisitz    944:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    945:                       .&Apache::lonhtmlcommon::StatusOptions(
                    946:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    947:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        948:     }
1.112     ng        949: 
1.561     bisitz    950:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    951:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    952:                   .&Apache::lonhtmlcommon::row_closure(1)
                    953:                   .&Apache::lonhtmlcommon::end_pick_box();
                    954: 
                    955:     $gradeTable .= '<p>'
1.618     www       956:                   .&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    957:                   .'<input type="hidden" name="command" value="processGroup" />'
                    958:                   .'</p>';
1.249     albertel  959: 
                    960: # checkall buttons
                    961:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        962:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    963:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    964:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  965:     $gradeTable.=&check_buttons();
1.450     banghart  966:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  967:     $gradeTable.= &Apache::loncommon::start_data_table().
                    968: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        969:     my $loop = 0;
                    970:     while ($loop < 2) {
1.485     albertel  971: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    972: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       973: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  974: 	    foreach my $part (sort(@$partlist)) {
                    975: 		my $display_part=
                    976: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    977: 		$gradeTable.=
                    978: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        979: 	    }
1.301     albertel  980: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  981: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        982: 	}
                    983: 	$loop++;
1.126     ng        984: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        985:     }
1.474     albertel  986:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        987: 
1.45      ng        988:     my $ctr = 0;
1.294     albertel  989:     foreach my $student (sort 
                    990: 			 {
                    991: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    992: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    993: 			     }
                    994: 			     return $a cmp $b;
                    995: 			 }
                    996: 			 (keys(%$fullname))) {
1.41      ng        997: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  998: 
1.110     ng        999: 	my %status = ();
1.301     albertel 1000: 
                   1001: 	if ($submitonly eq 'queued') {
                   1002: 	    my %queue_status = 
                   1003: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1004: 							$udom,$uname);
                   1005: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1006: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1007: 	}
                   1008: 
1.618     www      1009: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1010: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1011: 	    my $submitted = 0;
1.164     albertel 1012: 	    my $graded = 0;
1.248     albertel 1013: 	    my $incorrect = 0;
1.110     ng       1014: 	    foreach (keys(%status)) {
1.145     albertel 1015: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1016: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1017: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1018: 		
1.110     ng       1019: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1020: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1021: 		    $submitted = 0;
1.150     albertel 1022: 		    my ($part)=split(/\./,$partid);
1.110     ng       1023: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1024: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1025: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1026: 		}
1.41      ng       1027: 	    }
1.248     albertel 1028: 	    
1.156     albertel 1029: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1030: 				     $submitonly eq 'incorrect' ||
                   1031: 				     $submitonly eq 'graded'));
1.248     albertel 1032: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1033: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1034: 	}
1.34      ng       1035: 
1.45      ng       1036: 	$ctr++;
1.249     albertel 1037: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1038:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1039: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1040: 	    if ($ctr%2 ==1) {
                   1041: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1042: 	    }
1.126     ng       1043: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1044:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1045:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1046: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1047: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1048: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1049: 
1.618     www      1050: 	    if ($submitonly ne 'all') {
1.524     raeburn  1051: 		foreach (sort(keys(%status))) {
1.485     albertel 1052: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1053: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1054: 		}
1.41      ng       1055: 	    }
1.126     ng       1056: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1057: 	    if ($ctr%2 ==0) {
                   1058: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1059: 	    }
1.41      ng       1060: 	}
                   1061:     }
1.110     ng       1062:     if ($ctr%2 ==1) {
1.126     ng       1063: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1064: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1065: 		foreach (@$partlist) {
                   1066: 		    $gradeTable.='<td>&nbsp;</td>';
                   1067: 		}
1.301     albertel 1068: 	    } elsif ($submitonly eq 'queued') {
                   1069: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1070: 	    }
1.474     albertel 1071: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1072:     }
                   1073: 
1.474     albertel 1074:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1075:         '<input type="button" '.
                   1076:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1077:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1078:     if ($ctr == 0) {
1.96      albertel 1079: 	my $num_students=(scalar(keys(%$fullname)));
                   1080: 	if ($num_students eq 0) {
1.485     albertel 1081: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1082: 	} else {
1.171     albertel 1083: 	    my $submissions='submissions';
                   1084: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1085: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1086: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1087: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1088: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1089: 		    $num_students).
                   1090: 		'</span><br />';
1.96      albertel 1091: 	}
1.46      ng       1092:     } elsif ($ctr == 1) {
1.474     albertel 1093: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1094:     }
                   1095:     $request->print($gradeTable);
1.44      ng       1096:     return '';
1.10      ng       1097: }
                   1098: 
1.44      ng       1099: #---- Called from the listStudents routine
1.249     albertel 1100: 
                   1101: sub check_script {
                   1102:     my ($form, $type)=@_;
1.597     wenzelju 1103:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1104:     function checkall() {
                   1105:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1106:             ele = document.forms.'.$form.'.elements[i];
                   1107:             if (ele.name == "'.$type.'") {
                   1108:             document.forms.'.$form.'.elements[i].checked=true;
                   1109:                                        }
                   1110:         }
                   1111:     }
                   1112: 
                   1113:     function checksec() {
                   1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1115:             ele = document.forms.'.$form.'.elements[i];
                   1116:            string = document.forms.'.$form.'.chksec.value;
                   1117:            if
                   1118:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1119:               document.forms.'.$form.'.elements[i].checked=true;
                   1120:             }
                   1121:         }
                   1122:     }
                   1123: 
                   1124: 
                   1125:     function uncheckall() {
                   1126:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1127:             ele = document.forms.'.$form.'.elements[i];
                   1128:             if (ele.name == "'.$type.'") {
                   1129:             document.forms.'.$form.'.elements[i].checked=false;
                   1130:                                        }
                   1131:         }
                   1132:     }
                   1133: 
1.597     wenzelju 1134: '."\n");
1.249     albertel 1135:     return $chkallscript;
                   1136: }
                   1137: 
                   1138: sub check_buttons {
1.485     albertel 1139:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1140:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1141:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1142:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1143:     return $buttons;
                   1144: }
                   1145: 
1.44      ng       1146: #     Displays the submissions for one student or a group of students
1.34      ng       1147: sub processGroup {
1.619     www      1148:     my ($request,$symb)  = @_;
1.41      ng       1149:     my $ctr        = 0;
1.155     albertel 1150:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1151:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1152: 
1.396     banghart 1153:     foreach my $student (@stuchecked) {
                   1154: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1155: 	$env{'form.student'}        = $uname;
                   1156: 	$env{'form.userdom'}        = $udom;
                   1157: 	$env{'form.fullname'}       = $fullname;
1.619     www      1158: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1159: 	$ctr++;
                   1160:     }
                   1161:     return '';
1.35      ng       1162: }
1.34      ng       1163: 
1.44      ng       1164: #------------------------------------------------------------------------------------
                   1165: #
                   1166: #-------------------------- Next few routines handles grading by student, essentially
                   1167: #                           handles essay response type problem/part
                   1168: #
                   1169: #--- Javascript to handle the submission page functionality ---
                   1170: sub sub_page_js {
                   1171:     my $request = shift;
1.539     riegler  1172: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1173:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1174:     function updateRadio(formname,id,weight) {
1.125     ng       1175: 	var gradeBox = formname["GD_BOX"+id];
                   1176: 	var radioButton = formname["RADVAL"+id];
                   1177: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1178: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1179: 	gradeBox.value = pts;
                   1180: 	var resetbox = false;
                   1181: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1182: 	    alert("$alertmsg"+pts);
1.71      ng       1183: 	    for (var i=0; i<radioButton.length; i++) {
                   1184: 		if (radioButton[i].checked) {
                   1185: 		    gradeBox.value = i;
                   1186: 		    resetbox = true;
                   1187: 		}
                   1188: 	    }
                   1189: 	    if (!resetbox) {
                   1190: 		formtextbox.value = "";
                   1191: 	    }
                   1192: 	    return;
1.44      ng       1193: 	}
1.71      ng       1194: 
                   1195: 	if (pts > weight) {
                   1196: 	    var resp = confirm("You entered a value ("+pts+
                   1197: 			       ") greater than the weight for the part. Accept?");
                   1198: 	    if (resp == false) {
1.125     ng       1199: 		gradeBox.value = oldpts;
1.71      ng       1200: 		return;
                   1201: 	    }
1.44      ng       1202: 	}
1.13      albertel 1203: 
1.71      ng       1204: 	for (var i=0; i<radioButton.length; i++) {
                   1205: 	    radioButton[i].checked=false;
                   1206: 	    if (pts == i && pts != "") {
                   1207: 		radioButton[i].checked=true;
                   1208: 	    }
                   1209: 	}
                   1210: 	updateSelect(formname,id);
1.125     ng       1211: 	formname["stores"+id].value = "0";
1.41      ng       1212:     }
1.5       albertel 1213: 
1.72      ng       1214:     function writeBox(formname,id,pts) {
1.125     ng       1215: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1216: 	if (checkSolved(formname,id) == 'update') {
                   1217: 	    gradeBox.value = pts;
                   1218: 	} else {
1.125     ng       1219: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1220: 	    gradeBox.value = oldpts;
1.125     ng       1221: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1222: 	    for (var i=0; i<radioButton.length; i++) {
                   1223: 		radioButton[i].checked=false;
1.72      ng       1224: 		if (i == oldpts) {
1.71      ng       1225: 		    radioButton[i].checked=true;
                   1226: 		}
                   1227: 	    }
1.41      ng       1228: 	}
1.125     ng       1229: 	formname["stores"+id].value = "0";
1.71      ng       1230: 	updateSelect(formname,id);
                   1231: 	return;
1.41      ng       1232:     }
1.44      ng       1233: 
1.71      ng       1234:     function clearRadBox(formname,id) {
                   1235: 	if (checkSolved(formname,id) == 'noupdate') {
                   1236: 	    updateSelect(formname,id);
                   1237: 	    return;
                   1238: 	}
1.125     ng       1239: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1240: 	for (var i=0; i<gradeSelect.length; i++) {
                   1241: 	    if (gradeSelect[i].selected) {
                   1242: 		var selectx=i;
                   1243: 	    }
                   1244: 	}
1.125     ng       1245: 	var stores = formname["stores"+id];
1.71      ng       1246: 	if (selectx == stores.value) { return };
1.125     ng       1247: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1248: 	gradeBox.value = "";
1.125     ng       1249: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1250: 	for (var i=0; i<radioButton.length; i++) {
                   1251: 	    radioButton[i].checked=false;
                   1252: 	}
                   1253: 	stores.value = selectx;
                   1254:     }
1.5       albertel 1255: 
1.71      ng       1256:     function checkSolved(formname,id) {
1.125     ng       1257: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1258: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1259: 	    if (!reply) {return "noupdate";}
1.120     ng       1260: 	    formname.overRideScore.value = 'yes';
1.41      ng       1261: 	}
1.71      ng       1262: 	return "update";
1.13      albertel 1263:     }
1.71      ng       1264: 
                   1265:     function updateSelect(formname,id) {
1.125     ng       1266: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1267: 	return;
1.41      ng       1268:     }
1.33      ng       1269: 
1.121     ng       1270: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1271:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1272: 	formname.gradeOpt.value = val;
1.71      ng       1273: 	if (val == "Save & Next") {
                   1274: 	    for (i=0;i<=total;i++) {
                   1275: 		for (j=0;j<parttot;j++) {
1.125     ng       1276: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1277: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1278: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1279: 			if (points == "") {
1.125     ng       1280: 			    var name = formname["name"+i].value;
1.129     ng       1281: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1282: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1283: 					       ", part "+partid+". Continue?");
1.71      ng       1284: 			    if (resp == false) {
1.125     ng       1285: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1286: 				return false;
                   1287: 			    }
                   1288: 			}
                   1289: 		    }
                   1290: 		    
                   1291: 		}
                   1292: 	    }
                   1293: 	    
                   1294: 	}
1.120     ng       1295: 	formname.submit();
                   1296:     }
                   1297: 
1.71      ng       1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1299:     function checkSubmitPage(formname,total) {
                   1300: 	noscore = new Array(100);
                   1301: 	var ptr = 0;
                   1302: 	for (i=1;i<total;i++) {
1.125     ng       1303: 	    var partid = formname["q_"+i].value;
1.127     ng       1304: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1305: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1306: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1307: 		if (points == "" && status != "correct_by_student") {
                   1308: 		    noscore[ptr] = i;
                   1309: 		    ptr++;
                   1310: 		}
                   1311: 	    }
                   1312: 	}
                   1313: 	if (ptr != 0) {
                   1314: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1315: 	    var prolist = "";
                   1316: 	    if (ptr == 1) {
                   1317: 		prolist = noscore[0];
                   1318: 	    } else {
                   1319: 		var i = 0;
                   1320: 		while (i < ptr-1) {
                   1321: 		    prolist += noscore[i]+", ";
                   1322: 		    i++;
                   1323: 		}
                   1324: 		prolist += "and "+noscore[i];
                   1325: 	    }
                   1326: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1327: 	    if (resp == false) {
                   1328: 		return false;
                   1329: 	    }
                   1330: 	}
1.45      ng       1331: 
1.71      ng       1332: 	formname.submit();
                   1333:     }
                   1334: SUBJAVASCRIPT
                   1335: }
1.45      ng       1336: 
1.71      ng       1337: #--- javascript for essay type problem --
                   1338: sub sub_page_kw_js {
                   1339:     my $request = shift;
1.80      ng       1340:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1341:     &commonJSfunctions($request);
1.350     albertel 1342: 
1.629     www      1343:     my $inner_js_msg_central= (<<INNERJS);
                   1344: <script type="text/javascript">
1.350     albertel 1345:     function checkInput() {
                   1346:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1347:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1348:       var usrctr = document.msgcenter.usrctr.value;
                   1349:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1350:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1351: 
                   1352:       var msgchk = "";
                   1353:       if (document.msgcenter.subchk.checked) {
                   1354:          msgchk = "msgsub,";
                   1355:       }
                   1356:       var includemsg = 0;
                   1357:       for (var i=1; i<=nmsg; i++) {
                   1358:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1359:           var frmmsg = document.msgcenter["msg"+i];
                   1360:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1361:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1362:           showflg.value = "1";
                   1363:           var chkbox = document.msgcenter["msgn"+i];
                   1364:           if (chkbox.checked) {
                   1365:              msgchk += "savemsg"+i+",";
                   1366:              includemsg = 1;
                   1367:           }
                   1368:       }
                   1369:       if (document.msgcenter.newmsgchk.checked) {
                   1370:          msgchk += "newmsg"+usrctr;
                   1371:          includemsg = 1;
                   1372:       }
                   1373:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1374:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1375:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1376:       includemsg.value = msgchk;
                   1377: 
                   1378:       self.close()
                   1379: 
                   1380:     }
1.629     www      1381: </script>
1.350     albertel 1382: INNERJS
                   1383: 
1.629     www      1384:     my $inner_js_highlight_central= (<<INNERJS);
                   1385: <script type="text/javascript">
1.351     albertel 1386:     function updateChoice(flag) {
                   1387:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1388:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1389:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1390:       opener.document.SCORE.refresh.value = "on";
                   1391:       if (opener.document.SCORE.keywords.value!=""){
                   1392:          opener.document.SCORE.submit();
                   1393:       }
                   1394:       self.close()
                   1395:     }
1.629     www      1396: </script>
1.351     albertel 1397: INNERJS
                   1398: 
                   1399:     my $start_page_msg_central = 
                   1400:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1401: 				       {'js_ready'  => 1,
                   1402: 					'only_body' => 1,
                   1403: 					'bgcolor'   =>'#FFFFFF',});
                   1404:     my $end_page_msg_central = 
                   1405: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1406: 
                   1407: 
                   1408:     my $start_page_highlight_central = 
                   1409:         &Apache::loncommon::start_page('Highlight Central',
                   1410: 				       $inner_js_highlight_central,
1.350     albertel 1411: 				       {'js_ready'  => 1,
                   1412: 					'only_body' => 1,
                   1413: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1414:     my $end_page_highlight_central = 
1.350     albertel 1415: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1416: 
1.219     www      1417:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1418:     $docopen=~s/^document\.//;
1.652     raeburn  1419:     my %lt = &Apache::lonlocal::texthash(
                   1420:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1421:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1422:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1423:                 comp => 'Compose Message for: ',
                   1424:                 incl => 'Include',
1.656     raeburn  1425:                 type => 'Type',
1.652     raeburn  1426:                 subj => 'Subject',
                   1427:                 mesa => 'Message',
                   1428:                 new  => 'New',
                   1429:                 save => 'Save',
                   1430:                 canc => 'Cancel',
                   1431:                 kehi => 'Keyword Highlight Options',
                   1432:                 txtc => 'Text Color',
                   1433:                 font => 'Font Size',
1.656     raeburn  1434:                 fnst => 'Font Style',
1.718   ! bisitz   1435:                 col1 => 'red',
        !          1436:                 col2 => 'green',
        !          1437:                 col3 => 'blue',
        !          1438:                 siz1 => 'normal',
        !          1439:                 siz2 => '+1',
        !          1440:                 siz3 => '+2',
        !          1441:                 sty1 => 'normal',
        !          1442:                 sty2 => 'italic',
        !          1443:                 sty3 => 'bold',
1.652     raeburn  1444:              );
1.597     wenzelju 1445:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1446: 
1.44      ng       1447: //===================== Show list of keywords ====================
1.122     ng       1448:   function keywords(formname) {
1.652     raeburn  1449:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1450:     if (nret==null) return;
1.122     ng       1451:     formname.keywords.value = nret;
1.44      ng       1452: 
1.122     ng       1453:     if (formname.keywords.value != "") {
1.128     ng       1454: 	formname.refresh.value = "on";
1.122     ng       1455: 	formname.submit();
1.44      ng       1456:     }
                   1457:     return;
                   1458:   }
                   1459: 
                   1460: //===================== Script to view submitted by ==================
                   1461:   function viewSubmitter(submitter) {
                   1462:     document.SCORE.refresh.value = "on";
                   1463:     document.SCORE.NCT.value = "1";
                   1464:     document.SCORE.unamedom0.value = submitter;
                   1465:     document.SCORE.submit();
                   1466:     return;
                   1467:   }
                   1468: 
                   1469: //===================== Script to add keyword(s) ==================
                   1470:   function getSel() {
                   1471:     if (document.getSelection) txt = document.getSelection();
                   1472:     else if (document.selection) txt = document.selection.createRange().text;
                   1473:     else return;
                   1474:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1475:     if (cleantxt=="") {
1.652     raeburn  1476: 	alert("$lt{'plse'}");
1.44      ng       1477: 	return;
                   1478:     }
1.652     raeburn  1479:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1480:     if (nret==null) return;
1.127     ng       1481:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1482:     if (document.SCORE.keywords.value != "") {
1.127     ng       1483: 	document.SCORE.refresh.value = "on";
1.44      ng       1484: 	document.SCORE.submit();
                   1485:     }
                   1486:     return;
                   1487:   }
                   1488: 
                   1489: //====================== Script for composing message ==============
1.80      ng       1490:    // preload images
                   1491:    img1 = new Image();
                   1492:    img1.src = "$iconpath/mailbkgrd.gif";
                   1493:    img2 = new Image();
                   1494:    img2.src = "$iconpath/mailto.gif";
                   1495: 
1.44      ng       1496:   function msgCenter(msgform,usrctr,fullname) {
                   1497:     var Nmsg  = msgform.savemsgN.value;
                   1498:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1499:     var subject = msgform.msgsub.value;
1.127     ng       1500:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1501:     re = /msgsub/;
                   1502:     var shwsel = "";
                   1503:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1504:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1505:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1506:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1507: 	var testmsg = "savemsg"+i+",";
                   1508: 	re = new RegExp(testmsg,"g");
1.44      ng       1509: 	shwsel = "";
                   1510: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1511: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1512: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1513: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1514: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1515:     }
1.125     ng       1516:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1517:     shwsel = "";
                   1518:     re = /newmsg/;
                   1519:     if (re.test(msgchk)) { shwsel = "checked" }
                   1520:     newMsg(newmsg,shwsel);
                   1521:     msgTail(); 
                   1522:     return;
                   1523:   }
                   1524: 
1.123     ng       1525:   function checkEntities(strx) {
                   1526:     if (strx.length == 0) return strx;
                   1527:     var orgStr = ["&", "<", ">", '"']; 
                   1528:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1529:     var counter = 0;
                   1530:     while (counter < 4) {
                   1531: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1532: 	counter++;
                   1533:     }
                   1534:     return strx;
                   1535:   }
                   1536: 
                   1537:   function strReplace(strx, orgStr, newStr) {
                   1538:     return strx.split(orgStr).join(newStr);
                   1539:   }
                   1540: 
1.44      ng       1541:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1542:     var height = 70*Nmsg+250;
1.44      ng       1543:     if (height > 600) {
                   1544: 	height = 600;
                   1545:     }
1.118     ng       1546:     var xpos = (screen.width-600)/2;
                   1547:     xpos = (xpos < 0) ? '0' : xpos;
                   1548:     var ypos = (screen.height-height)/2-30;
                   1549:     ypos = (ypos < 0) ? '0' : ypos;
                   1550: 
1.668     www      1551:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1552:     pWin.focus();
                   1553:     pDoc = pWin.document;
1.219     www      1554:     pDoc.$docopen;
1.351     albertel 1555:     pDoc.write('$start_page_msg_central');
1.76      ng       1556: 
                   1557:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1558:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1559:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1560: 
1.676     golterma 1561:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1562:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1563: }
                   1564:     function displaySubject(msg,shwsel) {
1.76      ng       1565:     pDoc = pWin.document;
1.676     golterma 1566:     pDoc.write("<tr>");
                   1567:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1568:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1569:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1570: }
                   1571: 
1.72      ng       1572:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1573:     pDoc = pWin.document;
1.676     golterma 1574:     pDoc.write("<tr>");
                   1575:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1576:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1577:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1578: }
                   1579: 
                   1580:   function newMsg(newmsg,shwsel) {
1.76      ng       1581:     pDoc = pWin.document;
1.676     golterma 1582:     pDoc.write("<tr>");
                   1583:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1584:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1585:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1586: }
                   1587: 
                   1588:   function msgTail() {
1.76      ng       1589:     pDoc = pWin.document;
1.676     golterma 1590:     //pDoc.write("<\\/table>");
1.465     albertel 1591:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1592:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1593:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1594:     pDoc.write("<\\/form>");
1.351     albertel 1595:     pDoc.write('$end_page_msg_central');
1.128     ng       1596:     pDoc.close();
1.44      ng       1597: }
                   1598: 
                   1599: //====================== Script for keyword highlight options ==============
                   1600:   function kwhighlight() {
                   1601:     var kwclr    = document.SCORE.kwclr.value;
                   1602:     var kwsize   = document.SCORE.kwsize.value;
                   1603:     var kwstyle  = document.SCORE.kwstyle.value;
                   1604:     var redsel = "";
                   1605:     var grnsel = "";
                   1606:     var blusel = "";
1.718   ! bisitz   1607:     var txtcol1 = "$lt{'col1'}";
        !          1608:     var txtcol2 = "$lt{'col2'}";
        !          1609:     var txtcol3 = "$lt{'col3'}";
        !          1610:     var txtsiz1 = "$lt{'siz1'}";
        !          1611:     var txtsiz2 = "$lt{'siz2'}";
        !          1612:     var txtsiz3 = "$lt{'siz3'}";
        !          1613:     var txtsty1 = "$lt{'sty1'}";
        !          1614:     var txtsty2 = "$lt{'sty2'}";
        !          1615:     var txtsty3 = "$lt{'sty3'}";
        !          1616:     if (kwclr=="red")   {var redsel="checked='checked'"};
        !          1617:     if (kwclr=="green") {var grnsel="checked='checked'"};
        !          1618:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1619:     var sznsel = "";
                   1620:     var sz1sel = "";
                   1621:     var sz2sel = "";
1.718   ! bisitz   1622:     if (kwsize=="0")  {var sznsel="checked='checked'"};
        !          1623:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
        !          1624:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1625:     var synsel = "";
                   1626:     var syisel = "";
                   1627:     var sybsel = "";
1.718   ! bisitz   1628:     if (kwstyle=="")    {var synsel="checked='checked'"};
        !          1629:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
        !          1630:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1631:     highlightCentral();
1.718   ! bisitz   1632:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
        !          1633:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
        !          1634:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1635:     highlightend();
                   1636:     return;
                   1637:   }
                   1638: 
                   1639:   function highlightCentral() {
1.76      ng       1640: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1641:     var xpos = (screen.width-400)/2;
                   1642:     xpos = (xpos < 0) ? '0' : xpos;
                   1643:     var ypos = (screen.height-330)/2-30;
                   1644:     ypos = (ypos < 0) ? '0' : ypos;
                   1645: 
1.206     albertel 1646:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1647:     hwdWin.focus();
                   1648:     var hDoc = hwdWin.document;
1.219     www      1649:     hDoc.$docopen;
1.351     albertel 1650:     hDoc.write('$start_page_highlight_central');
1.76      ng       1651:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.718   ! bisitz   1652:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1653: 
1.718   ! bisitz   1654:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
        !          1655:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1656:   }
                   1657: 
                   1658:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1659:     var hDoc = hwdWin.document;
1.718   ! bisitz   1660:     hDoc.write("<tr>");
1.76      ng       1661:     hDoc.write("<td align=\\"left\\">");
1.718   ! bisitz   1662:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1663:     hDoc.write("<td align=\\"left\\">");
1.718   ! bisitz   1664:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1665:     hDoc.write("<td align=\\"left\\">");
1.718   ! bisitz   1666:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1667:     hDoc.write("<\\/tr>");
1.44      ng       1668:   }
                   1669: 
                   1670:   function highlightend() { 
1.76      ng       1671:     var hDoc = hwdWin.document;
1.718   ! bisitz   1672:     hDoc.write("<\\/table><br \\/>");
        !          1673:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
        !          1674:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1675:     hDoc.write("<\\/form>");
1.351     albertel 1676:     hDoc.write('$end_page_highlight_central');
1.128     ng       1677:     hDoc.close();
1.44      ng       1678:   }
                   1679: 
                   1680: SUBJAVASCRIPT
                   1681: }
                   1682: 
1.349     albertel 1683: sub get_increment {
1.348     bowersj2 1684:     my $increment = $env{'form.increment'};
                   1685:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1686:         $increment != .1) {
                   1687:         $increment = 1;
                   1688:     }
                   1689:     return $increment;
                   1690: }
                   1691: 
1.585     bisitz   1692: sub gradeBox_start {
                   1693:     return (
                   1694:         &Apache::loncommon::start_data_table()
                   1695:        .&Apache::loncommon::start_data_table_header_row()
                   1696:        .'<th>'.&mt('Part').'</th>'
                   1697:        .'<th>'.&mt('Points').'</th>'
                   1698:        .'<th>&nbsp;</th>'
                   1699:        .'<th>'.&mt('Assign Grade').'</th>'
                   1700:        .'<th>'.&mt('Weight').'</th>'
                   1701:        .'<th>'.&mt('Grade Status').'</th>'
                   1702:        .&Apache::loncommon::end_data_table_header_row()
                   1703:     );
                   1704: }
                   1705: 
                   1706: sub gradeBox_end {
                   1707:     return (
                   1708:         &Apache::loncommon::end_data_table()
                   1709:     );
                   1710: }
1.71      ng       1711: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1712: sub gradeBox {
1.322     albertel 1713:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1714:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1715: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1716:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1717:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1718:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1719:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1720:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1721: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1722:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1723:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1724:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1725: 				       [$partid]);
                   1726:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1727:     if ($last_resets{$partid}) {
                   1728:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1729:     }
1.695     bisitz   1730:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1731:     my $ctr = 0;
1.348     bowersj2 1732:     my $thisweight = 0;
1.349     albertel 1733:     my $increment = &get_increment();
1.485     albertel 1734: 
                   1735:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1736:     while ($thisweight<=$wgt) {
1.532     bisitz   1737: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1738:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1739: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1740: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1741: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1742:         $thisweight += $increment;
1.71      ng       1743: 	$ctr++;
                   1744:     }
1.485     albertel 1745:     $radio.='</tr></table>';
                   1746: 
                   1747:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1748: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1749: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1750: 	$wgt.')" /></td>'."\n";
1.485     albertel 1751:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1752: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1753: 	' </td>'."\n";
                   1754:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1755: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1756:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1757: 	$line.='<option></option>'.
                   1758: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1759:     } else {
1.485     albertel 1760: 	$line.='<option selected="selected"></option>'.
                   1761: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1762:     }
1.485     albertel 1763:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1764: 
                   1765: 
                   1766:     $result .= 
1.695     bisitz   1767: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1768:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1769:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1770:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1771: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1772: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1773: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1774:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1775:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1776:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1777:         $aggtries.'" />'."\n";
1.582     raeburn  1778:     my $res_error;
                   1779:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1780:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1781:     if ($res_error) {
                   1782:         return &navmap_errormsg();
                   1783:     }
1.318     banghart 1784:     return $result;
                   1785: }
1.322     albertel 1786: 
                   1787: sub handback_box {
1.623     www      1788:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1789:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1790:     my (@respids);
1.652     raeburn  1791:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1792:     foreach my $part_response_id (@part_response_id) {
                   1793:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1794:         if ($part eq $partid) {
1.375     albertel 1795:             push(@respids,$resp);
1.323     banghart 1796:         }
                   1797:     }
1.318     banghart 1798:     my $result;
1.323     banghart 1799:     foreach my $respid (@respids) {
1.322     albertel 1800: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1801: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1802: 	next if (!@$files);
1.654     raeburn  1803: 	my $file_counter = 0;
1.313     banghart 1804: 	foreach my $file (@$files) {
1.368     banghart 1805: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1806:                 $file_counter++;
1.368     banghart 1807:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1808:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1809:     	        $file_disp = "$name.$ext";
                   1810:     	        $file = $file_path.$file_disp;
                   1811:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1812:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1813:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1814:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1815: 	    }
1.322     albertel 1816: 	}
1.654     raeburn  1817:         if ($file_counter) {
                   1818:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1819:                        '<span class="LC_info">'.
                   1820:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1821:         }
1.313     banghart 1822:     }
1.318     banghart 1823:     return $result;    
1.71      ng       1824: }
1.44      ng       1825: 
1.58      albertel 1826: sub show_problem {
1.382     albertel 1827:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1828:     my $rendered;
1.382     albertel 1829:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1830:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1831:     if ($mode eq 'both' or $mode eq 'text') {
                   1832: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1833: 						       $env{'request.course.id'},
                   1834: 						       undef,\%form);
1.144     albertel 1835:     }
1.58      albertel 1836:     if ($removeform) {
                   1837: 	$rendered=~s|<form(.*?)>||g;
                   1838: 	$rendered=~s|</form>||g;
1.374     albertel 1839: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1840:     }
1.144     albertel 1841:     my $companswer;
                   1842:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1843: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1844: 	$companswer=
                   1845: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1846: 						    $env{'request.course.id'},
                   1847: 						    %form);
1.144     albertel 1848:     }
1.58      albertel 1849:     if ($removeform) {
                   1850: 	$companswer=~s|<form(.*?)>||g;
                   1851: 	$companswer=~s|</form>||g;
1.144     albertel 1852: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1853:     }
1.671     raeburn  1854:     my $renderheading = &mt('View of the problem');
                   1855:     my $answerheading = &mt('Correct answer');
                   1856:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1857:         my $stu_fullname = $env{'form.fullname'};
                   1858:         if ($stu_fullname eq '') {
                   1859:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1860:         }
                   1861:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1862:         if ($forwhom ne '') {
                   1863:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1864:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1865:         }
                   1866:     }
1.468     albertel 1867:     $rendered=
1.588     bisitz   1868:         '<div class="LC_Box">'
1.671     raeburn  1869:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1870:        .$rendered
                   1871:        .'</div>';
1.468     albertel 1872:     $companswer=
1.588     bisitz   1873:         '<div class="LC_Box">'
1.671     raeburn  1874:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1875:        .$companswer
                   1876:        .'</div>';
1.468     albertel 1877:     my $result;
1.144     albertel 1878:     if ($mode eq 'both') {
1.588     bisitz   1879:         $result=$rendered.$companswer;
1.144     albertel 1880:     } elsif ($mode eq 'text') {
1.588     bisitz   1881:         $result=$rendered;
1.144     albertel 1882:     } elsif ($mode eq 'answer') {
1.588     bisitz   1883:         $result=$companswer;
1.144     albertel 1884:     }
1.71      ng       1885:     return $result;
1.58      albertel 1886: }
1.397     albertel 1887: 
1.396     banghart 1888: sub files_exist {
                   1889:     my ($r, $symb) = @_;
                   1890:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1891: 
1.396     banghart 1892:     foreach my $student (@students) {
                   1893:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1894:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1895: 					      $udom,$uname);
1.396     banghart 1896:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1897:         foreach my $submission (@$string) {
                   1898:             my ($partid,$respid) =
                   1899: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1900:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1901: 					   \%record);
                   1902:             return 1 if (@$files);
1.396     banghart 1903:         }
                   1904:     }
1.397     albertel 1905:     return 0;
1.396     banghart 1906: }
1.397     albertel 1907: 
1.394     banghart 1908: sub download_all_link {
                   1909:     my ($r,$symb) = @_;
1.621     www      1910:     unless (&files_exist($r, $symb)) {
                   1911:        $r->print(&mt('There are currently no submitted documents.'));
                   1912:        return;
                   1913:     }
                   1914: 
1.395     albertel 1915:     my $all_students = 
                   1916: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1917: 
                   1918:     my $parts =
                   1919: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1920: 
1.394     banghart 1921:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1922:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1923:                              'cgi.'.$identifier.'.symb' => $symb,
                   1924:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1925:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1926: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1927:     return;
                   1928: }
                   1929: 
                   1930: sub submit_download_link {
                   1931:     my ($request,$symb) = @_;
                   1932:     if (!$symb) { return ''; }
                   1933: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1934:     &download_all_link($request,$symb);
1.394     banghart 1935: }
1.395     albertel 1936: 
1.432     banghart 1937: sub build_section_inputs {
                   1938:     my $section_inputs;
                   1939:     if ($env{'form.section'} eq '') {
                   1940:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1941:     } else {
                   1942:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1943:         foreach my $section (@sections) {
1.432     banghart 1944:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1945:         }
                   1946:     }
                   1947:     return $section_inputs;
                   1948: }
                   1949: 
1.44      ng       1950: # --------------------------- show submissions of a student, option to grade 
                   1951: sub submission {
1.608     www      1952:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1953:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1954:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1955:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1956:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1957: 
1.605     www      1958:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1959:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1960: 
                   1961:     if (!&canview($usec)) {
1.712     bisitz   1962:         $request->print(
                   1963:             '<span class="LC_warning">'.
1.713     bisitz   1964:             &mt('Unable to view requested student.').
1.712     bisitz   1965:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1966:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1967:             '</span>');
1.104     albertel 1968: 	return;
                   1969:     }
                   1970: 
1.257     albertel 1971:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1972:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1973:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1974:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1975:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1976: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1977: 	'/check.gif" height="16" border="0" />';
1.41      ng       1978: 
                   1979:     # header info
                   1980:     if ($counter == 0) {
                   1981: 	&sub_page_js($request);
1.621     www      1982: 	&sub_page_kw_js($request);
1.118     ng       1983: 
1.44      ng       1984: 	# option to display problem, only once else it cause problems 
                   1985:         # with the form later since the problem has a form.
1.257     albertel 1986: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1987: 	    my $mode;
1.257     albertel 1988: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1989: 		$mode='both';
1.257     albertel 1990: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1991: 		$mode='text';
1.257     albertel 1992: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1993: 		$mode='answer';
                   1994: 	    }
1.329     albertel 1995: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1996: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1997: 	}
1.441     www      1998: 
1.704     raeburn  1999: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2000:         # if this subroutine has been called once.
1.41      ng       2001: 	my %keyhash = ();
1.624     www      2002: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2003:         if (1) {
1.41      ng       2004: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2005: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2006: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2007: 
1.257     albertel 2008: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2009: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2010: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2011: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2012: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2013: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2014: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2015: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2016: 	}
1.257     albertel 2017: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2018: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2019: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2020: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2021: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2022: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2023: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2024: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2025: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2026: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2027: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2028: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2029: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2030: 			&build_section_inputs().
1.326     albertel 2031: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2032: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2033: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2034: #	if ($env{'form.handgrade'} eq 'yes') {
                   2035:         if (1) {
1.257     albertel 2036: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2037: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2038: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2039: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2040: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2041: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2042: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2043: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2044: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2045: 	    }
1.123     ng       2046: 	}
1.41      ng       2047: 	
                   2048: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2049: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2050: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2051: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2052: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2053: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2054: 		'" />'."\n".
                   2055: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2056: 	    $cts++;
                   2057: 	}
                   2058: 	$request->print($prnmsg);
1.32      ng       2059: 
1.624     www      2060: #	if ($env{'form.handgrade'} eq 'yes') {
                   2061:         if (1) {
1.652     raeburn  2062: 
                   2063:             my %lt = &Apache::lonlocal::texthash(
1.718   ! bisitz   2064:                           keyh => 'Keyword Highlighting',
1.652     raeburn  2065:                           keyw => 'Keyword Options',
1.655     raeburn  2066:                           list => 'List',
1.652     raeburn  2067:                           past => 'Paste Selection to List',
1.661     www      2068:                           high => 'Highlight Attribute',
1.652     raeburn  2069:                      );    
1.88      www      2070: #
                   2071: # Print out the keyword options line
                   2072: #
1.718   ! bisitz   2073: 	    $request->print(
        !          2074:                 '<div class="LC_columnSection">'
        !          2075:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
        !          2076:                .&Apache::lonhtmlcommon::funclist_from_array(
        !          2077:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
        !          2078:                      '<a href="#" onmousedown="javascript:getSel(); return false"
        !          2079:  class="page">'.$lt{'past'}.'</a>',
        !          2080:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
        !          2081:                     {legend => $lt{'keyw'}})
        !          2082:                .'</fieldset></div>'
        !          2083:             );
        !          2084: 
1.88      www      2085: #
                   2086: # Load the other essays for similarity check
                   2087: #
1.324     albertel 2088:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2089: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2090: 	    $apath=&escape($apath);
1.88      www      2091: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2092:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2093:         }
                   2094:     }
1.44      ng       2095: 
1.441     www      2096: # This is where output for one specific student would start
1.592     bisitz   2097:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2098:     $request->print(
                   2099:         "\n\n"
                   2100:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2101:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2102:        ."\n"
                   2103:     );
1.441     www      2104: 
1.592     bisitz   2105:     # Show additional functions if allowed
                   2106:     if ($perm{'vgr'}) {
                   2107:         $request->print(
                   2108:             &Apache::loncommon::track_student_link(
1.708     bisitz   2109:                 'View recent activity',
1.592     bisitz   2110:                 $uname,$udom,'check')
                   2111:            .' '
                   2112:         );
                   2113:     }
                   2114:     if ($perm{'opa'}) {
                   2115:         $request->print(
                   2116:             &Apache::loncommon::pprmlink(
                   2117:                 &mt('Set/Change parameters'),
                   2118:                 $uname,$udom,$symb,'check'));
                   2119:     }
                   2120: 
                   2121:     # Show Problem
1.257     albertel 2122:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2123: 	my $mode;
1.257     albertel 2124: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2125: 	    $mode='both';
1.257     albertel 2126: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2127: 	    $mode='text';
1.257     albertel 2128: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2129: 	    $mode='answer';
                   2130: 	}
1.329     albertel 2131: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2132: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2133:     }
1.144     albertel 2134: 
1.257     albertel 2135:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2136:     my $res_error;
                   2137:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2138:     if ($res_error) {
                   2139:         $request->print(&navmap_errormsg());
                   2140:         return;
                   2141:     }
1.41      ng       2142: 
1.44      ng       2143:     # Display student info
1.41      ng       2144:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2145: 
                   2146:     my $result='<div class="LC_Box">'
                   2147:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2148:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2149:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2150: #    if ($env{'form.handgrade'} eq 'no') {
                   2151:     if (1) {
1.588     bisitz   2152:         $result.='<p class="LC_info">'
                   2153:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2154:                 ."</p>\n";
1.469     albertel 2155:     }
                   2156: 
1.118     ng       2157:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2158:     my $fullname;
                   2159:     my $col_fullnames = [];
1.624     www      2160: #    if ($env{'form.handgrade'} eq 'yes') {
                   2161:     if (1) {
1.464     albertel 2162: 	(my $sub_result,$fullname,$col_fullnames)=
                   2163: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2164: 				 $counter);
                   2165: 	$result.=$sub_result;
1.41      ng       2166:     }
1.44      ng       2167:     $request->print($result."\n");
1.702     kruse    2168:     
1.44      ng       2169:     # print student answer/submission
1.588     bisitz   2170:     # Options are (1) Handgraded submission only
1.44      ng       2171:     #             (2) Last submission, includes submission that is not handgraded 
                   2172:     #                  (for multi-response type part)
                   2173:     #             (3) Last submission plus the parts info
                   2174:     #             (4) The whole record for this student
1.702     kruse    2175:     
                   2176:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2177: 	
1.702     kruse    2178:     my $lastsubonly;
1.468     albertel 2179: 
1.702     kruse    2180:     if ($$timestamp eq '') {
                   2181:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2182:     } else {
                   2183:         $lastsubonly =
                   2184:             '<div class="LC_grade_submissions_body">'
                   2185:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2186: 
                   2187: 	my %seenparts;
                   2188: 	my @part_response_id = &flatten_responseType($responseType);
                   2189: 	foreach my $part (@part_response_id) {
                   2190: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2191: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2192: 
1.702     kruse    2193: 	    my ($partid,$respid) = @{ $part };
                   2194: 	    my $display_part=&get_display_part($partid,$symb);
                   2195: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2196: 		if (exists($seenparts{$partid})) { next; }
                   2197: 		$seenparts{$partid}=1;
                   2198:                 $request->print(
                   2199:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2200:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2201:                                '<a href="javascript:viewSubmitter(\''.
                   2202:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2203:                                '\');" target="_self">'.
                   2204:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2205:                     '<br />');
                   2206: 		next;
                   2207: 		}
                   2208: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2209: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2210:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2211:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2212:                     ' <span class="LC_internal_info">'.
                   2213:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2214:                     '</span>&nbsp; &nbsp;'.
                   2215: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2216: 		next;
                   2217: 	    }
                   2218: 	    foreach my $submission (@$string) {
                   2219: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2220: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2221: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
                   2222: 		# Similarity check
                   2223:                 my $similar='';
                   2224:                 my ($type,$trial,$rndseed);
                   2225:                 if ($hide eq 'rand') {
                   2226:                     $type = 'randomizetry';
                   2227:                     $trial = $record{"resource.$partid.tries"};
                   2228:                     $rndseed = $record{"resource.$partid.rndseed"};
                   2229:                 }
                   2230: 	        if ($env{'form.checkPlag'}) {
                   2231:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2232: 		        &most_similar($uname,$udom,$symb,$subval);
                   2233: 		    if ($osim) {
                   2234: 			$osim=int($osim*100.0);
                   2235: 			my %old_course_desc = 
                   2236: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2237: 							{'one_time' => 1});
                   2238: 
                   2239:                         if ($hide eq 'anon') {
                   2240:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2241:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2242:                         } else {
                   2243: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2244: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2245: 				    $osim,
                   2246: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2247: 				        $old_course_desc{'description'},
                   2248: 				        $old_course_desc{'num'},
                   2249: 				        $old_course_desc{'domain'}).
                   2250: 				    '</span></h3><blockquote><i>'.
                   2251: 				    &keywords_highlight($oessay).
                   2252: 				    '</i></blockquote><hr />';
1.702     kruse    2253:                         }
                   2254: 	            }
                   2255: 		}
                   2256: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2257:                                      undef,$type,$trial,$rndseed);
                   2258:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2259: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2260: 		    my $display_part=&get_display_part($partid,$symb);
                   2261:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2262:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2263:                         ' <span class="LC_internal_info">'.
                   2264:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2265:                         '</span>&nbsp; &nbsp;';
                   2266: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2267:                         
                   2268: 		    if (@$files) {
                   2269:                         if ($hide eq 'anon') {
                   2270:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2271:                         } else {
                   2272:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2273:                                         .'<br /><span class="LC_warning">';
                   2274:                             if(@$files == 1) {
                   2275:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2276:                             } else {
1.702     kruse    2277:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2278:                             }
                   2279:                             $lastsubonly .= '</span>';                         
                   2280:                             foreach my $file (@$files) {
                   2281:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2282:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2283:                             }
                   2284:                         }
1.702     kruse    2285: 			$lastsubonly.='<br />';
                   2286:                     }
                   2287:                     if ($hide eq 'anon') {
                   2288:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2289:                     } else {
                   2290:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
                   2291: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2292: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2293:                     }
                   2294: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2295: 		    $lastsubonly.='</div>';
1.41      ng       2296: 		}
1.702     kruse    2297:             }
1.151     albertel 2298: 	}
1.702     kruse    2299: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2300:     }
                   2301:     $request->print($lastsubonly);
                   2302:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2303:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2304: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.702     kruse    2305:     } 
                   2306:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2307:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2308: 								 $env{'request.course.id'},
1.44      ng       2309: 								 $last,'.submission',
                   2310: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2311:     }
1.121     ng       2312:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2313: 	.$udom.'" />'."\n");
1.44      ng       2314:     # return if view submission with no grading option
1.618     www      2315:     if (!&canmodify($usec)) {
1.633     www      2316: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2317: 	return;
1.180     albertel 2318:     } else {
1.468     albertel 2319: 	$request->print('</div>'."\n");
1.41      ng       2320:     }
1.33      ng       2321: 
1.121     ng       2322:     # essay grading message center
1.624     www      2323: #    if ($env{'form.handgrade'} eq 'yes') {
                   2324:     if (1) {
1.468     albertel 2325: 	my $result='<div class="LC_grade_message_center">';
                   2326:     
                   2327: 	$result.='<div class="LC_grade_message_center_header">'.
                   2328: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2329: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2330: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2331: 	if (scalar(@$col_fullnames) > 0) {
                   2332: 	    my $lastone = pop(@$col_fullnames);
                   2333: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2334: 	}
                   2335: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2336: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2337: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2338: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2339: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2340: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2341: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2342: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2343: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2344: 	    '<br />&nbsp;('.
1.468     albertel 2345: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2346: 	$result.='</div></div>';
1.121     ng       2347: 	$request->print($result);
1.118     ng       2348:     }
1.41      ng       2349: 
                   2350:     my %seen = ();
                   2351:     my @partlist;
1.129     ng       2352:     my @gradePartRespid;
1.375     albertel 2353:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2354:     $request->print(
1.588     bisitz   2355:         '<div class="LC_Box">'
                   2356:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2357:     );
1.592     bisitz   2358:     $request->print(&gradeBox_start());
1.375     albertel 2359:     foreach my $part_response_id (@part_response_id) {
                   2360:     	my ($partid,$respid) = @{ $part_response_id };
                   2361: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2362: 	next if ($seen{$partid} > 0);
1.41      ng       2363: 	$seen{$partid}++;
1.393     albertel 2364: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2365: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2366: 	push(@partlist,$partid);
                   2367: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2368: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2369:     }
1.585     bisitz   2370:     $request->print(&gradeBox_end()); # </div>
                   2371:     $request->print('</div>');
1.468     albertel 2372: 
                   2373:     $request->print('<div class="LC_grade_info_links">');
                   2374:     $request->print('</div>');
                   2375: 
1.45      ng       2376:     $result='<input type="hidden" name="partlist'.$counter.
                   2377: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2378:     $result.='<input type="hidden" name="gradePartRespid'.
                   2379: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2380:     my $ctr = 0;
                   2381:     while ($ctr < scalar(@partlist)) {
                   2382: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2383: 	    $partlist[$ctr].'" />'."\n";
                   2384: 	$ctr++;
                   2385:     }
1.468     albertel 2386:     $request->print($result.''."\n");
1.41      ng       2387: 
1.441     www      2388: # Done with printing info for one student
                   2389: 
1.468     albertel 2390:     $request->print('</div>');#LC_grade_show_user
1.441     www      2391: 
                   2392: 
1.41      ng       2393:     # print end of form
                   2394:     if ($counter == $total) {
1.592     bisitz   2395:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2396: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2397: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2398: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2399: 	my $ntstu ='<select name="NTSTU">'.
                   2400: 	    '<option>1</option><option>2</option>'.
                   2401: 	    '<option>3</option><option>5</option>'.
                   2402: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2403: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2404: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2405:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2406: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2407: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2408: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2409: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2410:         $endform.='<span class="LC_warning">'.
                   2411:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2412:                   '</span>'."\n" ;
1.349     albertel 2413:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2414:             "' name='increment' />";
1.485     albertel 2415: 	$endform.='</td></tr></table></form>';
1.41      ng       2416: 	$request->print($endform);
                   2417:     }
                   2418:     return '';
1.38      ng       2419: }
                   2420: 
1.464     albertel 2421: sub check_collaborators {
                   2422:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2423:     my ($result,@col_fullnames);
                   2424:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2425:     foreach my $part (keys(%$handgrade)) {
                   2426: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2427: 					'.maxcollaborators',
                   2428: 					$symb,$udom,$uname);
                   2429: 	next if ($ncol <= 0);
                   2430: 	$part =~ s/\_/\./g;
                   2431: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2432: 	my (@good_collaborators, @bad_collaborators);
                   2433: 	foreach my $possible_collaborator
1.630     www      2434: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2435: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2436: 	    next if ($possible_collaborator eq '');
1.631     www      2437: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2438: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2439: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2440: 	    # Doing this grep allows 'fuzzy' specification
                   2441: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2442: 			       keys(%$classlist));
                   2443: 	    if (! scalar(@matches)) {
                   2444: 		push(@bad_collaborators, $possible_collaborator);
                   2445: 	    } else {
                   2446: 		push(@good_collaborators, @matches);
                   2447: 	    }
                   2448: 	}
                   2449: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2450: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2451: 	    foreach my $name (@good_collaborators) {
                   2452: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2453: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2454: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2455: 	    }
1.630     www      2456: 	    $result.='</ol><br />'."\n";
1.466     albertel 2457: 	    my ($part)=split(/\./,$part);
1.464     albertel 2458: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2459: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2460: 		"\n";
                   2461: 	}
                   2462: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2463: 	    $result.='<div class="LC_warning">';
1.464     albertel 2464: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2465: 	    $result .= '</div>';
                   2466: 	}         
                   2467: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2468: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2469: 	    $result .= &mt('This student has submitted too many '.
                   2470: 		'collaborators.  Maximum is [_1].',$ncol);
                   2471: 	    $result .= '</div>';
                   2472: 	}
                   2473:     }
                   2474:     return ($result,$fullname,\@col_fullnames);
                   2475: }
                   2476: 
1.44      ng       2477: #--- Retrieve the last submission for all the parts
1.38      ng       2478: sub get_last_submission {
1.119     ng       2479:     my ($returnhash)=@_;
1.596     raeburn  2480:     my (@string,$timestamp,%lasthidden);
1.119     ng       2481:     if ($$returnhash{'version'}) {
1.46      ng       2482: 	my %lasthash=();
                   2483: 	my ($version);
1.119     ng       2484: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2485: 	    foreach my $key (sort(split(/\:/,
                   2486: 					$$returnhash{$version.':keys'}))) {
                   2487: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2488: 		$timestamp = 
1.545     raeburn  2489: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2490: 	    }
                   2491: 	}
1.640     raeburn  2492:         my (%typeparts,%randombytry);
1.596     raeburn  2493:         my $showsurv = 
                   2494:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2495:         foreach my $key (sort(keys(%lasthash))) {
                   2496:             if ($key =~ /\.type$/) {
                   2497:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2498:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2499:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2500:                     my ($ign,@parts) = split(/\./,$key);
                   2501:                     pop(@parts);
1.641     raeburn  2502:                     my $id = join('.',@parts);
1.640     raeburn  2503:                     if ($lasthash{$key} eq 'randomizetry') {
                   2504:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2505:                     } else {
                   2506:                         unless ($showsurv) {
                   2507:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2508:                         }
1.596     raeburn  2509:                     }
                   2510:                     delete($lasthash{$key});
                   2511:                 }
                   2512:             }
                   2513:         }
                   2514:         my @hidden = keys(%typeparts);
1.640     raeburn  2515:         my @randomize = keys(%randombytry);
1.397     albertel 2516: 	foreach my $key (keys(%lasthash)) {
                   2517: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2518:             my $hide;
                   2519:             if (@hidden) {
                   2520:                 foreach my $id (@hidden) {
                   2521:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2522:                         $hide = 'anon';
1.596     raeburn  2523:                         last;
                   2524:                     }
                   2525:                 }
                   2526:             }
1.640     raeburn  2527:             unless ($hide) {
                   2528:                 if (@randomize) {
                   2529:                     foreach my $id (@hidden) {
                   2530:                         if ($key =~ /^\Q$id\E/) {
                   2531:                             $hide = 'rand';
                   2532:                             last;
                   2533:                         }
                   2534:                     }
                   2535:                 }
                   2536:             }
1.397     albertel 2537: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2538: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.717     bisitz   2539: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
1.716     bisitz   2540: 	    #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
                   2541:             push(@string, join(':', $key, $hide, $draft.(
                   2542:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2543:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2544: 	}
                   2545:     }
1.397     albertel 2546:     if (!@string) {
                   2547: 	$string[0] =
1.539     riegler  2548: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2549:     }
                   2550:     return (\@string,\$timestamp);
1.38      ng       2551: }
1.35      ng       2552: 
1.44      ng       2553: #--- High light keywords, with style choosen by user.
1.38      ng       2554: sub keywords_highlight {
1.44      ng       2555:     my $string    = shift;
1.257     albertel 2556:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2557:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2558:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2559:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2560:     foreach my $keyword (@keylist) {
                   2561: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2562:     }
                   2563:     return $string;
1.38      ng       2564: }
1.36      ng       2565: 
1.671     raeburn  2566: # For Tasks provide a mechanism to display previous version for one specific student
                   2567: 
                   2568: sub show_previous_task_version {
                   2569:     my ($request,$symb) = @_;
                   2570:     if ($symb eq '') {
1.717     bisitz   2571:         $request->print(
                   2572:             '<span class="LC_error">'.
                   2573:             &mt('Unable to handle ambiguous references.').
                   2574:             '</span>');
1.671     raeburn  2575:         return '';
                   2576:     }
                   2577:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2578:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2579:     if (!&canview($usec)) {
1.712     bisitz   2580:         $request->print(
                   2581:             '<span class="LC_warning">'.
1.713     bisitz   2582:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2583:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2584:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2585:             '</span>');
1.671     raeburn  2586:         return;
                   2587:     }
                   2588:     my $mode = 'both';
                   2589:     my $isTask = ($symb =~/\.task$/);
                   2590:     if ($isTask) {
                   2591:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2592:             if ($env{'form.fullname'} eq '') {
                   2593:                 $env{'form.fullname'} =
                   2594:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2595:             }
                   2596:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2597:             $request->print("\n\n".
                   2598:                             '<div class="LC_grade_show_user">'.
                   2599:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2600:                             '</h2>'."\n");
                   2601:             &Apache::lonxml::clear_problem_counter();
                   2602:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2603:                             {'previousversion' => $env{'form.previousversion'} }));
                   2604:             $request->print("\n</div>");
                   2605:         }
                   2606:     }
                   2607:     return;
                   2608: }
                   2609: 
                   2610: sub choose_task_version_form {
                   2611:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2612:     my $isTask = ($symb =~/\.task$/);
                   2613:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2614:     if ($isTask) {
                   2615:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2616:                                               $udom,$uname);
                   2617:         if (($record{'resource.0.version'} eq '') ||
                   2618:             ($record{'resource.0.version'} < 2)) {
                   2619:             return ($record{'resource.0.version'},
                   2620:                     $record{'resource.0.version'},$result,$js);
                   2621:         } else {
                   2622:             $current = $record{'resource.0.version'};
                   2623:         }
                   2624:         if ($env{'form.previousversion'}) {
                   2625:             $displayed = $env{'form.previousversion'};
                   2626:             $rowtitle = &mt('Choose another version:')
                   2627:         } else {
                   2628:             $displayed = $current;
                   2629:             $rowtitle = &mt('Show earlier version:');
                   2630:         }
                   2631:         $result = '<div class="LC_left_float">';
                   2632:         my $list;
                   2633:         my $numversions = 0;
                   2634:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2635:             if ($i == $current) {
                   2636:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2637:                     next;
                   2638:                 } else {
                   2639:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2640:                     $numversions ++;
                   2641:                 }
                   2642:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2643:                 unless ($i == $env{'form.previousversion'}) {
                   2644:                     $numversions ++;
                   2645:                 }
                   2646:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2647:             }
                   2648:         }
                   2649:         if ($numversions) {
                   2650:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2651:             $result .=
                   2652:                 '<form name="getprev" method="post" action=""'.
                   2653:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2654:                 &Apache::loncommon::start_data_table().
                   2655:                 &Apache::loncommon::start_data_table_row().
                   2656:                 '<th align="left">'.$rowtitle.'</th>'.
                   2657:                 '<td><select name="version">'.
                   2658:                 '<option>'.&mt('Select').'</option>'.
                   2659:                 $list.
                   2660:                 '</select></td>'.
                   2661:                 &Apache::loncommon::end_data_table_row();
                   2662:             unless ($nomenu) {
                   2663:                 $result .= &Apache::loncommon::start_data_table_row().
                   2664:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2665:                 '<td><span class="LC_nobreak">'.
                   2666:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2667:                 &mt('Yes').'</label>'.
                   2668:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2669:                 '</span></td>'.
                   2670:                 &Apache::loncommon::end_data_table_row();
                   2671:             }
                   2672:             $result .=
                   2673:                 &Apache::loncommon::start_data_table_row().
                   2674:                 '<th align="left">&nbsp;</th>'.
                   2675:                 '<td>'.
                   2676:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2677:                 '</td>'.
                   2678:                 &Apache::loncommon::end_data_table_row().
                   2679:                 &Apache::loncommon::end_data_table().
                   2680:                 '</form>';
                   2681:             $js = &previous_display_javascript($nomenu,$current);
                   2682:         } elsif ($displayed && $nomenu) {
                   2683:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2684:         } else {
                   2685:             $result .= &mt('No previous versions to show for this student');
                   2686:         }
                   2687:         $result .= '</div>';
                   2688:     }
                   2689:     return ($current,$displayed,$result,$js);
                   2690: }
                   2691: 
                   2692: sub previous_display_javascript {
                   2693:     my ($nomenu,$current) = @_;
                   2694:     my $js = <<"JSONE";
                   2695: <script type="text/javascript">
                   2696: // <![CDATA[
                   2697: function previousVersion(uname,udom,symb) {
                   2698:     var current = '$current';
                   2699:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2700:     var prevstr = new RegExp("^\\\\d+\$");
                   2701:     if (!prevstr.test(version)) {
                   2702:         return false;
                   2703:     }
                   2704:     var url = '';
                   2705:     if (version == current) {
                   2706:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2707:     } else {
                   2708:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2709:     }
                   2710: JSONE
                   2711:     if ($nomenu) {
                   2712:         $js .= <<"JSTWO";
                   2713:     document.location.href = url;
                   2714: JSTWO
                   2715:     } else {
                   2716:         $js .= <<"JSTHREE";
                   2717:     var newwin = 0;
                   2718:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2719:         if (document.getprev.prevwin[i].checked == true) {
                   2720:             newwin = document.getprev.prevwin[i].value;
                   2721:         }
                   2722:     }
                   2723:     if (newwin == 1) {
                   2724:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2725:         url = url+'&inhibitmenu=yes';
                   2726:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2727:             previousWin = window.open(url,'',options,1);
                   2728:         } else {
                   2729:             previousWin.location.href = url;
                   2730:         }
                   2731:         previousWin.focus();
                   2732:         return false;
                   2733:     } else {
                   2734:         document.location.href = url;
                   2735:         return false;
                   2736:     }
                   2737: JSTHREE
                   2738:     }
                   2739:     $js .= <<"ENDJS";
                   2740:     return false;
                   2741: }
                   2742: // ]]>
                   2743: </script>
                   2744: ENDJS
                   2745: 
                   2746: }
                   2747: 
1.44      ng       2748: #--- Called from submission routine
1.38      ng       2749: sub processHandGrade {
1.608     www      2750:     my ($request,$symb) = @_;
1.324     albertel 2751:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2752:     my $button = $env{'form.gradeOpt'};
                   2753:     my $ngrade = $env{'form.NCT'};
                   2754:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2755:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2756:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2757: 
1.44      ng       2758:     if ($button eq 'Save & Next') {
                   2759: 	my $ctr = 0;
                   2760: 	while ($ctr < $ngrade) {
1.257     albertel 2761: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2762: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2763: 	    if ($errorflag eq 'no_score') {
                   2764: 		$ctr++;
                   2765: 		next;
                   2766: 	    }
1.104     albertel 2767: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2768: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2769: 		$ctr++;
                   2770: 		next;
                   2771: 	    }
1.257     albertel 2772: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2773: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2774: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2775:             my ($feedurl,$showsymb) =
                   2776: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2777: 	    my $messagetail;
1.62      albertel 2778: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2779: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2780: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2781: 		$subject.=' ['.$restitle.']';
1.44      ng       2782: 		my (@msgnum) = split(/,/,$includemsg);
                   2783: 		foreach (@msgnum) {
1.257     albertel 2784: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2785: 		}
1.80      ng       2786: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2787: 		if ($env{'form.withgrades'.$ctr}) {
                   2788: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2789: 		    $messagetail = " for <a href=\"".
1.605     www      2790: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2791: 		}
                   2792: 		$msgstatus = 
                   2793:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2794: 						     $message.$messagetail,
1.418     albertel 2795:                                                      undef,$feedurl,undef,
1.386     raeburn  2796:                                                      undef,undef,$showsymb,
                   2797:                                                      $restitle);
1.574     bisitz   2798: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2799: 				$msgstatus.'<br />');
1.44      ng       2800: 	    }
1.257     albertel 2801: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2802: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2803: 		foreach my $collabstr (@collabstrs) {
                   2804: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2805: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2806: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2807: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2808: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2809: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2810: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2811: 			    next;
1.418     albertel 2812: 			} elsif ($message ne '') {
                   2813: 			    my ($baseurl,$showsymb) = 
                   2814: 				&get_feedurl_and_symb($symb,$collaborator,
                   2815: 						      $udom);
                   2816: 			    if ($env{'form.withgrades'.$ctr}) {
                   2817: 				$messagetail = " for <a href=\"".
1.605     www      2818:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2819: 			    }
1.418     albertel 2820: 			    $msgstatus = 
                   2821: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2822: 			}
1.44      ng       2823: 		    }
                   2824: 		}
                   2825: 	    }
                   2826: 	    $ctr++;
                   2827: 	}
                   2828:     }
                   2829: 
1.624     www      2830: #    if ($env{'form.handgrade'} eq 'yes') {
                   2831:     if (1) {
1.119     ng       2832: 	# Keywords sorted in alphabatical order
1.257     albertel 2833: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2834: 	my %keyhash = ();
1.257     albertel 2835: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2836: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2837: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2838: 	$env{'form.keywords'} = join(' ',@keywords);
                   2839: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2840: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2841: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2842: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2843: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2844: 
                   2845: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2846: 	# New messages are saved in env for the next student.
1.119     ng       2847: 	# All messages are saved in nohist_handgrade.db
                   2848: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2849: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2850: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2851: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2852: 		$idx++;
                   2853: 	    }
                   2854: 	    $ctr++;
1.41      ng       2855: 	}
1.119     ng       2856: 	$ctr = 0;
                   2857: 	while ($ctr < $ngrade) {
1.257     albertel 2858: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2859: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2860: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2861: 		$idx++;
                   2862: 	    }
                   2863: 	    $ctr++;
1.41      ng       2864: 	}
1.257     albertel 2865: 	$env{'form.savemsgN'} = --$idx;
                   2866: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2867: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2868: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2869:     }
1.44      ng       2870:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2871:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2872:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2873: 	my ($ctr,$total) = (0,0);
                   2874: 	while ($ctr < $ngrade) {
1.257     albertel 2875: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2876: 	    $ctr++;
                   2877: 	}
1.257     albertel 2878: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2879: 	$ctr = 0;
                   2880: 	while ($ctr < $total) {
1.257     albertel 2881: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2882: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2883: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2884: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2885: 	    $ctr++;
                   2886: 	}
                   2887: 	return '';
                   2888:     }
1.36      ng       2889: 
1.44      ng       2890:     # Get the next/previous one or group of students
1.257     albertel 2891:     my $firststu = $env{'form.unamedom0'};
                   2892:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2893:     my $ctr = 2;
1.41      ng       2894:     while ($laststu eq '') {
1.257     albertel 2895: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2896: 	$ctr++;
                   2897: 	$laststu = $firststu if ($ctr > $ngrade);
                   2898:     }
1.44      ng       2899: 
1.41      ng       2900:     my (@parsedlist,@nextlist);
                   2901:     my ($nextflg) = 0;
1.524     raeburn  2902:     foreach my $item (sort 
1.294     albertel 2903: 	     {
                   2904: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2905: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2906: 		 }
                   2907: 		 return $a cmp $b;
                   2908: 	     } (keys(%$fullname))) {
1.605     www      2909: # FIXME: this is fishy, looks like the button label
1.41      ng       2910: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2911: 	    push(@parsedlist,$item);
1.41      ng       2912: 	}
1.524     raeburn  2913: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2914: 	if ($button eq 'Previous') {
1.524     raeburn  2915: 	    last if ($item eq $firststu);
                   2916: 	    push(@parsedlist,$item);
1.41      ng       2917: 	}
                   2918:     }
                   2919:     $ctr = 0;
1.605     www      2920: # FIXME: this is fishy, looks like the button label
1.41      ng       2921:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2922:     my $res_error;
                   2923:     my ($partlist) = &response_type($symb,\$res_error);
                   2924:     if ($res_error) {
                   2925:         $request->print(&navmap_errormsg());
                   2926:         return;
                   2927:     }
1.41      ng       2928:     foreach my $student (@parsedlist) {
1.257     albertel 2929: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2930: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2931: 	
                   2932: 	if ($submitonly eq 'queued') {
                   2933: 	    my %queue_status = 
                   2934: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2935: 							$udom,$uname);
                   2936: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2937: 	}
                   2938: 
1.156     albertel 2939: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2940: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2941: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2942: 	    my $submitted = 0;
1.248     albertel 2943: 	    my $ungraded = 0;
                   2944: 	    my $incorrect = 0;
1.524     raeburn  2945: 	    foreach my $item (keys(%status)) {
                   2946: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2947: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2948: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2949: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2950: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2951: 		    $submitted = 0;
                   2952: 		}
1.41      ng       2953: 	    }
1.156     albertel 2954: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2955: 				     $submitonly eq 'incorrect' ||
                   2956: 				     $submitonly eq 'graded'));
1.248     albertel 2957: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2958: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2959: 	}
1.524     raeburn  2960: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2961: 	last if ($ctr == $ntstu);
1.41      ng       2962: 	$ctr++;
                   2963:     }
1.36      ng       2964: 
1.41      ng       2965:     $ctr = 0;
                   2966:     my $total = scalar(@nextlist)-1;
1.39      ng       2967: 
1.524     raeburn  2968:     foreach (sort(@nextlist)) {
1.41      ng       2969: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2970: 	$env{'form.student'}  = $uname;
                   2971: 	$env{'form.userdom'}  = $udom;
                   2972: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2973: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2974: 	$ctr++;
                   2975:     }
                   2976:     if ($total < 0) {
1.653     raeburn  2977: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2978: 	$request->print($the_end);
                   2979:     }
                   2980:     return '';
1.38      ng       2981: }
1.36      ng       2982: 
1.44      ng       2983: #---- Save the score and award for each student, if changed
1.38      ng       2984: sub saveHandGrade {
1.324     albertel 2985:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2986:     my @version_parts;
1.104     albertel 2987:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2988: 					   $env{'request.course.id'});
1.104     albertel 2989:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2990:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2991:     my @parts_graded;
1.77      ng       2992:     my %newrecord  = ();
                   2993:     my ($pts,$wgt) = ('','');
1.269     raeburn  2994:     my %aggregate = ();
                   2995:     my $aggregateflag = 0;
1.301     albertel 2996:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2997:     foreach my $new_part (@parts) {
1.337     banghart 2998: 	#collaborator ($submi may vary for different parts
1.259     banghart 2999: 	if ($submitter && $new_part ne $part) { next; }
                   3000: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3001: 	if ($dropMenu eq 'excused') {
1.259     banghart 3002: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3003: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3004: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3005: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3006: 		}
1.364     banghart 3007: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3008: 	    }
1.125     ng       3009: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3010: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3011: 	    foreach my $key (keys(%record)) {
1.259     banghart 3012: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3013: 	    }
1.259     banghart 3014: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3015: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3016:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3017: 
                   3018:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3019: 					       [$new_part]);
                   3020:             my $aggtries =$totaltries;
1.269     raeburn  3021:             if ($last_resets{$new_part}) {
1.270     albertel 3022:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3023: 					   $new_part);
1.269     raeburn  3024:             }
1.270     albertel 3025: 
                   3026:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3027:             if ($aggtries > 0) {
1.327     albertel 3028:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3029:                 $aggregateflag = 1;
                   3030:             }
1.125     ng       3031: 	} elsif ($dropMenu eq '') {
1.259     banghart 3032: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3033: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3034: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3035: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3036: 		next;
                   3037: 	    }
1.259     banghart 3038: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3039: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3040: 	    my $partial= $pts/$wgt;
1.259     banghart 3041: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3042: 		#do not update score for part if not changed.
1.346     banghart 3043:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3044: 		next;
1.251     banghart 3045: 	    } else {
1.524     raeburn  3046: 	        push(@parts_graded,$new_part);
1.153     albertel 3047: 	    }
1.259     banghart 3048: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3049: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3050: 	    }
1.259     banghart 3051: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3052: 	    if ($partial == 0) {
1.153     albertel 3053: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3054: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3055: 		}
1.41      ng       3056: 	    } else {
1.153     albertel 3057: 		if ($record{$reckey} ne 'correct_by_override') {
                   3058: 		    $newrecord{$reckey} = 'correct_by_override';
                   3059: 		}
                   3060: 	    }	    
                   3061: 	    if ($submitter && 
1.259     banghart 3062: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3063: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3064: 	    }
1.259     banghart 3065: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3066: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3067: 	}
1.259     banghart 3068: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3069: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3070: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3071: 	        $dropMenu eq 'reset status')
                   3072: 	   {
1.524     raeburn  3073: 	    push(@version_parts,$new_part);
1.259     banghart 3074: 	}
1.41      ng       3075:     }
1.301     albertel 3076:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3077:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3078: 
1.344     albertel 3079:     if (%newrecord) {
                   3080:         if (@version_parts) {
1.364     banghart 3081:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3082:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3083: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3084: 	    foreach my $new_part (@version_parts) {
                   3085: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3086: 				$new_part,\%newrecord);
                   3087: 	    }
1.259     banghart 3088:         }
1.44      ng       3089: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3090: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3091: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3092: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3093:     }
1.269     raeburn  3094:     if ($aggregateflag) {
                   3095:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3096: 			      $cdom,$cnum);
1.269     raeburn  3097:     }
1.301     albertel 3098:     return ('',$pts,$wgt);
1.36      ng       3099: }
1.322     albertel 3100: 
1.380     albertel 3101: sub check_and_remove_from_queue {
                   3102:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3103:     my @ungraded_parts;
                   3104:     foreach my $part (@{$parts}) {
                   3105: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3106: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3107: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3108: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3109: 		) {
                   3110: 	    push(@ungraded_parts, $part);
                   3111: 	}
                   3112:     }
                   3113:     if ( !@ungraded_parts ) {
                   3114: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3115: 					       $cnum,$domain,$stuname);
                   3116:     }
                   3117: }
                   3118: 
1.337     banghart 3119: sub handback_files {
                   3120:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3121:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3122:     my $res_error;
                   3123:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3124:     if ($res_error) {
                   3125:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3126:         return;
                   3127:     }
1.654     raeburn  3128:     my @handedback;
                   3129:     my $file_msg;
1.375     albertel 3130:     my @part_response_id = &flatten_responseType($responseType);
                   3131:     foreach my $part_response_id (@part_response_id) {
                   3132:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3133: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3134:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3135:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3136:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3137:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3138:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3139:                     my ($directory,$answer_file) = 
1.654     raeburn  3140:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3141:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3142: 		        &file_name_version_ext($answer_file);
1.355     banghart 3143: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3144:                     my $getpropath = 1;
1.662     raeburn  3145:                     my ($dir_list,$listerror) = 
                   3146:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3147:                                                  $domain,$stuname,$getpropath);
                   3148: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3149:                     # fix filename
1.355     banghart 3150:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3151:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3152:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3153:             	                                $save_file_name);
1.337     banghart 3154:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3155:                         $request->print('<br /><span class="LC_error">'.
                   3156:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3157:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3158:                                         '</span>');
1.356     banghart 3159:                     } else {
1.360     banghart 3160:                         # mark the file as read only
1.654     raeburn  3161:                         push(@handedback,$save_file_name);
1.367     albertel 3162: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3163: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3164: 			}
                   3165:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3166: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3167:                     }
1.686     bisitz   3168:                     $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 3169:                 }
                   3170:             }
                   3171:         }
1.654     raeburn  3172:     }
                   3173:     if (@handedback > 0) {
                   3174:         $request->print('<br />');
                   3175:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3176:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3177:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3178:         my ($subject,$message);
                   3179:         if (scalar(@handedback) == 1) {
                   3180:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3181:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3182:         } else {
                   3183:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3184:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3185:         }
                   3186:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3187:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3188:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3189:         my ($feedurl,$showsymb) =
                   3190:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3191:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3192:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3193:         my $msgstatus =
                   3194:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3195:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3196:                  $restitle);
                   3197:         if ($msgstatus) {
                   3198:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3199:         }
                   3200:     }
1.338     banghart 3201:     return;
1.337     banghart 3202: }
                   3203: 
1.418     albertel 3204: sub get_feedurl_and_symb {
                   3205:     my ($symb,$uname,$udom) = @_;
                   3206:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3207:     $url = &Apache::lonnet::clutter($url);
                   3208:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3209: 					$symb,$udom,$uname);
                   3210:     if ($encrypturl =~ /^yes$/i) {
                   3211: 	&Apache::lonenc::encrypted(\$url,1);
                   3212: 	&Apache::lonenc::encrypted(\$symb,1);
                   3213:     }
                   3214:     return ($url,$symb);
                   3215: }
                   3216: 
1.313     banghart 3217: sub get_submitted_files {
                   3218:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3219:     my @files;
                   3220:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3221:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3222:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3223:     	    push(@files,$file_url.$file);
                   3224:         }
                   3225:     }
                   3226:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3227:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3228:     }
                   3229:     return (\@files);
                   3230: }
1.322     albertel 3231: 
1.269     raeburn  3232: # ----------- Provides number of tries since last reset.
                   3233: sub get_num_tries {
                   3234:     my ($record,$last_reset,$part) = @_;
                   3235:     my $timestamp = '';
                   3236:     my $num_tries = 0;
                   3237:     if ($$record{'version'}) {
                   3238:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3239:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3240:                 $timestamp = $$record{$version.':timestamp'};
                   3241:                 if ($timestamp > $last_reset) {
                   3242:                     $num_tries ++;
                   3243:                 } else {
                   3244:                     last;
                   3245:                 }
                   3246:             }
                   3247:         }
                   3248:     }
                   3249:     return $num_tries;
                   3250: }
                   3251: 
                   3252: # ----------- Determine decrements required in aggregate totals 
                   3253: sub decrement_aggs {
                   3254:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3255:     my %decrement = (
                   3256:                         attempts => 0,
                   3257:                         users => 0,
                   3258:                         correct => 0
                   3259:                     );
                   3260:     $decrement{'attempts'} = $aggtries;
                   3261:     if ($solvedstatus =~ /^correct/) {
                   3262:         $decrement{'correct'} = 1;
                   3263:     }
                   3264:     if ($aggtries == $totaltries) {
                   3265:         $decrement{'users'} = 1;
                   3266:     }
1.524     raeburn  3267:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3268:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3269:     }
                   3270:     return;
                   3271: }
                   3272: 
                   3273: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3274: sub get_last_resets {
1.270     albertel 3275:     my ($symb,$courseid,$partids) =@_;
                   3276:     my %last_resets;
1.269     raeburn  3277:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3278:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3279:     my @keys;
                   3280:     foreach my $part (@{$partids}) {
                   3281: 	push(@keys,"$symb\0$part\0resettime");
                   3282:     }
                   3283:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3284: 				     $cdom,$cname);
                   3285:     foreach my $part (@{$partids}) {
                   3286: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3287:     }
1.270     albertel 3288:     return %last_resets;
1.269     raeburn  3289: }
                   3290: 
1.251     banghart 3291: # ----------- Handles creating versions for portfolio files as answers
                   3292: sub version_portfiles {
1.343     banghart 3293:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3294:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3295:     my @returned_keys;
1.255     banghart 3296:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3297:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3298:     foreach my $key (keys(%$record)) {
1.259     banghart 3299:         my $new_portfiles;
1.263     banghart 3300:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3301:             my @versioned_portfiles;
1.367     albertel 3302:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3303:             foreach my $file (@portfiles) {
1.306     banghart 3304:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3305:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3306: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3307: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3308:                 my $getpropath = 1;    
1.662     raeburn  3309:                 my ($dir_list,$listerror) = 
                   3310:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3311:                                              $stu_name,$getpropath);
                   3312:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3313:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3314:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3315:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3316:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3317:                         [$directory.$new_answer],
1.306     banghart 3318:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3319:                 }
1.252     banghart 3320:             }
1.343     banghart 3321:             $$record{$key} = join(',',@versioned_portfiles);
                   3322:             push(@returned_keys,$key);
1.251     banghart 3323:         }
                   3324:     } 
1.343     banghart 3325:     return (@returned_keys);   
1.305     banghart 3326: }
                   3327: 
1.307     banghart 3328: sub get_next_version {
1.341     banghart 3329:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3330:     my $version;
1.662     raeburn  3331:     if (ref($dir_list) eq 'ARRAY') {
                   3332:         foreach my $row (@{$dir_list}) {
                   3333:             my ($file) = split(/\&/,$row,2);
                   3334:             my ($file_name,$file_version,$file_ext) =
                   3335: 	        &file_name_version_ext($file);
                   3336:             if (($file_name eq $answer_name) && 
                   3337: 	        ($file_ext eq $answer_ext)) {
                   3338:                      # gets here if filename and extension match, 
                   3339:                      # regardless of version
1.307     banghart 3340:                 if ($file_version ne '') {
1.662     raeburn  3341:                     # a versioned file is found  so save it for later
                   3342:                     if ($file_version > $version) {
                   3343: 		        $version = $file_version;
                   3344: 	            }
                   3345:                 }
1.307     banghart 3346:             }
                   3347:         }
1.662     raeburn  3348:     }
1.307     banghart 3349:     $version ++;
                   3350:     return($version);
                   3351: }
                   3352: 
1.305     banghart 3353: sub version_selected_portfile {
1.306     banghart 3354:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3355:     my ($answer_name,$answer_ver,$answer_ext) =
                   3356:         &file_name_version_ext($file_name);
                   3357:     my $new_answer;
                   3358:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3359:     if($env{'form.copy'} eq '-1') {
                   3360:         $new_answer = 'problem getting file';
                   3361:     } else {
                   3362:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3363:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3364:                             $stu_name,$domain,'copy',
                   3365: 		        '/portfolio'.$directory.$new_answer);
                   3366:     }    
                   3367:     return ($new_answer);
1.251     banghart 3368: }
                   3369: 
1.304     albertel 3370: sub file_name_version_ext {
                   3371:     my ($file)=@_;
                   3372:     my @file_parts = split(/\./, $file);
                   3373:     my ($name,$version,$ext);
                   3374:     if (@file_parts > 1) {
                   3375: 	$ext=pop(@file_parts);
                   3376: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3377: 	    $version=pop(@file_parts);
                   3378: 	}
                   3379: 	$name=join('.',@file_parts);
                   3380:     } else {
                   3381: 	$name=join('.',@file_parts);
                   3382:     }
                   3383:     return($name,$version,$ext);
                   3384: }
                   3385: 
1.44      ng       3386: #--------------------------------------------------------------------------------------
                   3387: #
                   3388: #-------------------------- Next few routines handles grading by section or whole class
                   3389: #
                   3390: #--- Javascript to handle grading by section or whole class
1.42      ng       3391: sub viewgrades_js {
                   3392:     my ($request) = shift;
                   3393: 
1.539     riegler  3394:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3395:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3396:    function writePoint(partid,weight,point) {
1.125     ng       3397: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3398: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3399: 	if (point == "textval") {
1.125     ng       3400: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3401: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3402: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3403: 		var resetbox = false;
                   3404: 		for (var i=0; i<radioButton.length; i++) {
                   3405: 		    if (radioButton[i].checked) {
                   3406: 			textbox.value = i;
                   3407: 			resetbox = true;
                   3408: 		    }
                   3409: 		}
                   3410: 		if (!resetbox) {
                   3411: 		    textbox.value = "";
                   3412: 		}
                   3413: 		return;
                   3414: 	    }
1.109     matthew  3415: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3416: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3417: 				   ") greater than the weight for the part. Accept?");
                   3418: 		if (resp == false) {
                   3419: 		    textbox.value = "";
                   3420: 		    return;
                   3421: 		}
                   3422: 	    }
1.42      ng       3423: 	    for (var i=0; i<radioButton.length; i++) {
                   3424: 		radioButton[i].checked=false;
1.109     matthew  3425: 		if (parseFloat(point) == i) {
1.42      ng       3426: 		    radioButton[i].checked=true;
                   3427: 		}
                   3428: 	    }
1.41      ng       3429: 
1.42      ng       3430: 	} else {
1.125     ng       3431: 	    textbox.value = parseFloat(point);
1.42      ng       3432: 	}
1.41      ng       3433: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3434: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3435: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3436: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3437: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3438: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3439: 	    if (saveval != "correct") {
                   3440: 		scorename.value = point;
1.43      ng       3441: 		if (selname[0].selected != true) {
                   3442: 		    selname[0].selected = true;
                   3443: 		}
1.42      ng       3444: 	    }
                   3445: 	}
1.125     ng       3446: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3447:     }
                   3448: 
                   3449:     function writeRadText(partid,weight) {
1.125     ng       3450: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3451: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3452:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3453: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3454: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3455: 	    for (var i=0; i<radioButton.length; i++) {
                   3456: 		radioButton[i].checked=false;
                   3457: 
                   3458: 	    }
                   3459: 	    textbox.value = "";
                   3460: 
                   3461: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3462: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3463: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3464: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3465: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3466: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3467: 		if ((saveval != "correct") || override) {
1.42      ng       3468: 		    scorename.value = "";
1.125     ng       3469: 		    if (selval[1].selected) {
                   3470: 			selname[1].selected = true;
                   3471: 		    } else {
                   3472: 			selname[2].selected = true;
                   3473: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3474: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3475: 		    }
1.42      ng       3476: 		}
                   3477: 	    }
1.43      ng       3478: 	} else {
                   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.125     ng       3486: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3487: 		    selname[0].selected = true;
                   3488: 		}
                   3489: 	    }
                   3490: 	}	    
1.42      ng       3491:     }
                   3492: 
                   3493:     function changeSelect(partid,user) {
1.125     ng       3494: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3495: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3496: 	var point  = textbox.value;
1.125     ng       3497: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3498: 
1.109     matthew  3499: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3500: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3501: 	    textbox.value = "";
                   3502: 	    return;
                   3503: 	}
1.109     matthew  3504: 	if (parseFloat(point) > parseFloat(weight)) {
                   3505: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3506: 			       ") greater than the weight of the part. Accept?");
                   3507: 	    if (resp == false) {
                   3508: 		textbox.value = "";
                   3509: 		return;
                   3510: 	    }
                   3511: 	}
1.42      ng       3512: 	selval[0].selected = true;
                   3513:     }
                   3514: 
                   3515:     function changeOneScore(partid,user) {
1.125     ng       3516: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3517: 	if (selval[1].selected || selval[2].selected) {
                   3518: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3519: 	    if (selval[2].selected) {
                   3520: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3521: 	    }
1.269     raeburn  3522:         }
1.42      ng       3523:     }
                   3524: 
                   3525:     function resetEntry(numpart) {
                   3526: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3527: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3528: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3529: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3530: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3531: 	    for (var i=0; i<radioButton.length; i++) {
                   3532: 		radioButton[i].checked=false;
                   3533: 
                   3534: 	    }
                   3535: 	    textbox.value = "";
                   3536: 	    selval[0].selected = true;
                   3537: 
                   3538: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3539: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3540: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3541: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3542: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3543: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3544: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3545: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3546: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3547: 		if (saveselval == "excused") {
1.43      ng       3548: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3549: 		} else {
1.43      ng       3550: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3551: 		}
                   3552: 	    }
1.41      ng       3553: 	}
1.42      ng       3554:     }
                   3555: 
1.41      ng       3556: VIEWJAVASCRIPT
1.42      ng       3557: }
                   3558: 
1.44      ng       3559: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3560: sub viewgrades {
1.608     www      3561:     my ($request,$symb) = @_;
1.42      ng       3562:     &viewgrades_js($request);
1.41      ng       3563: 
1.168     albertel 3564:     #need to make sure we have the correct data for later EXT calls, 
                   3565:     #thus invalidate the cache
                   3566:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3567:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3568:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3569:     &Apache::lonnet::clear_EXT_cache_status();
                   3570: 
1.398     albertel 3571:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3572: 
                   3573:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3574:     $result.=&jscriptNform($symb);
1.41      ng       3575: 
1.44      ng       3576:     #beginning of class grading form
1.442     banghart 3577:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3578:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3579: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3580: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3581: 	&build_section_inputs().
1.442     banghart 3582: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3583: 
1.560     raeburn  3584:     my ($common_header,$specific_header);
1.257     albertel 3585:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3586: 	$common_header = &mt('Assign Common Grade to Class');
                   3587:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3588:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3589:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3590: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3591:     } else {
1.560     raeburn  3592:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3593:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3594: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3595:     }
1.560     raeburn  3596:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3597:     #radio buttons/text box for assigning points for a section or class.
                   3598:     #handles different parts of a problem
1.582     raeburn  3599:     my $res_error;
                   3600:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3601:     if ($res_error) {
                   3602:         return &navmap_errormsg();
                   3603:     }
1.42      ng       3604:     my %weight = ();
                   3605:     my $ctsparts = 0;
1.45      ng       3606:     my %seen = ();
1.375     albertel 3607:     my @part_response_id = &flatten_responseType($responseType);
                   3608:     foreach my $part_response_id (@part_response_id) {
                   3609:     	my ($partid,$respid) = @{ $part_response_id };
                   3610: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3611: 	next if $seen{$partid};
                   3612: 	$seen{$partid}++;
1.375     albertel 3613: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3614: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3615: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3616: 
1.324     albertel 3617: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3618: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3619: 	my $ctr = 0;
1.42      ng       3620: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3621: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3622: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3623: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3624: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3625: 	    $ctr++;
                   3626: 	}
1.485     albertel 3627: 	$radio.='</tr></table>';
                   3628: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3629: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3630: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3631: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3632:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3633:             '<select name="SELVAL_'.$partid.'" '.
                   3634:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3635:                 $weight{$partid}.')"> '.
1.401     albertel 3636: 	    '<option selected="selected"> </option>'.
1.485     albertel 3637: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3638: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3639: 	    '</select></td>'.
                   3640:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3641: 	$line.='<input type="hidden" name="partid_'.
                   3642: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3643: 	$line.='<input type="hidden" name="weight_'.
                   3644: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3645: 
                   3646: 	$result.=
                   3647: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3648: 	    '<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 3649: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3650: 	$ctsparts++;
1.41      ng       3651:     }
1.474     albertel 3652:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3653: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3654:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3655: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3656: 
1.44      ng       3657:     #table listing all the students in a section/class
                   3658:     #header of table
1.560     raeburn  3659:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3660:               &Apache::loncommon::start_data_table().
                   3661: 	      &Apache::loncommon::start_data_table_header_row().
                   3662: 	      '<th>'.&mt('No.').'</th>'.
                   3663: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3664:     my $partserror;
                   3665:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3666:     if ($partserror) {
                   3667:         return &navmap_errormsg();
                   3668:     }
1.324     albertel 3669:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3670:     my @partids = ();
1.41      ng       3671:     foreach my $part (@parts) {
                   3672: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3673:         my $narrowtext = &mt('Tries');
                   3674: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3675: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3676: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3677:         push(@partids,$partid);
1.628     www      3678: #
                   3679: # FIXME: Looks like $display looks at English text
                   3680: #
1.324     albertel 3681: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3682: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3683: 	    $result.='<th>'.
1.697     bisitz   3684: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3685: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3686: 	    next;
1.485     albertel 3687: 	    
1.207     albertel 3688: 	} else {
1.485     albertel 3689: 	    if ($display =~ /Problem Status/) {
                   3690: 		my $grade_status_mt = &mt('Grade Status');
                   3691: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3692: 	    }
                   3693: 	    my $part_mt = &mt('Part:');
                   3694: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3695: 	}
1.485     albertel 3696: 
1.474     albertel 3697: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3698:     }
1.474     albertel 3699:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3700: 
1.270     albertel 3701:     my %last_resets = 
                   3702: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3703: 
1.41      ng       3704:     #get info for each student
1.44      ng       3705:     #list all the students - with points and grade status
1.257     albertel 3706:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3707:     my $ctr = 0;
1.294     albertel 3708:     foreach (sort 
                   3709: 	     {
                   3710: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3711: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3712: 		 }
                   3713: 		 return $a cmp $b;
                   3714: 	     } (keys(%$fullname))) {
1.126     ng       3715: 	$ctr++;
1.324     albertel 3716: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3717: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3718:     }
1.474     albertel 3719:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3720:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3721:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3722: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3723:     if (scalar(%$fullname) eq 0) {
                   3724: 	my $colspan=3+scalar(@parts);
1.433     banghart 3725: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3726:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3727: 	$result='<span class="LC_warning">'.
1.485     albertel 3728: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3729: 	        $section_display, $stu_status).
1.433     banghart 3730: 	    '</span>';
1.96      albertel 3731:     }
1.41      ng       3732:     return $result;
                   3733: }
                   3734: 
1.44      ng       3735: #--- call by previous routine to display each student
1.41      ng       3736: sub viewstudentgrade {
1.324     albertel 3737:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3738:     my ($uname,$udom) = split(/:/,$student);
                   3739:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3740:     my %aggregates = (); 
1.474     albertel 3741:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3742: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3743: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3744: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3745: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3746: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3747:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3748:     foreach my $apart (@$parts) {
                   3749: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3750: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3751:         $result.='<td align="center">';
1.269     raeburn  3752:         my ($aggtries,$totaltries);
                   3753:         unless (exists($aggregates{$part})) {
1.270     albertel 3754: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3755: 
                   3756: 	    $aggtries = $totaltries;
1.269     raeburn  3757:             if ($$last_resets{$part}) {  
1.270     albertel 3758:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3759: 					   $part);
                   3760:             }
1.269     raeburn  3761:             $result.='<input type="hidden" name="'.
                   3762:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3763:             $result.='<input type="hidden" name="'.
                   3764:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3765:             $aggregates{$part} = 1;
                   3766:         }
1.41      ng       3767: 	if ($type eq 'awarded') {
1.320     albertel 3768: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3769: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3770: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3771: 	    $result.='<input type="text" name="'.
1.89      albertel 3772: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3773:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3774: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3775: 	} elsif ($type eq 'solved') {
                   3776: 	    my ($status,$foo)=split(/_/,$score,2);
                   3777: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3778: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3779: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3780: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3781: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3782:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3783: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3784: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3785: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3786: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3787: 	} else {
                   3788: 	    $result.='<input type="hidden" name="'.
                   3789: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3790: 		    "\n";
1.233     albertel 3791: 	    $result.='<input type="text" name="'.
1.122     ng       3792: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3793: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3794: 	}
                   3795:     }
1.474     albertel 3796:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3797:     return $result;
1.38      ng       3798: }
                   3799: 
1.44      ng       3800: #--- change scores for all the students in a section/class
                   3801: #    record does not get update if unchanged
1.38      ng       3802: sub editgrades {
1.608     www      3803:     my ($request,$symb) = @_;
1.41      ng       3804: 
1.433     banghart 3805:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3806:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3807:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3808: 
1.477     albertel 3809:     my $result= &Apache::loncommon::start_data_table().
                   3810: 	&Apache::loncommon::start_data_table_header_row().
                   3811: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3812: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3813:     my %scoreptr = (
                   3814: 		    'correct'  =>'correct_by_override',
                   3815: 		    'incorrect'=>'incorrect_by_override',
                   3816: 		    'excused'  =>'excused',
                   3817: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3818:                     'credited' =>'credit_attempted',
1.43      ng       3819: 		    'nothing'  => '',
                   3820: 		    );
1.257     albertel 3821:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3822: 
1.44      ng       3823:     my (@partid);
                   3824:     my %weight = ();
1.54      albertel 3825:     my %columns = ();
1.44      ng       3826:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3827: 
1.582     raeburn  3828:     my $partserror;
                   3829:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3830:     if ($partserror) {
                   3831:         return &navmap_errormsg();
                   3832:     }
1.54      albertel 3833:     my $header;
1.257     albertel 3834:     while ($ctr < $env{'form.totalparts'}) {
                   3835: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3836: 	push(@partid,$partid);
1.257     albertel 3837: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3838: 	$ctr++;
1.54      albertel 3839:     }
1.324     albertel 3840:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3841:     foreach my $partid (@partid) {
1.478     albertel 3842: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3843: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3844: 	$columns{$partid}=2;
                   3845: 	foreach my $stores (@parts) {
                   3846: 	    my ($part,$type) = &split_part_type($stores);
                   3847: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3848: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3849: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3850: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3851:             my $narrowtext = &mt('Tries');
                   3852: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3853: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3854: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3855: 	    $columns{$partid}+=2;
                   3856: 	}
                   3857:     }
                   3858:     foreach my $partid (@partid) {
1.324     albertel 3859: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3860: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3861: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3862: 	    '</th>';
1.54      albertel 3863: 
1.44      ng       3864:     }
1.477     albertel 3865:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3866: 	&Apache::loncommon::start_data_table_header_row().
                   3867: 	$header.
                   3868: 	&Apache::loncommon::end_data_table_header_row();
                   3869:     my @noupdate;
1.126     ng       3870:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3871:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3872: 	my $line;
1.257     albertel 3873: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3874: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3875: 	my %newrecord;
                   3876: 	my $updateflag = 0;
1.281     albertel 3877: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3878: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3879: 	if (!&canmodify($usec)) {
1.126     ng       3880: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3881: 	    push(@noupdate,
1.478     albertel 3882: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3883: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3884: 	    next;
                   3885: 	}
1.269     raeburn  3886:         my %aggregate = ();
                   3887:         my $aggregateflag = 0;
1.281     albertel 3888: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3889: 	foreach (@partid) {
1.257     albertel 3890: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3891: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3892: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3893: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3894: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3895: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3896: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3897: 	    my $score;
                   3898: 	    if ($partial eq '') {
1.257     albertel 3899: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3900: 	    } elsif ($partial > 0) {
                   3901: 		$score = 'correct_by_override';
                   3902: 	    } elsif ($partial == 0) {
                   3903: 		$score = 'incorrect_by_override';
                   3904: 	    }
1.257     albertel 3905: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3906: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3907: 
1.292     albertel 3908: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3909: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3910: 	    if ($dropMenu eq 'reset status' &&
                   3911: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3912: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3913: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3914: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3915: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3916: 		$updateflag = 1;
1.269     raeburn  3917:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3918:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3919:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3920:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3921:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3922:                     $aggregateflag = 1;
                   3923:                 }
1.139     albertel 3924: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3925: 		$updateflag = 1;
                   3926: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3927: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3928: 		$rec_update++;
1.125     ng       3929: 	    }
                   3930: 
1.93      albertel 3931: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3932: 		'<td align="center">'.$awarded.
                   3933: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3934: 
1.54      albertel 3935: 
                   3936: 	    my $partid=$_;
                   3937: 	    foreach my $stores (@parts) {
                   3938: 		my ($part,$type) = &split_part_type($stores);
                   3939: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3940: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3941: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3942: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3943: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3944: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3945: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3946: 		    $updateflag=1;
                   3947: 		}
1.93      albertel 3948: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3949: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3950: 	    }
1.44      ng       3951: 	}
1.477     albertel 3952: 	$line.="\n";
1.301     albertel 3953: 
                   3954: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3955: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3956: 
1.44      ng       3957: 	if ($updateflag) {
                   3958: 	    $count++;
1.257     albertel 3959: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3960: 				    $udom,$uname);
1.301     albertel 3961: 
                   3962: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3963: 					      $cnum,$udom,$uname)) {
                   3964: 		# need to figure out if should be in queue.
                   3965: 		my %record =  
                   3966: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3967: 					     $udom,$uname);
                   3968: 		my $all_graded = 1;
                   3969: 		my $none_graded = 1;
                   3970: 		foreach my $part (@parts) {
                   3971: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3972: 			$all_graded = 0;
                   3973: 		    } else {
                   3974: 			$none_graded = 0;
                   3975: 		    }
                   3976: 		}
                   3977: 
                   3978: 		if ($all_graded || $none_graded) {
                   3979: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3980: 							   $symb,$cdom,$cnum,
                   3981: 							   $udom,$uname);
                   3982: 		}
                   3983: 	    }
                   3984: 
1.477     albertel 3985: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3986: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3987: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3988: 	    $updateCtr++;
1.93      albertel 3989: 	} else {
1.477     albertel 3990: 	    push(@noupdate,
                   3991: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3992: 	    $noupdateCtr++;
1.44      ng       3993: 	}
1.269     raeburn  3994:         if ($aggregateflag) {
                   3995:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3996: 				  $cdom,$cnum);
1.269     raeburn  3997:         }
1.93      albertel 3998:     }
1.477     albertel 3999:     if (@noupdate) {
1.126     ng       4000: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4001: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4002: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4003: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4004: 	    &mt('No Changes Occurred For the Students Below').
                   4005: 	    '</td>'.
1.477     albertel 4006: 	    &Apache::loncommon::end_data_table_row();
                   4007: 	foreach my $line (@noupdate) {
                   4008: 	    $result.=
                   4009: 		&Apache::loncommon::start_data_table_row().
                   4010: 		$line.
                   4011: 		&Apache::loncommon::end_data_table_row();
                   4012: 	}
1.44      ng       4013:     }
1.614     www      4014:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4015:     my $msg = '<p><b>'.
                   4016: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4017: 	    $rec_update,$count).'</b><br />'.
                   4018: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4019: 	'</b></p>';
1.44      ng       4020:     return $title.$msg.$result;
1.5       albertel 4021: }
1.54      albertel 4022: 
                   4023: sub split_part_type {
                   4024:     my ($partstr) = @_;
                   4025:     my ($temp,@allparts)=split(/_/,$partstr);
                   4026:     my $type=pop(@allparts);
1.439     albertel 4027:     my $part=join('_',@allparts);
1.54      albertel 4028:     return ($part,$type);
                   4029: }
                   4030: 
1.44      ng       4031: #------------- end of section for handling grading by section/class ---------
                   4032: #
                   4033: #----------------------------------------------------------------------------
                   4034: 
1.5       albertel 4035: 
1.44      ng       4036: #----------------------------------------------------------------------------
                   4037: #
                   4038: #-------------------------- Next few routines handles grading by csv upload
                   4039: #
                   4040: #--- Javascript to handle csv upload
1.27      albertel 4041: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4042:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4043:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4044:   return(<<ENDPICK);
                   4045:   function verify(vf) {
                   4046:     var foundsomething=0;
                   4047:     var founduname=0;
1.243     albertel 4048:     var foundID=0;
1.27      albertel 4049:     for (i=0;i<=vf.nfields.value;i++) {
                   4050:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4051:       if (i==0 && tw!=0) { foundID=1; }
                   4052:       if (i==1 && tw!=0) { founduname=1; }
                   4053:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4054:     }
1.246     albertel 4055:     if (founduname==0 && foundID==0) {
                   4056: 	alert('$error1');
                   4057: 	return;
1.27      albertel 4058:     }
                   4059:     if (foundsomething==0) {
1.246     albertel 4060: 	alert('$error2');
                   4061: 	return;
1.27      albertel 4062:     }
                   4063:     vf.submit();
                   4064:   }
                   4065:   function flip(vf,tf) {
                   4066:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4067:     var i;
                   4068:     for (i=0;i<=vf.nfields.value;i++) {
                   4069:       //can not pick the same destination field for both name and domain
                   4070:       if (((i ==0)||(i ==1)) && 
                   4071:           ((tf==0)||(tf==1)) && 
                   4072:           (i!=tf) &&
                   4073:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4074:         eval('vf.f'+i+'.selectedIndex=0;')
                   4075:       }
                   4076:     }
                   4077:   }
                   4078: ENDPICK
                   4079: }
                   4080: 
                   4081: sub csvupload_javascript_forward_associate {
1.573     bisitz   4082:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4083:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4084:   return(<<ENDPICK);
                   4085:   function verify(vf) {
                   4086:     var foundsomething=0;
                   4087:     var founduname=0;
1.243     albertel 4088:     var foundID=0;
1.27      albertel 4089:     for (i=0;i<=vf.nfields.value;i++) {
                   4090:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4091:       if (tw==1) { foundID=1; }
                   4092:       if (tw==2) { founduname=1; }
                   4093:       if (tw>3) { foundsomething=1; }
1.27      albertel 4094:     }
1.246     albertel 4095:     if (founduname==0 && foundID==0) {
                   4096: 	alert('$error1');
                   4097: 	return;
1.27      albertel 4098:     }
                   4099:     if (foundsomething==0) {
1.246     albertel 4100: 	alert('$error2');
                   4101: 	return;
1.27      albertel 4102:     }
                   4103:     vf.submit();
                   4104:   }
                   4105:   function flip(vf,tf) {
                   4106:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4107:     var i;
                   4108:     //can not pick the same destination field twice
                   4109:     for (i=0;i<=vf.nfields.value;i++) {
                   4110:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4111:         eval('vf.f'+i+'.selectedIndex=0;')
                   4112:       }
                   4113:     }
                   4114:   }
                   4115: ENDPICK
                   4116: }
                   4117: 
1.26      albertel 4118: sub csvuploadmap_header {
1.324     albertel 4119:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4120:     my $javascript;
1.257     albertel 4121:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4122: 	$javascript=&csvupload_javascript_reverse_associate();
                   4123:     } else {
                   4124: 	$javascript=&csvupload_javascript_forward_associate();
                   4125:     }
1.45      ng       4126: 
1.418     albertel 4127:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4128:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4129:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4130:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4131:     my $reverse=&mt("Reverse Association");
1.41      ng       4132:     $request->print(<<ENDPICK);
1.632     www      4133: <br />
                   4134: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4135: <input type="hidden" name="associate"  value="" />
                   4136: <input type="hidden" name="phase"      value="three" />
                   4137: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4138: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4139: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4140: <input type="hidden" name="upfile_associate" 
1.257     albertel 4141:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4142: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4143: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4144: <hr />
                   4145: ENDPICK
1.597     wenzelju 4146:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4147:     return '';
1.26      albertel 4148: 
                   4149: }
                   4150: 
                   4151: sub csvupload_fields {
1.582     raeburn  4152:     my ($symb,$errorref) = @_;
                   4153:     my (@parts) = &getpartlist($symb,$errorref);
                   4154:     if (ref($errorref)) {
                   4155:         if ($$errorref) {
                   4156:             return;
                   4157:         }
                   4158:     }
                   4159: 
1.556     weissno  4160:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4161: 		['username','Student Username'],
                   4162: 		['domain','Student Domain']);
1.324     albertel 4163:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4164:     foreach my $part (sort(@parts)) {
                   4165: 	my @datum;
                   4166: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4167: 	my $name=$part;
                   4168: 	if  (!$display) { $display = $name; }
                   4169: 	@datum=($name,$display);
1.244     albertel 4170: 	if ($name=~/^stores_(.*)_awarded/) {
                   4171: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4172: 	}
1.41      ng       4173: 	push(@fields,\@datum);
                   4174:     }
                   4175:     return (@fields);
1.26      albertel 4176: }
                   4177: 
                   4178: sub csvuploadmap_footer {
1.41      ng       4179:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4180:     my $buttontext = &mt('Assign Grades');
1.41      ng       4181:     $request->print(<<ENDPICK);
1.26      albertel 4182: </table>
                   4183: <input type="hidden" name="nfields" value="$i" />
                   4184: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4185: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4186: </form>
                   4187: ENDPICK
                   4188: }
                   4189: 
1.283     albertel 4190: sub checkforfile_js {
1.638     www      4191:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4192:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4193:     function checkUpload(formname) {
                   4194: 	if (formname.upfile.value == "") {
1.539     riegler  4195: 	    alert("$alertmsg");
1.86      ng       4196: 	    return false;
                   4197: 	}
                   4198: 	formname.submit();
                   4199:     }
                   4200: CSVFORMJS
1.283     albertel 4201:     return $result;
                   4202: }
                   4203: 
                   4204: sub upcsvScores_form {
1.608     www      4205:     my ($request,$symb) = @_;
1.283     albertel 4206:     if (!$symb) {return '';}
                   4207:     my $result=&checkforfile_js();
1.632     www      4208:     $result.=&Apache::loncommon::start_data_table().
                   4209:              &Apache::loncommon::start_data_table_header_row().
                   4210:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4211:              &Apache::loncommon::end_data_table_header_row().
                   4212:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4213:     my $upload=&mt("Upload Scores");
1.86      ng       4214:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4215:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4216:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4217:     $result.=<<ENDUPFORM;
1.106     albertel 4218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4219: <input type="hidden" name="symb" value="$symb" />
                   4220: <input type="hidden" name="command" value="csvuploadmap" />
                   4221: $upfile_select
1.589     bisitz   4222: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4223: </form>
                   4224: ENDUPFORM
1.370     www      4225:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4226:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4227:              '</td>'.
                   4228:             &Apache::loncommon::end_data_table_row().
                   4229:             &Apache::loncommon::end_data_table();
1.86      ng       4230:     return $result;
                   4231: }
                   4232: 
                   4233: 
1.26      albertel 4234: sub csvuploadmap {
1.608     www      4235:     my ($request,$symb)= @_;
1.41      ng       4236:     if (!$symb) {return '';}
1.72      ng       4237: 
1.41      ng       4238:     my $datatoken;
1.257     albertel 4239:     if (!$env{'form.datatoken'}) {
1.41      ng       4240: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4241:     } else {
1.257     albertel 4242: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4243: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4244:     }
1.41      ng       4245:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4246:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4247:     my ($i,$keyfields);
                   4248:     if (@records) {
1.582     raeburn  4249:         my $fieldserror;
                   4250: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4251:         if ($fieldserror) {
                   4252:             $request->print(&navmap_errormsg());
                   4253:             return;
                   4254:         }
1.257     albertel 4255: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4256: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4257: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4258: 							  \@fields);
                   4259: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4260: 	    chop($keyfields);
                   4261: 	} else {
                   4262: 	    unshift(@fields,['none','']);
                   4263: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4264: 							    \@fields);
1.311     banghart 4265:             foreach my $rec (@records) {
                   4266:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4267:                 if (%temp) {
                   4268:                     $keyfields=join(',',sort(keys(%temp)));
                   4269:                     last;
                   4270:                 }
                   4271:             }
1.41      ng       4272: 	}
                   4273:     }
                   4274:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4275: 
1.41      ng       4276:     return '';
1.27      albertel 4277: }
                   4278: 
1.246     albertel 4279: sub csvuploadoptions {
1.608     www      4280:     my ($request,$symb)= @_;
1.632     www      4281:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4282:     $request->print(<<ENDPICK);
                   4283: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4284: <input type="hidden" name="command"    value="csvuploadassign" />
                   4285: <p>
                   4286: <label>
                   4287:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4288:    $overwrite
1.246     albertel 4289: </label>
                   4290: </p>
                   4291: ENDPICK
                   4292:     my %fields=&get_fields();
                   4293:     if (!defined($fields{'domain'})) {
1.257     albertel 4294: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4295: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4296:     }
1.257     albertel 4297:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4298: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4299: 	my $cleankey=$1;
                   4300: 	if ($cleankey eq 'command') { next; }
                   4301: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4302: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4303:     }
                   4304:     # FIXME do a check for any duplicated user ids...
                   4305:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4306:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4307: <hr /></form>'."\n");
1.246     albertel 4308:     return '';
                   4309: }
                   4310: 
                   4311: sub get_fields {
                   4312:     my %fields;
1.257     albertel 4313:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4314:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4315: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4316: 	    if ($env{'form.f'.$i} ne 'none') {
                   4317: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4318: 	    }
                   4319: 	} else {
1.257     albertel 4320: 	    if ($env{'form.f'.$i} ne 'none') {
                   4321: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4322: 	    }
                   4323: 	}
1.27      albertel 4324:     }
1.246     albertel 4325:     return %fields;
                   4326: }
                   4327: 
                   4328: sub csvuploadassign {
1.608     www      4329:     my ($request,$symb)= @_;
1.246     albertel 4330:     if (!$symb) {return '';}
1.345     bowersj2 4331:     my $error_msg = '';
1.246     albertel 4332:     &Apache::loncommon::load_tmp_file($request);
                   4333:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4334:     my %fields=&get_fields();
1.257     albertel 4335:     my $courseid=$env{'request.course.id'};
1.97      albertel 4336:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4337:     my @notallowed;
1.41      ng       4338:     my @skipped;
1.657     raeburn  4339:     my @warnings;
1.41      ng       4340:     my $countdone=0;
                   4341:     foreach my $grade (@gradedata) {
                   4342: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4343: 	my $domain;
                   4344: 	if ($entries{$fields{'domain'}}) {
                   4345: 	    $domain=$entries{$fields{'domain'}};
                   4346: 	} else {
1.257     albertel 4347: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4348: 	}
1.243     albertel 4349: 	$domain=~s/\s//g;
1.41      ng       4350: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4351: 	$username=~s/\s//g;
1.243     albertel 4352: 	if (!$username) {
                   4353: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4354: 	    $id=~s/\s//g;
1.243     albertel 4355: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4356: 	    $username=$ids{$id};
                   4357: 	}
1.41      ng       4358: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4359: 	    my $id=$entries{$fields{'ID'}};
                   4360: 	    $id=~s/\s//g;
                   4361: 	    if ($id) {
                   4362: 		push(@skipped,"$id:$domain");
                   4363: 	    } else {
                   4364: 		push(@skipped,"$username:$domain");
                   4365: 	    }
1.41      ng       4366: 	    next;
                   4367: 	}
1.108     albertel 4368: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4369: 	if (!&canmodify($usec)) {
                   4370: 	    push(@notallowed,"$username:$domain");
                   4371: 	    next;
                   4372: 	}
1.244     albertel 4373: 	my %points;
1.41      ng       4374: 	my %grades;
                   4375: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4376: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4377: 		$dest eq 'domain') { next; }
                   4378: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4379: 	    if ($dest=~/stores_(.*)_points/) {
                   4380: 		my $part=$1;
                   4381: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4382: 					      $symb,$domain,$username);
1.345     bowersj2 4383:                 if ($wgt) {
                   4384:                     $entries{$fields{$dest}}=~s/\s//g;
                   4385:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4386:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4387:                                           : 'correct_by_override';
1.638     www      4388:                     if ($pcr>1) {
1.657     raeburn  4389:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4390:                     }
1.345     bowersj2 4391:                     $grades{"resource.$part.awarded"}=$pcr;
                   4392:                     $grades{"resource.$part.solved"}=$award;
                   4393:                     $points{$part}=1;
                   4394:                 } else {
                   4395:                     $error_msg = "<br />" .
                   4396:                         &mt("Some point values were assigned"
                   4397:                             ." for problems with a weight "
                   4398:                             ."of zero. These values were "
                   4399:                             ."ignored.");
                   4400:                 }
1.244     albertel 4401: 	    } else {
                   4402: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4403: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4404: 		my $store_key=$dest;
                   4405: 		$store_key=~s/^stores/resource/;
                   4406: 		$store_key=~s/_/\./g;
                   4407: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4408: 	    }
1.41      ng       4409: 	}
1.508     www      4410: 	if (! %grades) { 
                   4411:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4412:         } else {
                   4413: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4414: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4415: 					   $env{'request.course.id'},
                   4416: 					   $domain,$username);
1.508     www      4417: 	   if ($result eq 'ok') {
1.627     www      4418: # Successfully stored
1.508     www      4419: 	      $request->print('.');
1.627     www      4420: # Remove from grading queue
                   4421:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4422:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4423:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4424:                                              $domain,$username);
                   4425:               $countdone++;
                   4426:            } else {
1.508     www      4427: 	      $request->print("<p><span class=\"LC_error\">".
                   4428:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4429:                                   "$username:$domain",$result)."</span></p>");
                   4430: 	   }
                   4431: 	   $request->rflush();
                   4432:         }
1.41      ng       4433:     }
1.570     www      4434:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4435:     if (@warnings) {
                   4436:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4437:         $request->print(join(', ',@warnings));
                   4438:     }
1.41      ng       4439:     if (@skipped) {
1.571     www      4440: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4441:         $request->print(join(', ',@skipped));
1.106     albertel 4442:     }
                   4443:     if (@notallowed) {
1.571     www      4444: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4445: 	$request->print(join(', ',@notallowed));
1.41      ng       4446:     }
1.106     albertel 4447:     $request->print("<br />\n");
1.345     bowersj2 4448:     return $error_msg;
1.26      albertel 4449: }
1.44      ng       4450: #------------- end of section for handling csv file upload ---------
                   4451: #
                   4452: #-------------------------------------------------------------------
                   4453: #
1.122     ng       4454: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4455: #
                   4456: #--- Select a page/sequence and a student to grade
1.68      ng       4457: sub pickStudentPage {
1.608     www      4458:     my ($request,$symb) = @_;
1.68      ng       4459: 
1.539     riegler  4460:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4461:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4462: 
                   4463: function checkPickOne(formname) {
1.76      ng       4464:     if (radioSelection(formname.student) == null) {
1.539     riegler  4465: 	alert("$alertmsg");
1.68      ng       4466: 	return;
                   4467:     }
1.125     ng       4468:     ptr = pullDownSelection(formname.selectpage);
                   4469:     formname.page.value = formname["page"+ptr].value;
                   4470:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4471:     formname.submit();
                   4472: }
                   4473: 
                   4474: LISTJAVASCRIPT
1.118     ng       4475:     &commonJSfunctions($request);
1.608     www      4476: 
1.257     albertel 4477:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4478:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4479:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4480: 
1.398     albertel 4481:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4482: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4483: 
1.80      ng       4484:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4485:     my $map_error;
                   4486:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4487:     if ($map_error) {
                   4488:         $request->print(&navmap_errormsg());
                   4489:         return; 
                   4490:     }
1.137     albertel 4491:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4492: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4493: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4494: 
                   4495:     # Collection of hidden fields
1.70      ng       4496:     my $ctr=0;
1.68      ng       4497:     foreach (@$titles) {
1.700     bisitz   4498:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4499:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4500:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4501:         $ctr++;
1.68      ng       4502:     }
1.700     bisitz   4503:     $result.='<input type="hidden" name="page" />'."\n".
                   4504:         '<input type="hidden" name="title" />'."\n";
                   4505: 
                   4506:     $result.=&build_section_inputs();
                   4507:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4508:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4509: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4510: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4511: 
1.700     bisitz   4512:     # Show grading options
                   4513:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4514:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4515:     $ctr=0;
                   4516:     foreach (@$titles) {
                   4517: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4518: 	$select.='<option value="'.$ctr.'"'.
                   4519: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4520: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4521: 	$ctr++;
                   4522:     }
1.700     bisitz   4523:     $select.= '</select>';
1.68      ng       4524: 
1.700     bisitz   4525:     $result.=
                   4526:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4527:        .$select
                   4528:        .&Apache::lonhtmlcommon::row_closure();
                   4529: 
                   4530:     $result.=
                   4531:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4532:        .'<label><input type="radio" name="vProb" value="no"'
                   4533:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4534:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4535:            .&mt('yes').'</label>'."\n"
                   4536:        .&Apache::lonhtmlcommon::row_closure();
                   4537: 
                   4538:     $result.=
                   4539:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4540:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4541:            .&mt('none').' </label>'."\n"
                   4542:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4543:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4544:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4545:            .&mt('all submissions with details').' </label>'
                   4546:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4547:     
1.700     bisitz   4548:     $result.=
                   4549:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4550:        .'<input type="text" name="CODE" value="" />'
                   4551:        .&Apache::lonhtmlcommon::row_closure(1)
                   4552:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4553: 
1.700     bisitz   4554:     # Show list of students to select for grading
                   4555:     $result.='<br /><input type="button" '.
1.589     bisitz   4556:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4557: 
1.68      ng       4558:     $request->print($result);
                   4559: 
1.485     albertel 4560:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4561: 	&Apache::loncommon::start_data_table().
                   4562: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4563: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4564: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4565: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4566: 	'<th>'.&nameUserString('header').'</th>'.
                   4567: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4568:  
1.76      ng       4569:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4570:     my $ptr = 1;
1.294     albertel 4571:     foreach my $student (sort 
                   4572: 			 {
                   4573: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4574: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4575: 			     }
                   4576: 			     return $a cmp $b;
                   4577: 			 } (keys(%$fullname))) {
1.68      ng       4578: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4579: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4580:                                   : '</td>');
1.126     ng       4581: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4582: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4583: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4584: 	$studentTable.=
                   4585: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4586:                          : '');
1.68      ng       4587: 	$ptr++;
                   4588:     }
1.484     albertel 4589:     if ($ptr%2 == 0) {
                   4590: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4591: 	    &Apache::loncommon::end_data_table_row();
                   4592:     }
                   4593:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4594:     $studentTable.='<input type="button" '.
1.589     bisitz   4595:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4596: 
                   4597:     $request->print($studentTable);
                   4598: 
                   4599:     return '';
                   4600: }
                   4601: 
                   4602: sub getSymbMap {
1.582     raeburn  4603:     my ($map_error) = @_;
1.132     bowersj2 4604:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4605:     unless (ref($navmap)) {
                   4606:         if (ref($map_error)) {
                   4607:             $$map_error = 'navmap';
                   4608:         }
                   4609:         return;
                   4610:     }
1.68      ng       4611:     my %symbx = ();
                   4612:     my @titles = ();
1.117     bowersj2 4613:     my $minder = 0;
                   4614: 
                   4615:     # Gather every sequence that has problems.
1.240     albertel 4616:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4617: 					       1,0,1);
1.117     bowersj2 4618:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4619: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4620: 	    my $title = $minder.'.'.
                   4621: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4622: 	    push(@titles, $title); # minder in case two titles are identical
                   4623: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4624: 	    $minder++;
1.241     albertel 4625: 	}
1.68      ng       4626:     }
                   4627:     return \@titles,\%symbx;
                   4628: }
                   4629: 
1.72      ng       4630: #
                   4631: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4632: sub displayPage {
1.608     www      4633:     my ($request,$symb) = @_;
1.257     albertel 4634:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4635:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4636:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4637:     my $pageTitle = $env{'form.page'};
1.103     albertel 4638:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4639:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4640:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4641: 
                   4642:     #need to make sure we have the correct data for later EXT calls, 
                   4643:     #thus invalidate the cache
                   4644:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4645:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4646:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4647:     &Apache::lonnet::clear_EXT_cache_status();
                   4648: 
1.103     albertel 4649:     if (!&canview($usec)) {
1.712     bisitz   4650:         $request->print(
                   4651:             '<span class="LC_warning">'.
                   4652:             &mt('Unable to view requested student. ([_1])',
                   4653:                     $env{'form.student'}).
                   4654:             '</span>');
                   4655:         return;
1.103     albertel 4656:     }
1.398     albertel 4657:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4658:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4659: 	'</h3>'."\n";
1.500     albertel 4660:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4661:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4662: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4663:     } else {
                   4664: 	delete($env{'form.CODE'});
                   4665:     }
1.71      ng       4666:     &sub_page_js($request);
                   4667:     $request->print($result);
                   4668: 
1.132     bowersj2 4669:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4670:     unless (ref($navmap)) {
                   4671:         $request->print(&navmap_errormsg());
                   4672:         return;
                   4673:     }
1.257     albertel 4674:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4675:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4676:     if (!$map) {
1.485     albertel 4677: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4678: 	return; 
                   4679:     }
1.68      ng       4680:     my $iterator = $navmap->getIterator($map->map_start(),
                   4681: 					$map->map_finish());
                   4682: 
1.71      ng       4683:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4684: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4685: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4686: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4687: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4688: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4689: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4690: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4691: 
1.382     albertel 4692:     if (defined($env{'form.CODE'})) {
                   4693: 	$studentTable.=
                   4694: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4695:     }
1.381     albertel 4696:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4697: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4698: 
1.594     bisitz   4699:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4700:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4701:         '</span>'."\n".
1.484     albertel 4702: 	&Apache::loncommon::start_data_table().
                   4703: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4704: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4705: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4706: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4707: 
1.329     albertel 4708:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4709:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4710:     $iterator->next(); # skip the first BEGIN_MAP
                   4711:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4712:     while ($depth > 0) {
1.68      ng       4713:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4714:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4715: 
1.385     albertel 4716:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4717: 	    my $parts = $curRes->parts();
1.68      ng       4718:             my $title = $curRes->compTitle();
1.71      ng       4719: 	    my $symbx = $curRes->symb();
1.484     albertel 4720: 	    $studentTable.=
                   4721: 		&Apache::loncommon::start_data_table_row().
                   4722: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4723: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4724: 		                        : '<br />('.&mt('[_1]parts',
                   4725: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4726: 		 ).
                   4727: 		 '</td>';
1.71      ng       4728: 	    $studentTable.='<td valign="top">';
1.382     albertel 4729: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4730: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4731: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4732: 					     undef,'both',\%form);
1.71      ng       4733: 	    } else {
1.382     albertel 4734: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4735: 		$companswer =~ s|<form(.*?)>||g;
                   4736: 		$companswer =~ s|</form>||g;
1.71      ng       4737: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4738: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4739: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4740: #		}
1.116     ng       4741: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4742: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4743: 	    }
                   4744: 
1.257     albertel 4745: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4746: 
1.257     albertel 4747: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4748: 		if ($record{'version'} eq '') {
1.485     albertel 4749: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4750: 		} else {
1.116     ng       4751: 		    my %responseType = ();
                   4752: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4753: 			my @responseIds =$curRes->responseIds($partid);
                   4754: 			my @responseType =$curRes->responseType($partid);
                   4755: 			my %responseIds;
                   4756: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4757: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4758: 			}
                   4759: 			$responseType{$partid} = \%responseIds;
1.116     ng       4760: 		    }
1.148     albertel 4761: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4762: 
1.71      ng       4763: 		}
1.257     albertel 4764: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4765: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4766: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4767: 									$env{'request.course.id'},
1.71      ng       4768: 									'','.submission');
                   4769:  
                   4770: 	    }
1.103     albertel 4771: 	    if (&canmodify($usec)) {
1.585     bisitz   4772:             $studentTable.=&gradeBox_start();
1.103     albertel 4773: 		foreach my $partid (@{$parts}) {
                   4774: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4775: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4776: 		    $question++;
                   4777: 		}
1.585     bisitz   4778:             $studentTable.=&gradeBox_end();
1.196     albertel 4779: 		$prob++;
1.71      ng       4780: 	    }
                   4781: 	    $studentTable.='</td></tr>';
1.68      ng       4782: 
1.103     albertel 4783: 	}
1.68      ng       4784:         $curRes = $iterator->next();
                   4785:     }
                   4786: 
1.589     bisitz   4787:     $studentTable.=
                   4788:         '</table>'."\n".
                   4789:         '<input type="button" value="'.&mt('Save').'" '.
                   4790:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4791:         '</form>'."\n";
1.71      ng       4792:     $request->print($studentTable);
                   4793: 
                   4794:     return '';
1.119     ng       4795: }
                   4796: 
                   4797: sub displaySubByDates {
1.148     albertel 4798:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4799:     my $isCODE=0;
1.335     albertel 4800:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4801:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4802:     my $studentTable=&Apache::loncommon::start_data_table().
                   4803: 	&Apache::loncommon::start_data_table_header_row().
                   4804: 	'<th>'.&mt('Date/Time').'</th>'.
                   4805: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4806:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4807: 	'<th>'.&mt('Submission').'</th>'.
                   4808: 	'<th>'.&mt('Status').'</th>'.
                   4809: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4810:     my ($version);
                   4811:     my %mark;
1.148     albertel 4812:     my %orders;
1.119     ng       4813:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4814:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4815: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4816:     }
1.335     albertel 4817: 
                   4818:     my $interaction;
1.525     raeburn  4819:     my $no_increment = 1;
1.640     raeburn  4820:     my %lastrndseed;
1.119     ng       4821:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4822: 	my $timestamp = 
                   4823: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4824: 	if (exists($$record{$version.':resource.0.version'})) {
                   4825: 	    $interaction = $$record{$version.':resource.0.version'};
                   4826: 	}
1.671     raeburn  4827:         if ($isTask && $env{'form.previousversion'}) {
                   4828:             next unless ($interaction == $env{'form.previousversion'});
                   4829:         }
1.335     albertel 4830: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4831: 		             : "$version:resource");
1.467     albertel 4832: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4833: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4834: 	if ($isCODE) {
                   4835: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4836: 	}
1.671     raeburn  4837:         if ($isTask) {
                   4838:             $studentTable.='<td>'.$interaction.'</td>';
                   4839:         }
1.119     ng       4840: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4841: 	my @displaySub = ();
                   4842: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4843:             my ($hidden,$type);
                   4844:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4845:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4846:                 $hidden = 1;
                   4847:             }
1.335     albertel 4848: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4849: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4850: 	    
1.122     ng       4851: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4852: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4853: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4854: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4855: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4856:                     
1.335     albertel 4857: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4858: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4859:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4860:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4861:                                    .' <span class="LC_internal_info">'
1.625     www      4862:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4863:                                    .'</span>'
                   4864:                                    .' <b>';
1.596     raeburn  4865:                     if ($hidden) {
                   4866:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4867:                     } else {
1.640     raeburn  4868:                         my ($trial,$rndseed,$newvariation);
                   4869:                         if ($type eq 'randomizetry') {
                   4870:                             $trial = $$record{"$where.$partid.tries"};
                   4871:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4872:                         }
1.596     raeburn  4873: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4874: 			    $displaySub[0].=&mt('Trial not counted');
                   4875: 		        } else {
                   4876: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4877: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4878:                             if ($rndseed || $lastrndseed{$partid}) {
                   4879:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4880:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4881:                                 }
                   4882:                             }
                   4883:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4884: 		        }
                   4885: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4886:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4887: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4888: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4889: 			    $orders{$partid}->{$responseId}=
                   4890: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4891:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4892: 		        }
1.640     raeburn  4893: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4894: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4895: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4896:                     }
1.147     albertel 4897: 		}
                   4898: 	    }
1.335     albertel 4899: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4900: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4901: 				    $$record{"$where.$partid.checkedin"},
                   4902: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4903: 					'<br />';
1.335     albertel 4904: 	    }
                   4905: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4906: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4907: 		    lc($$record{"$where.$partid.award"}).' '.
                   4908: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4909: 		    '<br />';
                   4910: 	    }
1.335     albertel 4911: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4912: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4913: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4914: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4915: 		$displaySub[2].=
                   4916: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4917: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4918: 	    }
                   4919: 	}
                   4920: 	# needed because old essay regrader has not parts info
                   4921: 	if (exists $$record{"$version:resource.regrader"}) {
                   4922: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4923: 	}
                   4924: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4925: 	if ($displaySub[2]) {
1.467     albertel 4926: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4927: 	}
1.467     albertel 4928: 	$studentTable.='&nbsp;</td>'.
                   4929: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4930:     }
1.467     albertel 4931:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4932:     return $studentTable;
1.71      ng       4933: }
                   4934: 
                   4935: sub updateGradeByPage {
1.608     www      4936:     my ($request,$symb) = @_;
1.71      ng       4937: 
1.257     albertel 4938:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4939:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4940:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4941:     my $pageTitle = $env{'form.page'};
1.103     albertel 4942:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4943:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4944:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4945:     if (!&canmodify($usec)) {
1.526     raeburn  4946: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4947: 	return;
                   4948:     }
1.398     albertel 4949:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4950:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4951: 	'</h3>'."\n";
1.70      ng       4952: 
1.68      ng       4953:     $request->print($result);
                   4954: 
1.582     raeburn  4955: 
1.132     bowersj2 4956:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4957:     unless (ref($navmap)) {
                   4958:         $request->print(&navmap_errormsg());
                   4959:         return;
                   4960:     }
1.257     albertel 4961:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4962:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4963:     if (!$map) {
1.527     raeburn  4964: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4965: 	return; 
                   4966:     }
1.71      ng       4967:     my $iterator = $navmap->getIterator($map->map_start(),
                   4968: 					$map->map_finish());
1.70      ng       4969: 
1.484     albertel 4970:     my $studentTable=
                   4971: 	&Apache::loncommon::start_data_table().
                   4972: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4973: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4974: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4975: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4976: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4977: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4978: 
                   4979:     $iterator->next(); # skip the first BEGIN_MAP
                   4980:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4981:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4982:     while ($depth > 0) {
1.71      ng       4983:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4984:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4985: 
1.385     albertel 4986:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4987: 	    my $parts = $curRes->parts();
1.71      ng       4988:             my $title = $curRes->compTitle();
                   4989: 	    my $symbx = $curRes->symb();
1.484     albertel 4990: 	    $studentTable.=
                   4991: 		&Apache::loncommon::start_data_table_row().
                   4992: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4993: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4994:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4995: 		.')').'</td>';
1.71      ng       4996: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4997: 
                   4998: 	    my %newrecord=();
                   4999: 	    my @displayPts=();
1.269     raeburn  5000:             my %aggregate = ();
                   5001:             my $aggregateflag = 0;
1.71      ng       5002: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5003: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5004: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5005: 
1.257     albertel 5006: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5007: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5008: 		my $partial = $newpts/$wgt;
                   5009: 		my $score;
                   5010: 		if ($partial > 0) {
                   5011: 		    $score = 'correct_by_override';
1.125     ng       5012: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5013: 		    $score = 'incorrect_by_override';
                   5014: 		}
1.257     albertel 5015: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5016: 		if ($dropMenu eq 'excused') {
1.71      ng       5017: 		    $partial = '';
                   5018: 		    $score = 'excused';
1.125     ng       5019: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5020: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5021: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5022: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5023: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5024: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5025: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5026: 		    $changeflag++;
                   5027: 		    $newpts = '';
1.269     raeburn  5028:                     
                   5029:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5030:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5031:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5032:                     if ($aggtries > 0) {
                   5033:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5034:                         $aggregateflag = 1;
                   5035:                     }
1.71      ng       5036: 		}
1.324     albertel 5037: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5038: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5039: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5040: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5041: 		    '&nbsp;<br />';
1.526     raeburn  5042: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5043: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5044: 		    '&nbsp;<br />';
1.71      ng       5045: 		$question++;
1.380     albertel 5046: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5047: 
1.71      ng       5048: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5049: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5050: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5051: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5052: 
                   5053: 		$changeflag++;
                   5054: 	    }
                   5055: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5056: 		my %record = 
                   5057: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5058: 					     $udom,$uname);
                   5059: 
                   5060: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5061: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5062: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5063: 		    $newrecord{'resource.CODE'} = '';
                   5064: 		}
1.257     albertel 5065: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5066: 					$udom,$uname);
1.382     albertel 5067: 		%record = &Apache::lonnet::restore($symbx,
                   5068: 						   $env{'request.course.id'},
                   5069: 						   $udom,$uname);
1.380     albertel 5070: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5071: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5072: 	    }
1.380     albertel 5073: 	    
1.269     raeburn  5074:             if ($aggregateflag) {
                   5075:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5076:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5077:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5078:             }
1.125     ng       5079: 
1.71      ng       5080: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5081: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5082: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5083: 
1.196     albertel 5084: 	    $prob++;
1.68      ng       5085: 	}
1.71      ng       5086:         $curRes = $iterator->next();
1.68      ng       5087:     }
1.98      albertel 5088: 
1.484     albertel 5089:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5090:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5091: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5092: 		  $changeflag));
1.76      ng       5093:     $request->print($grademsg.$studentTable);
1.68      ng       5094: 
1.70      ng       5095:     return '';
                   5096: }
                   5097: 
1.72      ng       5098: #-------- end of section for handling grading by page/sequence ---------
                   5099: #
                   5100: #-------------------------------------------------------------------
                   5101: 
1.581     www      5102: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5103: #
                   5104: #------ start of section for handling grading by page/sequence ---------
                   5105: 
1.423     albertel 5106: =pod
                   5107: 
                   5108: =head1 Bubble sheet grading routines
                   5109: 
1.424     albertel 5110:   For this documentation:
                   5111: 
                   5112:    'scanline' refers to the full line of characters
                   5113:    from the file that we are parsing that represents one entire sheet
                   5114: 
                   5115:    'bubble line' refers to the data
1.659     raeburn  5116:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5117: 
                   5118: 
1.659     raeburn  5119: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5120: into a course. When a user wants to grade, they select a
1.659     raeburn  5121: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5122: one of the predefined configurations for what each scanline looks
                   5123: like.
                   5124: 
                   5125: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5126: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5127: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5128: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5129: invalid student/employee ID
1.424     albertel 5130: 
                   5131: If the CODE option is used that determines the randomization of the
1.556     weissno  5132: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5133: username:domain.
                   5134: 
                   5135: During the validation phase the instructor can choose to skip scanlines. 
                   5136: 
1.659     raeburn  5137: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5138: 
                   5139:   scantron_original_filename (unmodified original file)
                   5140:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5141:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5142: 
                   5143: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5144: correction information that isn't representable in the bubblesheet
1.424     albertel 5145: file (see &scantron_getfile() for more information)
                   5146: 
                   5147: After all scanlines are either valid, marked as valid or skipped, then
                   5148: foreach line foreach problem in the picked sequence, an ssi request is
                   5149: made that simulates a user submitting their selected letter(s) against
                   5150: the homework problem.
1.423     albertel 5151: 
                   5152: =over 4
                   5153: 
                   5154: 
                   5155: 
                   5156: =item defaultFormData
                   5157: 
                   5158:   Returns html hidden inputs used to hold context/default values.
                   5159: 
                   5160:  Arguments:
                   5161:   $symb - $symb of the current resource 
                   5162: 
                   5163: =cut
1.422     foxr     5164: 
1.81      albertel 5165: sub defaultFormData {
1.324     albertel 5166:     my ($symb)=@_;
1.613     www      5167:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5168: }
                   5169: 
1.447     foxr     5170: 
1.423     albertel 5171: =pod 
                   5172: 
                   5173: =item getSequenceDropDown
                   5174: 
                   5175:    Return html dropdown of possible sequences to grade
                   5176:  
                   5177:  Arguments:
1.582     raeburn  5178:    $symb - $symb of the current resource
                   5179:    $map_error - ref to scalar which will container error if
                   5180:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5181: 
                   5182: =cut
1.422     foxr     5183: 
1.75      albertel 5184: sub getSequenceDropDown {
1.582     raeburn  5185:     my ($symb,$map_error)=@_;
1.75      albertel 5186:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5187:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5188:     if (ref($map_error)) {
                   5189:         return if ($$map_error);
                   5190:     }
1.137     albertel 5191:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5192:     my $ctr=0;
                   5193:     foreach (@$titles) {
                   5194: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5195: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5196: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5197: 	    '>'.$showtitle.'</option>'."\n";
                   5198: 	$ctr++;
                   5199:     }
                   5200:     $result.= '</select>';
                   5201:     return $result;
                   5202: }
                   5203: 
1.495     albertel 5204: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5205:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5206: 
                   5207: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5208: 
1.509     raeburn  5209: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5210:                                    # matchresponse or rankresponse, where 
                   5211:                                    # an individual response can have multiple 
                   5212:                                    # lines
1.503     raeburn  5213: 
                   5214: my %responsetype_per_response;     # responsetype for each response
                   5215: 
1.691     raeburn  5216: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5217:                                    # numbered response. Needed when randomorder
                   5218:                                    # or randompick are in use. Key is ID, value 
                   5219:                                    # is response number.
                   5220: 
1.495     albertel 5221: # Save and restore the bubble lines array to the form env.
                   5222: 
                   5223: 
                   5224: sub save_bubble_lines {
                   5225:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5226: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5227: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5228: 	    $first_bubble_line{$line};
1.503     raeburn  5229:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5230:             $subdivided_bubble_lines{$line};
                   5231:         $env{"form.scantron.responsetype.$line"} =
                   5232:             $responsetype_per_response{$line};
1.495     albertel 5233:     }
1.691     raeburn  5234:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5235:         my $line = $masterseq_id_responsenum{$resid};
                   5236:         $env{"form.scantron.residpart.$line"} = $resid;
                   5237:     }
1.495     albertel 5238: }
                   5239: 
                   5240: 
                   5241: sub restore_bubble_lines {
                   5242:     my $line = 0;
                   5243:     %bubble_lines_per_response = ();
1.691     raeburn  5244:     %masterseq_id_responsenum = ();
1.495     albertel 5245:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5246: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5247: 	$bubble_lines_per_response{$line} = $value;
                   5248: 	$first_bubble_line{$line}  =
                   5249: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5250:         $subdivided_bubble_lines{$line} =
                   5251:             $env{"form.scantron.sub_bubblelines.$line"};
                   5252:         $responsetype_per_response{$line} =
                   5253:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5254:         my $id = $env{"form.scantron.residpart.$line"};
                   5255:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5256: 	$line++;
                   5257:     }
                   5258: }
                   5259: 
1.423     albertel 5260: =pod 
                   5261: 
                   5262: =item scantron_filenames
                   5263: 
                   5264:    Returns a list of the scantron files in the current course 
                   5265: 
                   5266: =cut
1.422     foxr     5267: 
1.202     albertel 5268: sub scantron_filenames {
1.257     albertel 5269:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5270:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5271:     my $getpropath = 1;
1.662     raeburn  5272:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5273:                                                         $cname,$getpropath);
1.202     albertel 5274:     my @possiblenames;
1.662     raeburn  5275:     if (ref($dirlist) eq 'ARRAY') {
                   5276:         foreach my $filename (sort(@{$dirlist})) {
                   5277: 	    ($filename)=split(/&/,$filename);
                   5278: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5279: 	    $filename=~s/^scantron_orig_//;
                   5280: 	    push(@possiblenames,$filename);
                   5281:         }
1.202     albertel 5282:     }
                   5283:     return @possiblenames;
                   5284: }
                   5285: 
1.423     albertel 5286: =pod 
                   5287: 
                   5288: =item scantron_uploads
                   5289: 
                   5290:    Returns  html drop-down list of scantron files in current course.
                   5291: 
                   5292:  Arguments:
                   5293:    $file2grade - filename to set as selected in the dropdown
                   5294: 
                   5295: =cut
1.422     foxr     5296: 
1.202     albertel 5297: sub scantron_uploads {
1.209     ng       5298:     my ($file2grade) = @_;
1.202     albertel 5299:     my $result=	'<select name="scantron_selectfile">';
                   5300:     $result.="<option></option>";
                   5301:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5302: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5303:     }
                   5304:     $result.="</select>";
                   5305:     return $result;
                   5306: }
                   5307: 
1.423     albertel 5308: =pod 
                   5309: 
                   5310: =item scantron_scantab
                   5311: 
                   5312:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5313:   file.
                   5314: 
                   5315: =cut
1.422     foxr     5316: 
1.82      albertel 5317: sub scantron_scantab {
                   5318:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5319:     $result.='<option></option>'."\n";
1.518     raeburn  5320:     my @lines = &get_scantronformat_file();
                   5321:     if (@lines > 0) {
                   5322:         foreach my $line (@lines) {
                   5323:             next if (($line =~ /^\#/) || ($line eq ''));
                   5324: 	    my ($name,$descrip)=split(/:/,$line);
                   5325: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5326:         }
1.82      albertel 5327:     }
                   5328:     $result.='</select>'."\n";
1.518     raeburn  5329:     return $result;
                   5330: }
                   5331: 
                   5332: =pod
                   5333: 
                   5334: =item get_scantronformat_file
                   5335: 
                   5336:   Returns an array containing lines from the scantron format file for
                   5337:   the domain of the course.
                   5338: 
                   5339:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5340:   lines are from this file.
                   5341: 
                   5342:   Otherwise, if a default.tab has been published in RES space by the 
                   5343:   domainconfig user, lines are from this file.
                   5344: 
                   5345:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5346:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5347: 
1.518     raeburn  5348: =cut
                   5349: 
                   5350: sub get_scantronformat_file {
                   5351:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5352:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5353:     my $gottab = 0;
                   5354:     my @lines;
                   5355:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5356:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5357:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5358:             if ($formatfile ne '-1') {
                   5359:                 @lines = split("\n",$formatfile,-1);
                   5360:                 $gottab = 1;
                   5361:             }
                   5362:         }
                   5363:     }
                   5364:     if (!$gottab) {
                   5365:         my $confname = $cdom.'-domainconfig';
                   5366:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5367:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5368:         if ($formatfile ne '-1') {
                   5369:             @lines = split("\n",$formatfile,-1);
                   5370:             $gottab = 1;
                   5371:         }
                   5372:     }
                   5373:     if (!$gottab) {
1.519     raeburn  5374:         my @domains = &Apache::lonnet::current_machine_domains();
                   5375:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5376:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5377:             @lines = <$fh>;
                   5378:             close($fh);
                   5379:         } else {
                   5380:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5381:             @lines = <$fh>;
                   5382:             close($fh);
                   5383:         }
1.518     raeburn  5384:     }
                   5385:     return @lines;
1.82      albertel 5386: }
                   5387: 
1.423     albertel 5388: =pod 
                   5389: 
                   5390: =item scantron_CODElist
                   5391: 
                   5392:   Returns html drop down of the saved CODE lists from current course,
                   5393:   generated from earlier printings.
                   5394: 
                   5395: =cut
1.422     foxr     5396: 
1.186     albertel 5397: sub scantron_CODElist {
1.257     albertel 5398:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5399:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5400:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5401:     my $namechoice='<option></option>';
1.225     albertel 5402:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5403: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5404: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5405: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5406:     }
                   5407:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5408:     return $namechoice;
                   5409: }
                   5410: 
1.423     albertel 5411: =pod 
                   5412: 
                   5413: =item scantron_CODEunique
                   5414: 
                   5415:   Returns the html for "Each CODE to be used once" radio.
                   5416: 
                   5417: =cut
1.422     foxr     5418: 
1.186     albertel 5419: sub scantron_CODEunique {
1.532     bisitz   5420:     my $result='<span class="LC_nobreak">
1.272     albertel 5421:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5422:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5423:                 </span>
1.532     bisitz   5424:                 <span class="LC_nobreak">
1.272     albertel 5425:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5426:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5427:                 </span>';
1.186     albertel 5428:     return $result;
                   5429: }
1.423     albertel 5430: 
                   5431: =pod 
                   5432: 
                   5433: =item scantron_selectphase
                   5434: 
1.659     raeburn  5435:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5436:   Allows for - starting a grading run.
1.424     albertel 5437:              - downloading existing scan data (original, corrected
1.423     albertel 5438:                                                 or skipped info)
                   5439: 
                   5440:              - uploading new scan data
                   5441: 
                   5442:  Arguments:
                   5443:   $r          - The Apache request object
                   5444:   $file2grade - name of the file that contain the scanned data to score
                   5445: 
                   5446: =cut
1.186     albertel 5447: 
1.75      albertel 5448: sub scantron_selectphase {
1.608     www      5449:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5450:     if (!$symb) {return '';}
1.582     raeburn  5451:     my $map_error;
                   5452:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5453:     if ($map_error) {
                   5454:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5455:         return;
                   5456:     }
1.324     albertel 5457:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5458:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5459:     my $format_selector=&scantron_scantab();
1.186     albertel 5460:     my $CODE_selector=&scantron_CODElist();
                   5461:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5462:     my $result;
1.422     foxr     5463: 
1.513     foxr     5464:     $ssi_error = 0;
                   5465: 
1.606     wenzelju 5466:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5467:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5468: 
                   5469: 	# Chunk of form to prompt for a scantron file upload.
                   5470: 
                   5471:         $r->print('
                   5472:     <br />
                   5473:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5474:        '.&Apache::loncommon::start_data_table_header_row().'
                   5475:             <th>
                   5476:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5477:             </th>
                   5478:        '.&Apache::loncommon::end_data_table_header_row().'
                   5479:        '.&Apache::loncommon::start_data_table_row().'
                   5480:             <td>
                   5481: ');
1.608     www      5482:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5483:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5484:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5485:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5486:     function checkUpload(formname) {
                   5487: 	if (formname.upfile.value == "") {
                   5488: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5489: 	    return false;
                   5490: 	}
                   5491: 	formname.submit();
                   5492:     }'));
                   5493:     $r->print('
                   5494:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5495:                 '.$default_form_data.'
                   5496:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5497:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5498:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5499:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5500:                 <br />
                   5501:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5502:               </form>
                   5503: ');
                   5504: 
                   5505:         $r->print('
                   5506:             </td>
                   5507:        '.&Apache::loncommon::end_data_table_row().'
                   5508:        '.&Apache::loncommon::end_data_table().'
                   5509: ');
                   5510:     }
                   5511: 
1.422     foxr     5512:     # Chunk of form to prompt for a file to grade and how:
                   5513: 
1.489     albertel 5514:     $result.= '
                   5515:     <br />
                   5516:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5517:     <input type="hidden" name="command" value="scantron_warning" />
                   5518:     '.$default_form_data.'
                   5519:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5520:        '.&Apache::loncommon::start_data_table_header_row().'
                   5521:             <th colspan="2">
1.492     albertel 5522:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5523:             </th>
                   5524:        '.&Apache::loncommon::end_data_table_header_row().'
                   5525:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5526:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5527:        '.&Apache::loncommon::end_data_table_row().'
                   5528:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5529:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5530:        '.&Apache::loncommon::end_data_table_row().'
                   5531:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5532:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5533:        '.&Apache::loncommon::end_data_table_row().'
                   5534:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5535:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5536:        '.&Apache::loncommon::end_data_table_row().'
                   5537:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5538:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5539:        '.&Apache::loncommon::end_data_table_row().'
                   5540:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5541: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5542:             <td>
1.492     albertel 5543: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5544:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5545:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5546: 	    </td>
1.489     albertel 5547:        '.&Apache::loncommon::end_data_table_row().'
                   5548:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5549:             <td colspan="2">
1.572     www      5550:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5551:             </td>
1.489     albertel 5552:        '.&Apache::loncommon::end_data_table_row().'
                   5553:     '.&Apache::loncommon::end_data_table().'
                   5554:     </form>
                   5555: ';
1.162     albertel 5556:    
                   5557:     $r->print($result);
                   5558: 
1.422     foxr     5559: 
                   5560: 
                   5561:     # Chunk of the form that prompts to view a scoring office file,
                   5562:     # corrected file, skipped records in a file.
                   5563: 
1.489     albertel 5564:     $r->print('
                   5565:    <br />
                   5566:    <form action="/adm/grades" name="scantron_download">
                   5567:      '.$default_form_data.'
                   5568:      <input type="hidden" name="command" value="scantron_download" />
                   5569:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5570:        '.&Apache::loncommon::start_data_table_header_row().'
                   5571:               <th>
1.492     albertel 5572:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5573:               </th>
                   5574:        '.&Apache::loncommon::end_data_table_header_row().'
                   5575:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5576:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5577:                 <br />
1.492     albertel 5578:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5579:        '.&Apache::loncommon::end_data_table_row().'
                   5580:      '.&Apache::loncommon::end_data_table().'
                   5581:    </form>
                   5582:    <br />
                   5583: ');
1.162     albertel 5584: 
1.457     banghart 5585:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5586: 
1.694     bisitz   5587:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5588:              $default_form_data."\n".
                   5589:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5590:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5591:              '<th colspan="2">
1.572     www      5592:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5593:              '</th>'."\n".
                   5594:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5595:               &Apache::loncommon::start_data_table_row()."\n".
                   5596:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5597:               '<td> '.$sequence_selector.' </td>'.
                   5598:               &Apache::loncommon::end_data_table_row()."\n".
                   5599:               &Apache::loncommon::start_data_table_row()."\n".
                   5600:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5601:               '<td> '.$file_selector.' </td>'."\n".
                   5602:               &Apache::loncommon::end_data_table_row()."\n".
                   5603:               &Apache::loncommon::start_data_table_row()."\n".
                   5604:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5605:               '<td> '.$format_selector.' </td>'."\n".
                   5606:               &Apache::loncommon::end_data_table_row()."\n".
                   5607:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5608:               '<td> '.&mt('Options').' </td>'."\n".
                   5609:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5610:               &Apache::loncommon::end_data_table_row()."\n".
                   5611:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5612:               '<td colspan="2">'."\n".
                   5613:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5614:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5615:               '</td>'."\n".
                   5616:               &Apache::loncommon::end_data_table_row()."\n".
                   5617:               &Apache::loncommon::end_data_table()."\n".
                   5618:               '</form><br />');
                   5619:     return;
1.75      albertel 5620: }
                   5621: 
1.423     albertel 5622: =pod
                   5623: 
                   5624: =item get_scantron_config
                   5625: 
1.711     bisitz   5626:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5627:    hash of configuration file fields.
                   5628: 
                   5629:  Arguments:
                   5630:     which - the name of the configuration to parse from the file.
                   5631: 
                   5632: 
                   5633:  Returns:
                   5634:             If the named configuration is not in the file, an empty
                   5635:             hash is returned.
                   5636:     a hash with the fields
                   5637:       name         - internal name for the this configuration setup
                   5638:       description  - text to display to operator that describes this config
                   5639:       CODElocation - if 0 or the string 'none'
                   5640:                           - no CODE exists for this config
                   5641:                      if -1 || the string 'letter'
                   5642:                           - a CODE exists for this config and is
                   5643:                             a string of letters
                   5644:                      Unsupported value (but planned for future support)
                   5645:                           if a positive integer
                   5646:                                - The CODE exists as the first n items from
                   5647:                                  the question section of the form
                   5648:                           if the string 'number'
                   5649:                                - The CODE exists for this config and is
                   5650:                                  a string of numbers
                   5651:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5652:                      the CODE starts
                   5653:       CODElength  - length of the CODE
1.573     bisitz   5654:       IDstart     - column where the student/employee ID starts
1.556     weissno  5655:       IDlength    - length of the student/employee ID info
1.423     albertel 5656:       Qstart      - column where the information from the bubbled
                   5657:                     'questions' start
                   5658:       Qlength     - number of columns comprising a single bubble line from
                   5659:                     the sheet. (usually either 1 or 10)
1.424     albertel 5660:       Qon         - either a single character representing the character used
1.423     albertel 5661:                     to signal a bubble was chosen in the positional setup, or
                   5662:                     the string 'letter' if the letter of the chosen bubble is
                   5663:                     in the final, or 'number' if a number representing the
                   5664:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5665:       Qoff        - the character used to represent that a bubble was
                   5666:                     left blank
1.423     albertel 5667:       PaperID     - if the scanning process generates a unique number for each
                   5668:                     sheet scanned the column that this ID number starts in
                   5669:       PaperIDlength - number of columns that comprise the unique ID number
                   5670:                       for the sheet of paper
1.424     albertel 5671:       FirstName   - column that the first name starts in
1.423     albertel 5672:       FirstNameLength - number of columns that the first name spans
                   5673:  
                   5674:       LastName    - column that the last name starts in
                   5675:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5676:       BubblesPerRow - number of bubbles available in each row used to 
                   5677:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5678: 
1.423     albertel 5679: =cut
1.422     foxr     5680: 
1.82      albertel 5681: sub get_scantron_config {
                   5682:     my ($which) = @_;
1.518     raeburn  5683:     my @lines = &get_scantronformat_file();
1.82      albertel 5684:     my %config;
1.157     albertel 5685:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5686:     foreach my $line (@lines) {
1.82      albertel 5687: 	my ($name,$descrip)=split(/:/,$line);
                   5688: 	if ($name ne $which ) { next; }
                   5689: 	chomp($line);
                   5690: 	my @config=split(/:/,$line);
                   5691: 	$config{'name'}=$config[0];
                   5692: 	$config{'description'}=$config[1];
                   5693: 	$config{'CODElocation'}=$config[2];
                   5694: 	$config{'CODEstart'}=$config[3];
                   5695: 	$config{'CODElength'}=$config[4];
                   5696: 	$config{'IDstart'}=$config[5];
                   5697: 	$config{'IDlength'}=$config[6];
                   5698: 	$config{'Qstart'}=$config[7];
1.497     foxr     5699:  	$config{'Qlength'}=$config[8];
1.82      albertel 5700: 	$config{'Qoff'}=$config[9];
                   5701: 	$config{'Qon'}=$config[10];
1.157     albertel 5702: 	$config{'PaperID'}=$config[11];
                   5703: 	$config{'PaperIDlength'}=$config[12];
                   5704: 	$config{'FirstName'}=$config[13];
                   5705: 	$config{'FirstNamelength'}=$config[14];
                   5706: 	$config{'LastName'}=$config[15];
                   5707: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5708:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5709: 	last;
                   5710:     }
                   5711:     return %config;
                   5712: }
                   5713: 
1.423     albertel 5714: =pod 
                   5715: 
                   5716: =item username_to_idmap
                   5717: 
1.556     weissno  5718:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5719:     student username:domain.
                   5720: 
                   5721:   Arguments:
                   5722: 
                   5723:     $classlist - reference to the class list hash. This is a hash
                   5724:                  keyed by student name:domain  whose elements are references
1.424     albertel 5725:                  to arrays containing various chunks of information
1.423     albertel 5726:                  about the student. (See loncoursedata for more info).
                   5727: 
                   5728:   Returns
                   5729:     %idmap - the constructed hash
                   5730: 
                   5731: =cut
                   5732: 
1.82      albertel 5733: sub username_to_idmap {
                   5734:     my ($classlist)= @_;
                   5735:     my %idmap;
                   5736:     foreach my $student (keys(%$classlist)) {
                   5737: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5738: 	    $student;
                   5739:     }
                   5740:     return %idmap;
                   5741: }
1.423     albertel 5742: 
                   5743: =pod
                   5744: 
1.424     albertel 5745: =item scantron_fixup_scanline
1.423     albertel 5746: 
                   5747:    Process a requested correction to a scanline.
                   5748: 
                   5749:   Arguments:
                   5750:     $scantron_config   - hash from &get_scantron_config()
                   5751:     $scan_data         - hash of correction information 
                   5752:                           (see &scantron_getfile())
                   5753:     $line              - existing scanline
                   5754:     $whichline         - line number of the passed in scanline
                   5755:     $field             - type of change to process 
                   5756:                          (either 
1.573     bisitz   5757:                           'ID'     -> correct the student/employee ID
1.423     albertel 5758:                           'CODE'   -> correct the CODE
                   5759:                           'answer' -> fixup the submitted answers)
                   5760:     
                   5761:    $args               - hash of additional info,
                   5762:                           - 'ID' 
                   5763:                                'newid' -> studentID to use in replacement
1.424     albertel 5764:                                           of existing one
1.423     albertel 5765:                           - 'CODE' 
                   5766:                                'CODE_ignore_dup' - set to true if duplicates
                   5767:                                                    should be ignored.
                   5768: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5769:                                         if the existing unfound code should
1.423     albertel 5770:                                         be used as is
                   5771:                           - 'answer'
                   5772:                                'response' - new answer or 'none' if blank
                   5773:                                'question' - the bubble line to change
1.503     raeburn  5774:                                'questionnum' - the question identifier,
                   5775:                                                may include subquestion. 
1.423     albertel 5776: 
                   5777:   Returns:
                   5778:     $line - the modified scanline
                   5779: 
                   5780:   Side effects: 
                   5781:     $scan_data - may be updated
                   5782: 
                   5783: =cut
                   5784: 
1.82      albertel 5785: 
1.157     albertel 5786: sub scantron_fixup_scanline {
                   5787:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5788:     if ($field eq 'ID') {
                   5789: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5790: 	    return ($line,1,'New value too large');
1.157     albertel 5791: 	}
                   5792: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5793: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5794: 				     $args->{'newid'});
                   5795: 	}
                   5796: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5797: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5798: 	if ($args->{'newid'}=~/^\s*$/) {
                   5799: 	    &scan_data($scan_data,"$whichline.user",
                   5800: 		       $args->{'username'}.':'.$args->{'domain'});
                   5801: 	}
1.186     albertel 5802:     } elsif ($field eq 'CODE') {
1.192     albertel 5803: 	if ($args->{'CODE_ignore_dup'}) {
                   5804: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5805: 	}
                   5806: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5807: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5808: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5809: 		return ($line,1,'New CODE value too large');
                   5810: 	    }
                   5811: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5812: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5813: 	    }
                   5814: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5815: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5816: 	}
1.157     albertel 5817:     } elsif ($field eq 'answer') {
1.497     foxr     5818: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5819: 	my $off=$scantron_config->{'Qoff'};
                   5820: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5821: 	my $answer=${off}x$length;
                   5822: 	if ($args->{'response'} eq 'none') {
                   5823: 	    &scan_data($scan_data,
1.503     raeburn  5824: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5825: 	} else {
                   5826: 	    if ($on eq 'letter') {
                   5827: 		my @alphabet=('A'..'Z');
                   5828: 		$answer=$alphabet[$args->{'response'}];
                   5829: 	    } elsif ($on eq 'number') {
                   5830: 		$answer=$args->{'response'}+1;
                   5831: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5832: 	    } else {
1.497     foxr     5833: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5834: 	    }
1.497     foxr     5835: 	    &scan_data($scan_data,
1.503     raeburn  5836: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5837: 	}
1.497     foxr     5838: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5839: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5840:     }
                   5841:     return $line;
                   5842: }
1.423     albertel 5843: 
                   5844: =pod
                   5845: 
                   5846: =item scan_data
                   5847: 
                   5848:     Edit or look up  an item in the scan_data hash.
                   5849: 
                   5850:   Arguments:
                   5851:     $scan_data  - The hash (see scantron_getfile)
                   5852:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5853:                   scantronfilename_key).
1.423     albertel 5854:     $data        - New value of the hash entry.
                   5855:     $delete      - If true, the entry is removed from the hash.
                   5856: 
                   5857:   Returns:
                   5858:     The new value of the hash table field (undefined if deleted).
                   5859: 
                   5860: =cut
                   5861: 
                   5862: 
1.157     albertel 5863: sub scan_data {
                   5864:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5865:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5866:     if (defined($value)) {
                   5867: 	$scan_data->{$filename.'_'.$key} = $value;
                   5868:     }
                   5869:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5870:     return $scan_data->{$filename.'_'.$key};
                   5871: }
1.423     albertel 5872: 
1.495     albertel 5873: # ----- These first few routines are general use routines.----
                   5874: 
                   5875: # Return the number of occurences of a pattern in a string.
                   5876: 
                   5877: sub occurence_count {
                   5878:     my ($string, $pattern) = @_;
                   5879: 
                   5880:     my @matches = ($string =~ /$pattern/g);
                   5881: 
                   5882:     return scalar(@matches);
                   5883: }
                   5884: 
                   5885: 
                   5886: # Take a string known to have digits and convert all the
                   5887: # digits into letters in the range J,A..I.
                   5888: 
                   5889: sub digits_to_letters {
                   5890:     my ($input) = @_;
                   5891: 
                   5892:     my @alphabet = ('J', 'A'..'I');
                   5893: 
                   5894:     my @input    = split(//, $input);
                   5895:     my $output ='';
                   5896:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5897: 	if ($input[$i] =~ /\d/) {
                   5898: 	    $output .= $alphabet[$input[$i]];
                   5899: 	} else {
                   5900: 	    $output .= $input[$i];
                   5901: 	}
                   5902:     }
                   5903:     return $output;
                   5904: }
                   5905: 
1.423     albertel 5906: =pod 
                   5907: 
                   5908: =item scantron_parse_scanline
                   5909: 
1.711     bisitz   5910:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5911: 
                   5912:  Arguments:
1.711     bisitz   5913:     line             - The text of the bubblesheet file line to process
1.423     albertel 5914:     whichline        - Line number
1.711     bisitz   5915:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5916:     scan_data        - Hash of extra information about the scanline
                   5917:                        (see scantron_getfile for more information)
                   5918:     just_header      - True if should not process question answers but only
                   5919:                        the stuff to the left of the answers.
1.691     raeburn  5920:     randomorder      - True if randomorder in use
                   5921:     randompick       - True if randompick in use
                   5922:     sequence         - Exam folder URL
                   5923:     master_seq       - Ref to array containing symbs in exam folder
                   5924:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5925:                        (corresponding values are resource objects)
                   5926:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5927:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5928:                        are refs to an array of resource objects, ordered
                   5929:                        according to order used for CODE, when randomorder
                   5930:                        and or randompick are in use.
                   5931:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5932:                        for current line to question number used for same question
                   5933:                         in "Master Sequence" (as seen by Course Coordinator).
                   5934:     startline        - Ref to hash where key is question number (0 is first)
                   5935:                        and value is number of first bubble line for current 
                   5936:                        student or code-based randompick and/or randomorder.
                   5937:     totalref         - Ref of scalar used to score total number of bubble
                   5938:                        lines needed for responses in a scan line (used when
                   5939:                        randompick in use. 
                   5940:     
1.423     albertel 5941:  Returns:
                   5942:    Hash containing the result of parsing the scanline
                   5943: 
                   5944:    Keys are all proceeded by the string 'scantron.'
                   5945: 
                   5946:        CODE    - the CODE in use for this scanline
                   5947:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5948:                  by the operator
                   5949:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5950:                             CODEs were selected, but the usage has been
                   5951:                             forced by the operator
1.556     weissno  5952:        ID  - student/employee ID
1.423     albertel 5953:        PaperID - if used, the ID number printed on the sheet when the 
                   5954:                  paper was scanned
                   5955:        FirstName - first name from the sheet
                   5956:        LastName  - last name from the sheet
                   5957: 
                   5958:      if just_header was not true these key may also exist
                   5959: 
1.447     foxr     5960:        missingerror - a list of bubble ranges that are considered to be answers
                   5961:                       to a single question that don't have any bubbles filled in.
                   5962:                       Of the form questionnumber:firstbubblenumber:count.
                   5963:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5964:                       to a single question that have more than one bubble filled in.
                   5965:                       Of the form questionnumber::firstbubblenumber:count
                   5966:    
                   5967:                 In the above, count is the number of bubble responses in the
                   5968:                 input line needed to represent the possible answers to the question.
                   5969:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5970:                 per line would have count = 2.
                   5971: 
1.423     albertel 5972:        maxquest     - the number of the last bubble line that was parsed
                   5973: 
                   5974:        (<number> starts at 1)
                   5975:        <number>.answer - zero or more letters representing the selected
                   5976:                          letters from the scanline for the bubble line 
                   5977:                          <number>.
                   5978:                          if blank there was either no bubble or there where
                   5979:                          multiple bubbles, (consult the keys missingerror and
                   5980:                          doubleerror if this is an error condition)
                   5981: 
                   5982: =cut
                   5983: 
1.82      albertel 5984: sub scantron_parse_scanline {
1.691     raeburn  5985:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5986:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5987:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5988: 
1.82      albertel 5989:     my %record;
1.691     raeburn  5990:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 5991:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5992: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5993: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5994: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5995: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5996: 	    $record{'scantron.CODE'}=substr($data,
                   5997: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5998: 					    $$scantron_config{'CODElength'});
1.191     albertel 5999: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6000: 		$record{'scantron.useCODE'}=1;
                   6001: 	    }
1.192     albertel 6002: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6003: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6004: 	    }
1.82      albertel 6005: 	} else {
                   6006: 	    #FIXME interpret first N questions
                   6007: 	}
                   6008:     }
1.83      albertel 6009:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6010: 				  $$scantron_config{'IDlength'});
1.157     albertel 6011:     $record{'scantron.PaperID'}=
                   6012: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6013: 	       $$scantron_config{'PaperIDlength'});
                   6014:     $record{'scantron.FirstName'}=
                   6015: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6016: 	       $$scantron_config{'FirstNamelength'});
                   6017:     $record{'scantron.LastName'}=
                   6018: 	substr($data,$$scantron_config{'LastName'}-1,
                   6019: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6020:     if ($just_header) { return \%record; }
1.194     albertel 6021: 
1.82      albertel 6022:     my @alphabet=('A'..'Z');
                   6023:     my $questnum=0;
1.447     foxr     6024:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6025: 
1.691     raeburn  6026:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6027:     if ($randompick || $randomorder) {
                   6028:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6029:                                          $master_seq,$symb_to_resource,
                   6030:                                          $partids_by_symb,$orderedforcode,
                   6031:                                          $respnumlookup,$startline);
                   6032:         if ($total) {
                   6033:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6034:         }
                   6035:         if (ref($totalref)) {
                   6036:             $$totalref = $total;
                   6037:         }
                   6038:     }
                   6039:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6040:     chomp($questions);		# Get rid of any trailing \n.
                   6041:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6042:     while (length($questions)) {
1.691     raeburn  6043:         my $answers_needed;
                   6044:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6045:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6046:         } else {
                   6047: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6048:         }
1.503     raeburn  6049:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6050:                              || 1;
                   6051:         $questnum++;
                   6052:         my $quest_id = $questnum;
                   6053:         my $currentquest = substr($questions,0,$answer_length);
                   6054:         $questions       = substr($questions,$answer_length);
                   6055:         if (length($currentquest) < $answer_length) { next; }
                   6056: 
1.691     raeburn  6057:         my $subdivided;
                   6058:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6059:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6060:         } else {
                   6061:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6062:         }
                   6063:         if ($subdivided =~ /,/) {
1.503     raeburn  6064:             my $subquestnum = 1;
                   6065:             my $subquestions = $currentquest;
1.691     raeburn  6066:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6067:             foreach my $subans (@subanswers_needed) {
                   6068:                 my $subans_length =
                   6069:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6070:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6071:                 $subquestions   = substr($subquestions,$subans_length);
                   6072:                 $quest_id = "$questnum.$subquestnum";
                   6073:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6074:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6075:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6076:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6077:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6078:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6079:                 } else {
                   6080:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6081:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6082:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6083:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6084:                 }
                   6085:                 $subquestnum ++;
                   6086:             }
                   6087:         } else {
                   6088:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6089:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6090:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6091:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6092:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6093:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6094:             } else {
                   6095:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6096:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6097:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6098:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6099:             }
                   6100:         }
                   6101:     }
                   6102:     $record{'scantron.maxquest'}=$questnum;
                   6103:     return \%record;
                   6104: }
1.447     foxr     6105: 
1.691     raeburn  6106: sub get_master_seq {
                   6107:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6108:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6109:                    (ref($symb_to_resource) eq 'HASH'));
                   6110:     my $resource_error;
                   6111:     foreach my $resource (@{$resources}) {
                   6112:         my $ressymb;
                   6113:         if (ref($resource)) {
                   6114:             $ressymb = $resource->symb();
                   6115:             push(@{$master_seq},$ressymb);
                   6116:             $symb_to_resource->{$ressymb} = $resource;
                   6117:         } else {
                   6118:             $resource_error = 1;
                   6119:             last;
                   6120:         }
                   6121:     }
                   6122:     return $resource_error;
                   6123: }
                   6124: 
                   6125: sub get_respnum_lookups {
                   6126:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6127:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6128:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6129:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6130:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6131:                    (ref($startline) eq 'HASH'));
                   6132:     my ($user,$scancode);
                   6133:     if ((exists($record->{'scantron.CODE'})) &&
                   6134:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6135:         $scancode = $record->{'scantron.CODE'};
                   6136:     } else {
                   6137:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6138:     }
                   6139:     my @mapresources =
                   6140:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6141:                      $orderedforcode);
                   6142:     my $total = 0;
                   6143:     my $count = 0;
                   6144:     foreach my $resource (@mapresources) {
                   6145:         my $id = $resource->id();
                   6146:         my $symb = $resource->symb();
                   6147:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6148:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6149:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6150:                 if ($respnum ne '') {
                   6151:                     $respnumlookup->{$count} = $respnum;
                   6152:                     $startline->{$count} = $total;
                   6153:                     $total += $bubble_lines_per_response{$respnum};
                   6154:                     $count ++;
                   6155:                 }
                   6156:             }
                   6157:         }
                   6158:     }
                   6159:     return $total;
                   6160: }
                   6161: 
1.503     raeburn  6162: sub scantron_validator_lettnum {
                   6163:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6164:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6165:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6166: 
                   6167:     # Qon 'letter' implies for each slot in currquest we have:
                   6168:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6169:     #    about anything else (esp. a value of Qoff) for missing
                   6170:     #    bubbles.
                   6171:     #
                   6172:     # Qon 'number' implies each slot gives a digit that indexes the
                   6173:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6174:     #    and * or ? for double bubbles on a single line.
                   6175:     #
1.447     foxr     6176: 
1.503     raeburn  6177:     my $matchon;
                   6178:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6179:         $matchon = '[A-Z]';
                   6180:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6181:         $matchon = '\d';
                   6182:     }
                   6183:     my $occurrences = 0;
1.691     raeburn  6184:     my $responsenum = $questnum-1;
                   6185:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6186:        $responsenum = $respnumlookup->{$questnum-1} 
                   6187:     }
                   6188:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6189:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6190:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6191:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6192:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6193:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6194:         my @singlelines = split('',$currquest);
                   6195:         foreach my $entry (@singlelines) {
                   6196:             $occurrences = &occurence_count($entry,$matchon);
                   6197:             if ($occurrences > 1) {
                   6198:                 last;
                   6199:             }
1.691     raeburn  6200:         }
1.503     raeburn  6201:     } else {
                   6202:         $occurrences = &occurence_count($currquest,$matchon); 
                   6203:     }
                   6204:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6205:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6206:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6207:             my $bubble = substr($currquest,$ans,1);
                   6208:             if ($bubble =~ /$matchon/ ) {
                   6209:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6210:                     if ($bubble == 0) {
                   6211:                         $bubble = 10; 
                   6212:                     }
                   6213:                     $record->{"scantron.$ansnum.answer"} = 
                   6214:                         $alphabet->[$bubble-1];
                   6215:                 } else {
                   6216:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6217:                 }
                   6218:             } else {
                   6219:                 $record->{"scantron.$ansnum.answer"}='';
                   6220:             }
                   6221:             $ansnum++;
                   6222:         }
                   6223:     } elsif (!defined($currquest)
                   6224:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6225:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6226:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6227:             $record->{"scantron.$ansnum.answer"}='';
                   6228:             $ansnum++;
                   6229:         }
                   6230:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6231:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6232:         }
                   6233:     } else {
                   6234:         if ($$scantron_config{'Qon'} eq 'number') {
                   6235:             $currquest = &digits_to_letters($currquest);            
                   6236:         }
                   6237:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6238:             my $bubble = substr($currquest,$ans,1);
                   6239:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6240:             $ansnum++;
                   6241:         }
                   6242:     }
                   6243:     return $ansnum;
                   6244: }
1.447     foxr     6245: 
1.503     raeburn  6246: sub scantron_validator_positional {
                   6247:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6248:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6249:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6250: 
1.503     raeburn  6251:     # Otherwise there's a positional notation;
                   6252:     # each bubble line requires Qlength items, and there are filled in
                   6253:     # bubbles for each case where there 'Qon' characters.
                   6254:     #
1.447     foxr     6255: 
1.503     raeburn  6256:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6257: 
1.503     raeburn  6258:     # If the split only gives us one element.. the full length of the
                   6259:     # answer string, no bubbles are filled in:
1.447     foxr     6260: 
1.507     raeburn  6261:     if ($answers_needed eq '') {
                   6262:         return;
                   6263:     }
                   6264: 
1.503     raeburn  6265:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6266:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6267:             $record->{"scantron.$ansnum.answer"}='';
                   6268:             $ansnum++;
                   6269:         }
                   6270:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6271:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6272:         }
                   6273:     } elsif (scalar(@array) == 2) {
                   6274:         my $location = length($array[0]);
                   6275:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6276:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6277:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6278:             if ($ans eq $line_num) {
                   6279:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6280:             } else {
                   6281:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6282:             }
                   6283:             $ansnum++;
                   6284:          }
                   6285:     } else {
                   6286:         #  If there's more than one instance of a bubble character
                   6287:         #  That's a double bubble; with positional notation we can
                   6288:         #  record all the bubbles filled in as well as the
                   6289:         #  fact this response consists of multiple bubbles.
                   6290:         #
1.691     raeburn  6291:         my $responsenum = $questnum-1;
                   6292:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6293:             $responsenum = $respnumlookup->{$questnum-1}
                   6294:         }
                   6295:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6296:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6297:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6298:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6299:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6300:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6301:             my $doubleerror = 0;
                   6302:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6303:                    (!$doubleerror)) {
                   6304:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6305:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6306:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6307:                if (length(@currarray) > 2) {
                   6308:                    $doubleerror = 1;
                   6309:                } 
                   6310:             }
                   6311:             if ($doubleerror) {
                   6312:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6313:             }
                   6314:         } else {
                   6315:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6316:         }
                   6317:         my $item = $ansnum;
                   6318:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6319:             $record->{"scantron.$item.answer"} = '';
                   6320:             $item ++;
                   6321:         }
1.447     foxr     6322: 
1.503     raeburn  6323:         my @ans=@array;
                   6324:         my $i=0;
                   6325:         my $increment = 0;
                   6326:         while ($#ans) {
                   6327:             $i+=length($ans[0]) + $increment;
                   6328:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6329:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6330:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6331:             shift(@ans);
                   6332:             $increment = 1;
                   6333:         }
                   6334:         $ansnum += $answers_needed;
1.82      albertel 6335:     }
1.503     raeburn  6336:     return $ansnum;
1.82      albertel 6337: }
                   6338: 
1.423     albertel 6339: =pod
                   6340: 
                   6341: =item scantron_add_delay
                   6342: 
                   6343:    Adds an error message that occurred during the grading phase to a
                   6344:    queue of messages to be shown after grading pass is complete
                   6345: 
                   6346:  Arguments:
1.424     albertel 6347:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6348:    $scanline    - the scanline that caused the error
                   6349:    $errormesage - the error message
                   6350:    $errorcode   - a numeric code for the error
                   6351: 
                   6352:  Side Effects:
1.424     albertel 6353:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6354: 
                   6355: =cut
                   6356: 
1.82      albertel 6357: sub scantron_add_delay {
1.140     albertel 6358:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6359:     push(@$delayqueue,
                   6360: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6361: 	  'ecode' => $errorcode }
                   6362: 	 );
1.82      albertel 6363: }
                   6364: 
1.423     albertel 6365: =pod
                   6366: 
                   6367: =item scantron_find_student
                   6368: 
1.424     albertel 6369:    Finds the username for the current scanline
                   6370: 
                   6371:   Arguments:
                   6372:    $scantron_record - hash result from scantron_parse_scanline
                   6373:    $scan_data       - hash of correction information 
                   6374:                       (see &scantron_getfile() form more information)
                   6375:    $idmap           - hash from &username_to_idmap()
                   6376:    $line            - number of current scanline
                   6377:  
                   6378:   Returns:
                   6379:    Either 'username:domain' or undef if unknown
                   6380: 
1.423     albertel 6381: =cut
                   6382: 
1.82      albertel 6383: sub scantron_find_student {
1.157     albertel 6384:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6385:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6386:     if ($scanID =~ /^\s*$/) {
                   6387:  	return &scan_data($scan_data,"$line.user");
                   6388:     }
1.83      albertel 6389:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6390:  	if (lc($id) eq lc($scanID)) {
                   6391:  	    return $$idmap{$id};
                   6392:  	}
1.83      albertel 6393:     }
                   6394:     return undef;
                   6395: }
                   6396: 
1.423     albertel 6397: =pod
                   6398: 
                   6399: =item scantron_filter
                   6400: 
1.424     albertel 6401:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6402:    hidden resources was selected
                   6403: 
1.423     albertel 6404: =cut
                   6405: 
1.83      albertel 6406: sub scantron_filter {
                   6407:     my ($curres)=@_;
1.331     albertel 6408: 
                   6409:     if (ref($curres) && $curres->is_problem()) {
                   6410: 	# if the user has asked to not have either hidden
                   6411: 	# or 'randomout' controlled resources to be graded
                   6412: 	# don't include them
                   6413: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6414: 	    && $curres->randomout) {
                   6415: 	    return 0;
                   6416: 	}
1.83      albertel 6417: 	return 1;
                   6418:     }
                   6419:     return 0;
1.82      albertel 6420: }
                   6421: 
1.423     albertel 6422: =pod
                   6423: 
                   6424: =item scantron_process_corrections
                   6425: 
1.424     albertel 6426:    Gets correction information out of submitted form data and corrects
                   6427:    the scanline
                   6428: 
1.423     albertel 6429: =cut
                   6430: 
1.157     albertel 6431: sub scantron_process_corrections {
                   6432:     my ($r) = @_;
1.257     albertel 6433:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6434:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6435:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6436:     my $which=$env{'form.scantron_line'};
1.200     albertel 6437:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6438:     my ($skip,$err,$errmsg);
1.257     albertel 6439:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6440: 	$skip=1;
1.257     albertel 6441:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6442: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6443: 	    $env{'form.scantron_domain'};
1.157     albertel 6444: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6445: 	($line,$err,$errmsg)=
                   6446: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6447: 				     'ID',{'newid'=>$newid,
1.257     albertel 6448: 				    'username'=>$env{'form.scantron_username'},
                   6449: 				    'domain'=>$env{'form.scantron_domain'}});
                   6450:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6451: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6452: 	my $newCODE;
1.192     albertel 6453: 	my %args;
1.190     albertel 6454: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6455: 	    $newCODE='use_unfound';
1.190     albertel 6456: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6457: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6458: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6459: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6460: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6461: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6462: 	}
1.257     albertel 6463: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6464: 	    $args{'CODE_ignore_dup'}=1;
                   6465: 	}
                   6466: 	$args{'CODE'}=$newCODE;
1.186     albertel 6467: 	($line,$err,$errmsg)=
                   6468: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6469: 				     'CODE',\%args);
1.257     albertel 6470:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6471: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6472: 	    ($line,$err,$errmsg)=
                   6473: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6474: 					 $which,'answer',
                   6475: 					 { 'question'=>$question,
1.503     raeburn  6476: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6477:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6478: 	    if ($err) { last; }
                   6479: 	}
                   6480:     }
                   6481:     if ($err) {
1.703     bisitz   6482:         $r->print(
                   6483:             '<p class="LC_error">'
                   6484:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6485:                 $errmsg)
1.704     raeburn  6486:            .'</p>');
1.157     albertel 6487:     } else {
1.200     albertel 6488: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6489: 	&scantron_putfile($scanlines,$scan_data);
                   6490:     }
                   6491: }
                   6492: 
1.423     albertel 6493: =pod
                   6494: 
                   6495: =item reset_skipping_status
                   6496: 
1.424     albertel 6497:    Forgets the current set of remember skipped scanlines (and thus
                   6498:    reverts back to considering all lines in the
                   6499:    scantron_skipped_<filename> file)
                   6500: 
1.423     albertel 6501: =cut
                   6502: 
1.200     albertel 6503: sub reset_skipping_status {
                   6504:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6505:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6506:     &scantron_putfile(undef,$scan_data);
                   6507: }
                   6508: 
1.423     albertel 6509: =pod
                   6510: 
                   6511: =item start_skipping
                   6512: 
1.424     albertel 6513:    Marks a scanline to be skipped. 
                   6514: 
1.423     albertel 6515: =cut
                   6516: 
1.376     albertel 6517: sub start_skipping {
1.200     albertel 6518:     my ($scan_data,$i)=@_;
                   6519:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6520:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6521: 	$remembered{$i}=2;
                   6522:     } else {
                   6523: 	$remembered{$i}=1;
                   6524:     }
1.200     albertel 6525:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6526: }
                   6527: 
1.423     albertel 6528: =pod
                   6529: 
                   6530: =item should_be_skipped
                   6531: 
1.424     albertel 6532:    Checks whether a scanline should be skipped.
                   6533: 
1.423     albertel 6534: =cut
                   6535: 
1.200     albertel 6536: sub should_be_skipped {
1.376     albertel 6537:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6538:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6539: 	# not redoing old skips
1.376     albertel 6540: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6541: 	return 0;
                   6542:     }
                   6543:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6544: 
                   6545:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6546: 	return 0;
                   6547:     }
1.200     albertel 6548:     return 1;
                   6549: }
                   6550: 
1.423     albertel 6551: =pod
                   6552: 
                   6553: =item remember_current_skipped
                   6554: 
1.424     albertel 6555:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6556:    file and remembers them into scan_data for later use.
                   6557: 
1.423     albertel 6558: =cut
                   6559: 
1.200     albertel 6560: sub remember_current_skipped {
                   6561:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6562:     my %to_remember;
                   6563:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6564: 	if ($scanlines->{'skipped'}[$i]) {
                   6565: 	    $to_remember{$i}=1;
                   6566: 	}
                   6567:     }
1.376     albertel 6568: 
1.200     albertel 6569:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6570:     &scantron_putfile(undef,$scan_data);
                   6571: }
                   6572: 
1.423     albertel 6573: =pod
                   6574: 
                   6575: =item check_for_error
                   6576: 
1.424     albertel 6577:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6578:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6579:     something went wrong.
                   6580: 
1.423     albertel 6581: =cut
                   6582: 
1.200     albertel 6583: sub check_for_error {
                   6584:     my ($r,$result)=@_;
                   6585:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6586: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6587:     }
                   6588: }
1.157     albertel 6589: 
1.423     albertel 6590: =pod
                   6591: 
                   6592: =item scantron_warning_screen
                   6593: 
1.424     albertel 6594:    Interstitial screen to make sure the operator has selected the
                   6595:    correct options before we start the validation phase.
                   6596: 
1.423     albertel 6597: =cut
                   6598: 
1.203     albertel 6599: sub scantron_warning_screen {
1.650     raeburn  6600:     my ($button_text,$symb)=@_;
1.257     albertel 6601:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6602:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6603:     my $CODElist;
1.284     albertel 6604:     if ($scantron_config{'CODElocation'} &&
                   6605: 	$scantron_config{'CODEstart'} &&
                   6606: 	$scantron_config{'CODElength'}) {
                   6607: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6608: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6609: 	$CODElist=
1.492     albertel 6610: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6611: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6612:     }
1.663     raeburn  6613:     my $lastbubblepoints;
                   6614:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6615:         $lastbubblepoints =
                   6616:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6617:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6618:     }
1.492     albertel 6619:     return ('
1.203     albertel 6620: <p>
1.492     albertel 6621: <span class="LC_warning">
1.705     raeburn  6622: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6623: </p>
                   6624: <table>
1.492     albertel 6625: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6626: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6627: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6628: </table>
1.680     raeburn  6629: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6630: '.&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 6631: 
                   6632: <br />
1.492     albertel 6633: ');
1.203     albertel 6634: }
                   6635: 
1.423     albertel 6636: =pod
                   6637: 
                   6638: =item scantron_do_warning
                   6639: 
1.424     albertel 6640:    Check if the operator has picked something for all required
                   6641:    fields. Error out if something is missing.
                   6642: 
1.423     albertel 6643: =cut
                   6644: 
1.203     albertel 6645: sub scantron_do_warning {
1.608     www      6646:     my ($r,$symb)=@_;
1.203     albertel 6647:     if (!$symb) {return '';}
1.324     albertel 6648:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6649:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6650:     if ( $env{'form.selectpage'} eq '' ||
                   6651: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6652: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6653: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6654: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6655: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6656: 	} 
1.257     albertel 6657: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6658: 	    $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 6659: 	} 
1.257     albertel 6660: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6661: 	    $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 6662: 	} 
                   6663:     } else {
1.650     raeburn  6664: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6665:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6666: 	$r->print('
1.663     raeburn  6667: '.$warning.$bubbledbyhand.'
1.492     albertel 6668: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6669: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6670: ');
1.237     albertel 6671:     }
1.614     www      6672:     $r->print("</form><br />");
1.203     albertel 6673:     return '';
                   6674: }
                   6675: 
1.423     albertel 6676: =pod
                   6677: 
                   6678: =item scantron_form_start
                   6679: 
1.424     albertel 6680:     html hidden input for remembering all selected grading options
                   6681: 
1.423     albertel 6682: =cut
                   6683: 
1.203     albertel 6684: sub scantron_form_start {
                   6685:     my ($max_bubble)=@_;
                   6686:     my $result= <<SCANTRONFORM;
                   6687: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6688:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6689:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6690:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6691:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6692:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6693:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6694:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6695:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6696:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6697: SCANTRONFORM
1.447     foxr     6698: 
                   6699:   my $line = 0;
                   6700:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6701:        my $chunk =
                   6702: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6703:        $chunk .=
                   6704: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6705:        $chunk .= 
                   6706:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6707:        $chunk .=
                   6708:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6709:        $chunk .=
                   6710:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6711:        $result .= $chunk;
                   6712:        $line++;
1.691     raeburn  6713:     }
1.203     albertel 6714:     return $result;
                   6715: }
                   6716: 
1.423     albertel 6717: =pod
                   6718: 
                   6719: =item scantron_validate_file
                   6720: 
1.659     raeburn  6721:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6722: 
                   6723:     Also processes any necessary information resets that need to
                   6724:     occur before validation begins (ignore previous corrections,
                   6725:     restarting the skipped records processing)
                   6726: 
1.423     albertel 6727: =cut
                   6728: 
1.157     albertel 6729: sub scantron_validate_file {
1.608     www      6730:     my ($r,$symb) = @_;
1.157     albertel 6731:     if (!$symb) {return '';}
1.324     albertel 6732:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6733:     
1.703     bisitz   6734:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6735:     # them when doing the corrections reset
1.257     albertel 6736:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6737: 	&reset_skipping_status();
                   6738:     }
1.257     albertel 6739:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6740: 	&remember_current_skipped();
1.257     albertel 6741: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6742:     }
                   6743: 
1.257     albertel 6744:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6745: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6746: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6747: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6748: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6749:     }
1.200     albertel 6750: 
1.257     albertel 6751:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6752: 	&scantron_process_corrections($r);
                   6753:     }
1.503     raeburn  6754:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6755:     #get the student pick code ready
                   6756:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6757:     my $nav_error;
1.649     raeburn  6758:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6759:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6760:     if ($nav_error) {
                   6761:         $r->print(&navmap_errormsg());
                   6762:         return '';
                   6763:     }
1.203     albertel 6764:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6765:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6766:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6767:     }
1.157     albertel 6768:     $r->print($result);
                   6769:     
1.334     albertel 6770:     my @validate_phases=( 'sequence',
                   6771: 			  'ID',
1.157     albertel 6772: 			  'CODE',
                   6773: 			  'doublebubble',
                   6774: 			  'missingbubbles');
1.257     albertel 6775:     if (!$env{'form.validatepass'}) {
                   6776: 	$env{'form.validatepass'} = 0;
1.157     albertel 6777:     }
1.257     albertel 6778:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6779: 
1.448     foxr     6780: 
1.157     albertel 6781:     my $stop=0;
                   6782:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6783: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6784: 	$r->rflush();
1.691     raeburn  6785:      
1.157     albertel 6786: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6787: 	{
                   6788: 	    no strict 'refs';
                   6789: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6790: 	}
                   6791:     }
                   6792:     if (!$stop) {
1.650     raeburn  6793: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6794: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6795:                   $warning.
                   6796:                   &mt('Perform verification for each student after storage of submissions?').
                   6797:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6798:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6799:                   ('&nbsp;'x3).'<label>'.
                   6800:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6801:                   '</label></span><br />'.
                   6802:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6803:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6804:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6805:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6806:     } else {
                   6807: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6808: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6809:     }
                   6810:     if ($stop) {
1.334     albertel 6811: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6812: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6813: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6814: 
1.650     raeburn  6815: 	    $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 6816: 	} else {
1.503     raeburn  6817:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6818: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6819:             } else {
1.539     riegler  6820:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6821:             }
1.492     albertel 6822: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6823: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6824: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6825: 	}
1.157     albertel 6826:     }
1.614     www      6827:     $r->print(" </form><br />");
1.157     albertel 6828:     return '';
                   6829: }
                   6830: 
1.423     albertel 6831: 
                   6832: =pod
                   6833: 
                   6834: =item scantron_remove_file
                   6835: 
1.659     raeburn  6836:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6837:    scantron_original_<filename> is never removed
                   6838: 
                   6839: 
1.423     albertel 6840: =cut
                   6841: 
1.200     albertel 6842: sub scantron_remove_file {
1.192     albertel 6843:     my ($which)=@_;
1.257     albertel 6844:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6845:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6846:     my $file='scantron_';
1.200     albertel 6847:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6848: 	$file.=$which.'_';
1.192     albertel 6849:     } else {
                   6850: 	return 'refused';
                   6851:     }
1.257     albertel 6852:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6853:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6854: }
                   6855: 
1.423     albertel 6856: 
                   6857: =pod
                   6858: 
                   6859: =item scantron_remove_scan_data
                   6860: 
1.659     raeburn  6861:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6862:    data file.  (In the case that both the are doing skipped records we need
                   6863:    to remember the old skipped lines for the time being so that element
                   6864:    persists for a while.)
                   6865: 
1.423     albertel 6866: =cut
                   6867: 
1.200     albertel 6868: sub scantron_remove_scan_data {
1.257     albertel 6869:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6870:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6871:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6872:     my @todelete;
1.257     albertel 6873:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6874:     foreach my $key (@keys) {
                   6875: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6876: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6877: 		$key=~/remember_skipping/) {
                   6878: 		next;
                   6879: 	    }
1.192     albertel 6880: 	    push(@todelete,$key);
                   6881: 	}
                   6882:     }
1.200     albertel 6883:     my $result;
1.192     albertel 6884:     if (@todelete) {
1.491     albertel 6885: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6886: 				       \@todelete,$cdom,$cname);
                   6887:     } else {
                   6888: 	$result = 'ok';
1.192     albertel 6889:     }
                   6890:     return $result;
                   6891: }
                   6892: 
1.423     albertel 6893: 
                   6894: =pod
                   6895: 
                   6896: =item scantron_getfile
                   6897: 
1.659     raeburn  6898:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6899:     the scan_data hash
                   6900:   
                   6901:   Arguments:
                   6902:     None
                   6903: 
                   6904:   Returns:
                   6905:     2 hash references
                   6906: 
                   6907:      - first one has 
                   6908:          orig      -
                   6909:          corrected -
                   6910:          skipped   -  each of which points to an array ref of the specified
                   6911:                       file broken up into individual lines
                   6912:          count     - number of scanlines
                   6913:  
                   6914:      - second is the scan_data hash possible keys are
1.425     albertel 6915:        ($number refers to scanline numbered $number and thus the key affects
                   6916:         only that scanline
                   6917:         $bubline refers to the specific bubble line element and the aspects
                   6918:         refers to that specific bubble line element)
                   6919: 
                   6920:        $number.user - username:domain to use
                   6921:        $number.CODE_ignore_dup 
                   6922:                     - ignore the duplicate CODE error 
                   6923:        $number.useCODE
                   6924:                     - use the CODE in the scanline as is
                   6925:        $number.no_bubble.$bubline
                   6926:                     - it is valid that there is no bubbled in bubble
                   6927:                       at $number $bubline
                   6928:        remember_skipping
                   6929:                     - a frozen hash containing keys of $number and values
                   6930:                       of either 
                   6931:                         1 - we are on a 'do skipped records pass' and plan
                   6932:                             on processing this line
                   6933:                         2 - we are on a 'do skipped records pass' and this
                   6934:                             scanline has been marked to skip yet again
1.424     albertel 6935: 
1.423     albertel 6936: =cut
                   6937: 
1.157     albertel 6938: sub scantron_getfile {
1.200     albertel 6939:     #FIXME really would prefer a scantron directory
1.257     albertel 6940:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6941:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6942:     my $lines;
                   6943:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6944: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6945:     my %scanlines;
                   6946:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6947:     my $temp=$scanlines{'orig'};
                   6948:     $scanlines{'count'}=$#$temp;
                   6949: 
                   6950:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6951: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6952:     if ($lines eq '-1') {
                   6953: 	$scanlines{'corrected'}=[];
                   6954:     } else {
                   6955: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6956:     }
                   6957:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6958: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6959:     if ($lines eq '-1') {
                   6960: 	$scanlines{'skipped'}=[];
                   6961:     } else {
                   6962: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6963:     }
1.175     albertel 6964:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6965:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6966:     my %scan_data = @tmp;
                   6967:     return (\%scanlines,\%scan_data);
                   6968: }
                   6969: 
1.423     albertel 6970: =pod
                   6971: 
                   6972: =item lonnet_putfile
                   6973: 
1.424     albertel 6974:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6975: 
                   6976:  Arguments:
                   6977:    $contents - data to store
                   6978:    $filename - filename to store $contents into
                   6979: 
                   6980:  Returns:
                   6981:    result value from &Apache::lonnet::finishuserfileupload
                   6982: 
1.423     albertel 6983: =cut
                   6984: 
1.157     albertel 6985: sub lonnet_putfile {
                   6986:     my ($contents,$filename)=@_;
1.257     albertel 6987:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6988:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6989:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6990:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6991: 
                   6992: }
                   6993: 
1.423     albertel 6994: =pod
                   6995: 
                   6996: =item scantron_putfile
                   6997: 
1.659     raeburn  6998:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6999:     scan_data hash. (Does not modify the original version only the
                   7000:     corrected and skipped versions.
                   7001: 
                   7002:  Arguments:
                   7003:     $scanlines - hash ref that looks like the first return value from
                   7004:                  &scantron_getfile()
                   7005:     $scan_data - hash ref that looks like the second return value from
                   7006:                  &scantron_getfile()
                   7007: 
1.423     albertel 7008: =cut
                   7009: 
1.157     albertel 7010: sub scantron_putfile {
                   7011:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7012:     #FIXME really would prefer a scantron directory
1.257     albertel 7013:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7014:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7015:     if ($scanlines) {
                   7016: 	my $prefix='scantron_';
1.157     albertel 7017: # no need to update orig, shouldn't change
                   7018: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7019: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7020: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7021: 			$prefix.'corrected_'.
1.257     albertel 7022: 			$env{'form.scantron_selectfile'});
1.200     albertel 7023: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7024: 			$prefix.'skipped_'.
1.257     albertel 7025: 			$env{'form.scantron_selectfile'});
1.200     albertel 7026:     }
1.175     albertel 7027:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7028: }
                   7029: 
1.423     albertel 7030: =pod
                   7031: 
                   7032: =item scantron_get_line
                   7033: 
1.424     albertel 7034:    Returns the correct version of the scanline
                   7035: 
                   7036:  Arguments:
                   7037:     $scanlines - hash ref that looks like the first return value from
                   7038:                  &scantron_getfile()
                   7039:     $scan_data - hash ref that looks like the second return value from
                   7040:                  &scantron_getfile()
                   7041:     $i         - number of the requested line (starts at 0)
                   7042: 
                   7043:  Returns:
                   7044:    A scanline, (either the original or the corrected one if it
                   7045:    exists), or undef if the requested scanline should be
                   7046:    skipped. (Either because it's an skipped scanline, or it's an
                   7047:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7048:    pass.
                   7049: 
1.423     albertel 7050: =cut
                   7051: 
1.157     albertel 7052: sub scantron_get_line {
1.200     albertel 7053:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7054:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7055:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7056:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7057:     return $scanlines->{'orig'}[$i]; 
                   7058: }
                   7059: 
1.423     albertel 7060: =pod
                   7061: 
                   7062: =item scantron_todo_count
                   7063: 
1.424     albertel 7064:     Counts the number of scanlines that need processing.
                   7065: 
                   7066:  Arguments:
                   7067:     $scanlines - hash ref that looks like the first return value from
                   7068:                  &scantron_getfile()
                   7069:     $scan_data - hash ref that looks like the second return value from
                   7070:                  &scantron_getfile()
                   7071: 
                   7072:  Returns:
                   7073:     $count - number of scanlines to process
                   7074: 
1.423     albertel 7075: =cut
                   7076: 
1.200     albertel 7077: sub get_todo_count {
                   7078:     my ($scanlines,$scan_data)=@_;
                   7079:     my $count=0;
                   7080:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7081: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7082: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7083: 	$count++;
                   7084:     }
                   7085:     return $count;
                   7086: }
                   7087: 
1.423     albertel 7088: =pod
                   7089: 
                   7090: =item scantron_put_line
                   7091: 
1.659     raeburn  7092:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7093:     data file.
                   7094: 
                   7095:  Arguments:
                   7096:     $scanlines - hash ref that looks like the first return value from
                   7097:                  &scantron_getfile()
                   7098:     $scan_data - hash ref that looks like the second return value from
                   7099:                  &scantron_getfile()
                   7100:     $i         - line number to update
                   7101:     $newline   - contents of the updated scanline
                   7102:     $skip      - if true make the line for skipping and update the
                   7103:                  'skipped' file
                   7104: 
1.423     albertel 7105: =cut
                   7106: 
1.157     albertel 7107: sub scantron_put_line {
1.200     albertel 7108:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7109:     if ($skip) {
                   7110: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7111: 	&start_skipping($scan_data,$i);
1.157     albertel 7112: 	return;
                   7113:     }
                   7114:     $scanlines->{'corrected'}[$i]=$newline;
                   7115: }
                   7116: 
1.423     albertel 7117: =pod
                   7118: 
                   7119: =item scantron_clear_skip
                   7120: 
1.424     albertel 7121:    Remove a line from the 'skipped' file
                   7122: 
                   7123:  Arguments:
                   7124:     $scanlines - hash ref that looks like the first return value from
                   7125:                  &scantron_getfile()
                   7126:     $scan_data - hash ref that looks like the second return value from
                   7127:                  &scantron_getfile()
                   7128:     $i         - line number to update
                   7129: 
1.423     albertel 7130: =cut
                   7131: 
1.376     albertel 7132: sub scantron_clear_skip {
                   7133:     my ($scanlines,$scan_data,$i)=@_;
                   7134:     if (exists($scanlines->{'skipped'}[$i])) {
                   7135: 	undef($scanlines->{'skipped'}[$i]);
                   7136: 	return 1;
                   7137:     }
                   7138:     return 0;
                   7139: }
                   7140: 
1.423     albertel 7141: =pod
                   7142: 
                   7143: =item scantron_filter_not_exam
                   7144: 
1.424     albertel 7145:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7146:    filter out resources that are not marked as 'exam' mode
                   7147: 
1.423     albertel 7148: =cut
                   7149: 
1.334     albertel 7150: sub scantron_filter_not_exam {
                   7151:     my ($curres)=@_;
                   7152:     
                   7153:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7154: 	# if the user has asked to not have either hidden
                   7155: 	# or 'randomout' controlled resources to be graded
                   7156: 	# don't include them
                   7157: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7158: 	    && $curres->randomout) {
                   7159: 	    return 0;
                   7160: 	}
                   7161: 	return 1;
                   7162:     }
                   7163:     return 0;
                   7164: }
                   7165: 
1.423     albertel 7166: =pod
                   7167: 
                   7168: =item scantron_validate_sequence
                   7169: 
1.424     albertel 7170:     Validates the selected sequence, checking for resource that are
                   7171:     not set to exam mode.
                   7172: 
1.423     albertel 7173: =cut
                   7174: 
1.334     albertel 7175: sub scantron_validate_sequence {
                   7176:     my ($r,$currentphase) = @_;
                   7177: 
                   7178:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7179:     unless (ref($navmap)) {
                   7180:         $r->print(&navmap_errormsg());
                   7181:         return (1,$currentphase);
                   7182:     }
1.334     albertel 7183:     my (undef,undef,$sequence)=
                   7184: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7185: 
                   7186:     my $map=$navmap->getResourceByUrl($sequence);
                   7187: 
                   7188:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7189:                                     value="ignore" />');
                   7190:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7191: 	my @resources=
                   7192: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7193: 	if (@resources) {
1.675     bisitz   7194: 	    $r->print(
                   7195:                 '<p class="LC_warning">'
                   7196:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7197:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7198:                    .' work correctly.')
                   7199:                .'</p>'
                   7200:             );
1.334     albertel 7201: 	    return (1,$currentphase);
                   7202: 	}
                   7203:     }
                   7204: 
                   7205:     return (0,$currentphase+1);
                   7206: }
                   7207: 
1.423     albertel 7208: 
                   7209: 
1.157     albertel 7210: sub scantron_validate_ID {
                   7211:     my ($r,$currentphase) = @_;
                   7212:     
                   7213:     #get student info
                   7214:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7215:     my %idmap=&username_to_idmap($classlist);
                   7216: 
                   7217:     #get scantron line setup
1.257     albertel 7218:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7219:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7220: 
                   7221:     my $nav_error;
1.649     raeburn  7222:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7223:     if ($nav_error) {
                   7224:         $r->print(&navmap_errormsg());
                   7225:         return(1,$currentphase);
                   7226:     }
1.157     albertel 7227: 
                   7228:     my %found=('ids'=>{},'usernames'=>{});
                   7229:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7230: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7231: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7232: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7233: 						 $scan_data);
                   7234: 	my $id=$$scan_record{'scantron.ID'};
                   7235: 	my $found;
                   7236: 	foreach my $checkid (keys(%idmap)) {
                   7237: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7238: 	}
                   7239: 	if ($found) {
                   7240: 	    my $username=$idmap{$found};
                   7241: 	    if ($found{'ids'}{$found}) {
                   7242: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7243: 					 $line,'duplicateID',$found);
1.194     albertel 7244: 		return(1,$currentphase);
1.157     albertel 7245: 	    } elsif ($found{'usernames'}{$username}) {
                   7246: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7247: 					 $line,'duplicateID',$username);
1.194     albertel 7248: 		return(1,$currentphase);
1.157     albertel 7249: 	    }
1.186     albertel 7250: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7251: 	    $found{'ids'}{$found}++;
                   7252: 	    $found{'usernames'}{$username}++;
                   7253: 	} else {
                   7254: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7255: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7256: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7257: 		    &scantron_get_correction($r,$i,$scan_record,
                   7258: 					     \%scantron_config,
                   7259: 					     $line,'duplicateID',$username);
1.194     albertel 7260: 		    return(1,$currentphase);
1.157     albertel 7261: 		} elsif (!defined($username)) {
                   7262: 		    &scantron_get_correction($r,$i,$scan_record,
                   7263: 					     \%scantron_config,
                   7264: 					     $line,'incorrectID');
1.194     albertel 7265: 		    return(1,$currentphase);
1.157     albertel 7266: 		}
                   7267: 		$found{'usernames'}{$username}++;
                   7268: 	    } else {
                   7269: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7270: 					 $line,'incorrectID');
1.194     albertel 7271: 		return(1,$currentphase);
1.157     albertel 7272: 	    }
                   7273: 	}
                   7274:     }
                   7275: 
                   7276:     return (0,$currentphase+1);
                   7277: }
                   7278: 
1.423     albertel 7279: 
1.157     albertel 7280: sub scantron_get_correction {
1.691     raeburn  7281:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7282:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7283: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7284: #to show both the current line and the previous one and allow skipping
                   7285: #the previous one or the current one
                   7286: 
1.333     albertel 7287:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7288:         $r->print(
                   7289:             '<p class="LC_warning">'
                   7290:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7291:                 "<b>$error</b>",
                   7292:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7293:            ."</p> \n");
1.157     albertel 7294:     } else {
1.658     bisitz   7295:         $r->print(
                   7296:             '<p class="LC_warning">'
                   7297:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7298:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7299:            ."</p> \n");
                   7300:     }
                   7301:     my $message =
                   7302:         '<p>'
                   7303:        .&mt('The ID on the form is [_1]',
                   7304:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7305:        .'<br />'
1.665     raeburn  7306:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7307:             $$scan_record{'scantron.LastName'},
                   7308:             $$scan_record{'scantron.FirstName'})
                   7309:        .'</p>';
1.242     albertel 7310: 
1.157     albertel 7311:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7312:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7313:                            # Array populated for doublebubble or
                   7314:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7315:                            # to validate radio button checking   
                   7316: 
1.157     albertel 7317:     if ($error =~ /ID$/) {
1.186     albertel 7318: 	if ($error eq 'incorrectID') {
1.658     bisitz   7319:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7320: 		      "</p>\n");
1.157     albertel 7321: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7322:             $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 7323: 	}
1.242     albertel 7324: 	$r->print($message);
1.492     albertel 7325: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7326: 	$r->print("\n<ul><li> ");
                   7327: 	#FIXME it would be nice if this sent back the user ID and
                   7328: 	#could do partial userID matches
                   7329: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7330: 				       'scantron_username','scantron_domain'));
                   7331: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7332: 	$r->print("\n:\n".
1.257     albertel 7333: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7334: 
                   7335: 	$r->print('</li>');
1.186     albertel 7336:     } elsif ($error =~ /CODE$/) {
                   7337: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7338: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7339: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7340: 	    $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 7341: 	}
1.658     bisitz   7342: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7343: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7344:                  ."</p>\n");
1.242     albertel 7345: 	$r->print($message);
1.658     bisitz   7346: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7347: 	$r->print("\n<br /> ");
1.194     albertel 7348: 	my $i=0;
1.273     albertel 7349: 	if ($error eq 'incorrectCODE' 
                   7350: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7351: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7352: 	    if ($closest > 0) {
                   7353: 		foreach my $testcode (@{$closest}) {
                   7354: 		    my $checked='';
1.569     bisitz   7355: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7356: 		    $r->print("
                   7357:    <label>
1.569     bisitz   7358:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7359:        ".&mt("Use the similar CODE [_1] instead.",
                   7360: 	    "<b><tt>".$testcode."</tt></b>")."
                   7361:     </label>
                   7362:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7363: 		    $r->print("\n<br />");
                   7364: 		    $i++;
                   7365: 		}
1.194     albertel 7366: 	    }
                   7367: 	}
1.273     albertel 7368: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7369: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7370: 	    $r->print("
                   7371:     <label>
1.569     bisitz   7372:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7373:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7374: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7375:     </label>");
1.273     albertel 7376: 	    $r->print("\n<br />");
                   7377: 	}
1.194     albertel 7378: 
1.597     wenzelju 7379: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7380: function change_radio(field) {
1.190     albertel 7381:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7382:     var i;
                   7383:     for (i=0;i<slct.length;i++) {
                   7384:         if (slct[i].value==field) { slct[i].checked=true; }
                   7385:     }
                   7386: }
                   7387: ENDSCRIPT
1.187     albertel 7388: 	my $href="/adm/pickcode?".
1.359     www      7389: 	   "form=".&escape("scantronupload").
                   7390: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7391: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7392: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7393: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7394: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7395: 	    $r->print("
                   7396:     <label>
                   7397:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7398:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7399: 	     "<a target='_blank' href='$href'>","</a>")."
                   7400:     </label> 
1.558     bisitz   7401:     ".&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 7402: 	    $r->print("\n<br />");
                   7403: 	}
1.492     albertel 7404: 	$r->print("
                   7405:     <label>
                   7406:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7407:        ".&mt("Use [_1] as the CODE.",
                   7408: 	     "</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 7409: 	$r->print("\n<br /><br />");
1.157     albertel 7410:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7411: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7412: 
                   7413: 	# The form field scantron_questions is acutally a list of line numbers.
                   7414: 	# represented by this form so:
                   7415: 
1.691     raeburn  7416: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7417:                                                 $respnumlookup,$startline);
1.497     foxr     7418: 
1.157     albertel 7419: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7420: 		  $line_list.'" />');
1.242     albertel 7421: 	$r->print($message);
1.492     albertel 7422: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7423: 	foreach my $question (@{$arg}) {
1.503     raeburn  7424: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7425:                                                    $scan_record, $error,
                   7426:                                                    $randomorder,$randompick,
                   7427:                                                    $respnumlookup,$startline);
1.524     raeburn  7428:             push(@lines_to_correct,@linenums);
1.157     albertel 7429: 	}
1.503     raeburn  7430:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7431:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7432: 	$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 7433: 	$r->print($message);
1.492     albertel 7434: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7435: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7436: 
1.503     raeburn  7437: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7438: 	# a list of question numbers. Therefore:
                   7439: 	#
1.691     raeburn  7440: 
                   7441: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7442:                                                 $respnumlookup,$startline);
1.497     foxr     7443: 
1.157     albertel 7444: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7445: 		  $line_list.'" />');
1.157     albertel 7446: 	foreach my $question (@{$arg}) {
1.503     raeburn  7447: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7448:                                                    $scan_record, $error,
                   7449:                                                    $randomorder,$randompick,
                   7450:                                                    $respnumlookup,$startline);
1.524     raeburn  7451:             push(@lines_to_correct,@linenums);
1.157     albertel 7452: 	}
1.503     raeburn  7453:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7454:     } else {
                   7455: 	$r->print("\n<ul>");
                   7456:     }
                   7457:     $r->print("\n</li></ul>");
1.497     foxr     7458: }
                   7459: 
1.503     raeburn  7460: sub verify_bubbles_checked {
                   7461:     my (@ansnums) = @_;
                   7462:     my $ansnumstr = join('","',@ansnums);
                   7463:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7464:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7465: function verify_bubble_radio(form) {
                   7466:     var ansnumArray = new Array ("$ansnumstr");
                   7467:     var need_bubble_count = 0;
                   7468:     for (var i=0; i<ansnumArray.length; i++) {
                   7469:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7470:             var bubble_picked = 0; 
                   7471:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7472:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7473:                     bubble_picked = 1;
                   7474:                 }
                   7475:             }
                   7476:             if (bubble_picked == 0) {
                   7477:                 need_bubble_count ++;
                   7478:             }
                   7479:         }
                   7480:     }
                   7481:     if (need_bubble_count) {
                   7482:         alert("$warning");
                   7483:         return;
                   7484:     }
                   7485:     form.submit(); 
                   7486: }
                   7487: ENDSCRIPT
                   7488:     return $output;
                   7489: }
                   7490: 
1.497     foxr     7491: =pod
                   7492: 
                   7493: =item  questions_to_line_list
1.157     albertel 7494: 
1.497     foxr     7495: Converts a list of questions into a string of comma separated
                   7496: line numbers in the answer sheet used by the questions.  This is
                   7497: used to fill in the scantron_questions form field.
                   7498: 
                   7499:   Arguments:
                   7500:      questions    - Reference to an array of questions.
1.691     raeburn  7501:      randomorder  - True if randomorder in use.
                   7502:      randompick   - True if randompick in use.
                   7503:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7504:                      for current line to question number used for same question
                   7505:                      in "Master Seqence" (as seen by Course Coordinator).
                   7506:      startline    - Reference to hash where key is question number (0 is first)
                   7507:                     and key is number of first bubble line for current student
                   7508:                     or code-based randompick and/or randomorder.
1.693     raeburn  7509: 
1.497     foxr     7510: =cut
                   7511: 
                   7512: 
                   7513: sub questions_to_line_list {
1.691     raeburn  7514:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7515:     my @lines;
                   7516: 
1.503     raeburn  7517:     foreach my $item (@{$questions}) {
                   7518:         my $question = $item;
                   7519:         my ($first,$count,$last);
                   7520:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7521:             $question = $1;
                   7522:             my $subquestion = $2;
1.691     raeburn  7523:             my $responsenum = $question-1;
                   7524:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7525:                 $responsenum = $respnumlookup->{$question-1};
                   7526:                 if (ref($startline) eq 'HASH') {
                   7527:                     $first = $startline->{$question-1} + 1;
                   7528:                 }
                   7529:             } else {
                   7530:                 $first = $first_bubble_line{$responsenum} + 1;
                   7531:             }
                   7532:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7533:             my $subcount = 1;
                   7534:             while ($subcount<$subquestion) {
                   7535:                 $first += $subans[$subcount-1];
                   7536:                 $subcount ++;
                   7537:             }
                   7538:             $count = $subans[$subquestion-1];
                   7539:         } else {
1.691     raeburn  7540:             my $responsenum = $question-1;
                   7541:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7542:                 $responsenum = $respnumlookup->{$question-1};
                   7543:                 if (ref($startline) eq 'HASH') {
                   7544:                     $first = $startline->{$question-1} + 1;
                   7545:                 }
                   7546:             } else {
                   7547:                 $first = $first_bubble_line{$responsenum} + 1;
                   7548:             }
                   7549: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7550:         }
1.506     raeburn  7551:         $last = $first+$count-1;
1.503     raeburn  7552:         push(@lines, ($first..$last));
1.497     foxr     7553:     }
                   7554:     return join(',', @lines);
                   7555: }
                   7556: 
                   7557: =pod 
                   7558: 
                   7559: =item prompt_for_corrections
                   7560: 
                   7561: Prompts for a potentially multiline correction to the
                   7562: user's bubbling (factors out common code from scantron_get_correction
                   7563: for multi and missing bubble cases).
                   7564: 
                   7565:  Arguments:
                   7566:    $r           - Apache request object.
                   7567:    $question    - The question number to prompt for.
                   7568:    $scan_config - The scantron file configuration hash.
                   7569:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7570:    $error       - Type of error
1.691     raeburn  7571:    $randomorder - True if randomorder in use.
                   7572:    $randompick  - True if randompick in use.
                   7573:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7574:                     for current line to question number used for same question
                   7575:                     in "Master Seqence" (as seen by Course Coordinator).
                   7576:    $startline   - Reference to hash where key is question number (0 is first)
                   7577:                   and value is number of first bubble line for current student
                   7578:                   or code-based randompick and/or randomorder.
                   7579: 
1.497     foxr     7580: 
                   7581:  Implicit inputs:
                   7582:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7583:                                   Numbered from 0 (but question numbers are from
                   7584:                                   1.
                   7585:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7586:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7587:                                   type problems render as separate sub-questions, 
1.503     raeburn  7588:                                   in exam mode. This hash contains a 
                   7589:                                   comma-separated list of the lines per 
                   7590:                                   sub-question.
1.510     raeburn  7591:    %responsetype_per_response   - essayresponse, formularesponse,
                   7592:                                   stringresponse, imageresponse, reactionresponse,
                   7593:                                   and organicresponse type problem parts can have
1.503     raeburn  7594:                                   multiple lines per response if the weight
                   7595:                                   assigned exceeds 10.  In this case, only
                   7596:                                   one bubble per line is permitted, but more 
                   7597:                                   than one line might contain bubbles, e.g.
                   7598:                                   bubbling of: line 1 - J, line 2 - J, 
                   7599:                                   line 3 - B would assign 22 points.  
1.497     foxr     7600: 
                   7601: =cut
                   7602: 
                   7603: sub prompt_for_corrections {
1.691     raeburn  7604:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7605:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7606:     my ($current_line,$lines);
                   7607:     my @linenums;
                   7608:     my $questionnum = $question;
1.691     raeburn  7609:     my ($first,$responsenum);
1.503     raeburn  7610:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7611:         $question = $1;
                   7612:         my $subquestion = $2;
1.691     raeburn  7613:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7614:             $responsenum = $respnumlookup->{$question-1};
                   7615:             if (ref($startline) eq 'HASH') {
                   7616:                 $first = $startline->{$question-1};
                   7617:             }
                   7618:         } else {
                   7619:             $responsenum = $question-1;
1.714     raeburn  7620:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7621:         }
                   7622:         $current_line = $first + 1 ;
                   7623:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7624:         my $subcount = 1;
                   7625:         while ($subcount<$subquestion) {
                   7626:             $current_line += $subans[$subcount-1];
                   7627:             $subcount ++;
                   7628:         }
                   7629:         $lines = $subans[$subquestion-1];
                   7630:     } else {
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;
                   7638:             $first = $first_bubble_line{$responsenum};
                   7639:         }
                   7640:         $current_line = $first + 1;
                   7641:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7642:     }
1.497     foxr     7643:     if ($lines > 1) {
1.503     raeburn  7644:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7645:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7646:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7647:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7648:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7649:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7650:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7651:             $r->print(
                   7652:                 &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)
                   7653:                .'<br /><br />'
                   7654:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7655:                .'<br />'
                   7656:                .&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.')
                   7657:                .'<br />'
                   7658:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7659:                .'<br /><br />'
                   7660:             );
1.503     raeburn  7661:         } else {
                   7662:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7663:         }
1.497     foxr     7664:     }
                   7665:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7666:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7667: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7668: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7669:         push(@linenums,$current_line);
1.497     foxr     7670: 	$current_line++;
                   7671:     }
                   7672:     if ($lines > 1) {
                   7673: 	$r->print("<hr /><br />");
                   7674:     }
1.503     raeburn  7675:     return @linenums;
1.157     albertel 7676: }
1.423     albertel 7677: 
                   7678: =pod
                   7679: 
                   7680: =item scantron_bubble_selector
                   7681:   
                   7682:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7683:    possibly showing the existing the selected bubbles if known
1.423     albertel 7684: 
                   7685:  Arguments:
                   7686:     $r           - Apache request object
                   7687:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7688:     $line        - Number of the line being displayed.
1.503     raeburn  7689:     $questionnum - Question number (may include subquestion)
                   7690:     $error       - Type of error.
1.497     foxr     7691:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7692: 
                   7693: =cut
                   7694: 
1.157     albertel 7695: sub scantron_bubble_selector {
1.503     raeburn  7696:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7697:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7698: 
                   7699:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7700:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7701:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7702:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7703:             $max=$$scan_config{'BubblesPerRow'};
                   7704:             if (($scmode eq 'number') && ($max > 10)) {
                   7705:                 $max = 10;
                   7706:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7707:                 $max = 26;
                   7708:             }
                   7709:         } else {
                   7710:             $max = 10;
                   7711:         }
                   7712:     }
1.274     albertel 7713: 
1.157     albertel 7714:     my @alphabet=('A'..'Z');
1.503     raeburn  7715:     $r->print(&Apache::loncommon::start_data_table().
                   7716:               &Apache::loncommon::start_data_table_row());
                   7717:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7718:     for (my $i=0;$i<$max+1;$i++) {
                   7719: 	$r->print("\n".'<td align="center">');
                   7720: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7721: 	else { $r->print('&nbsp;'); }
                   7722: 	$r->print('</td>');
                   7723:     }
1.503     raeburn  7724:     $r->print(&Apache::loncommon::end_data_table_row().
                   7725:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7726:     for (my $i=0;$i<$max;$i++) {
                   7727: 	$r->print("\n".
                   7728: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7729: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7730:     }
1.503     raeburn  7731:     my $nobub_checked = ' ';
                   7732:     if ($error eq 'missingbubble') {
                   7733:         $nobub_checked = ' checked = "checked" ';
                   7734:     }
                   7735:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7736: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7737:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7738:               $line.'" value="'.$questionnum.'" /></td>');
                   7739:     $r->print(&Apache::loncommon::end_data_table_row().
                   7740:               &Apache::loncommon::end_data_table());
1.157     albertel 7741: }
                   7742: 
1.423     albertel 7743: =pod
                   7744: 
                   7745: =item num_matches
                   7746: 
1.424     albertel 7747:    Counts the number of characters that are the same between the two arguments.
                   7748: 
                   7749:  Arguments:
                   7750:    $orig - CODE from the scanline
                   7751:    $code - CODE to match against
                   7752: 
                   7753:  Returns:
                   7754:    $count - integer count of the number of same characters between the
                   7755:             two arguments
                   7756: 
1.423     albertel 7757: =cut
                   7758: 
1.194     albertel 7759: sub num_matches {
                   7760:     my ($orig,$code) = @_;
                   7761:     my @code=split(//,$code);
                   7762:     my @orig=split(//,$orig);
                   7763:     my $same=0;
                   7764:     for (my $i=0;$i<scalar(@code);$i++) {
                   7765: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7766:     }
                   7767:     return $same;
                   7768: }
                   7769: 
1.423     albertel 7770: =pod
                   7771: 
                   7772: =item scantron_get_closely_matching_CODEs
                   7773: 
1.424     albertel 7774:    Cycles through all CODEs and finds the set that has the greatest
                   7775:    number of same characters as the provided CODE
                   7776: 
                   7777:  Arguments:
                   7778:    $allcodes - hash ref returned by &get_codes()
                   7779:    $CODE     - CODE from the current scanline
                   7780: 
                   7781:  Returns:
                   7782:    2 element list
                   7783:     - first elements is number of how closely matching the best fit is 
                   7784:       (5 means best set has 5 matching characters)
                   7785:     - second element is an arrary ref containing the set of valid CODEs
                   7786:       that best fit the passed in CODE
                   7787: 
1.423     albertel 7788: =cut
                   7789: 
1.194     albertel 7790: sub scantron_get_closely_matching_CODEs {
                   7791:     my ($allcodes,$CODE)=@_;
                   7792:     my @CODEs;
                   7793:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7794: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7795:     }
                   7796: 
                   7797:     return ($#CODEs,$CODEs[-1]);
                   7798: }
                   7799: 
1.423     albertel 7800: =pod
                   7801: 
                   7802: =item get_codes
                   7803: 
1.424     albertel 7804:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7805:    set of remembered CODEs.
                   7806: 
                   7807:  Arguments:
                   7808:   $old_name - name of the set of remembered CODEs
                   7809:   $cdom     - domain of the course
                   7810:   $cnum     - internal course name
                   7811: 
                   7812:  Returns:
                   7813:   %allcodes - keys are the valid CODEs, values are all 1
                   7814: 
1.423     albertel 7815: =cut
                   7816: 
1.194     albertel 7817: sub get_codes {
1.280     foxr     7818:     my ($old_name, $cdom, $cnum) = @_;
                   7819:     if (!$old_name) {
                   7820: 	$old_name=$env{'form.scantron_CODElist'};
                   7821:     }
                   7822:     if (!$cdom) {
                   7823: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7824:     }
                   7825:     if (!$cnum) {
                   7826: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7827:     }
1.278     albertel 7828:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7829: 				    $cdom,$cnum);
                   7830:     my %allcodes;
                   7831:     if ($result{"type\0$old_name"} eq 'number') {
                   7832: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7833:     } else {
                   7834: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7835:     }
1.194     albertel 7836:     return %allcodes;
                   7837: }
                   7838: 
1.423     albertel 7839: =pod
                   7840: 
                   7841: =item scantron_validate_CODE
                   7842: 
1.424     albertel 7843:    Validates all scanlines in the selected file to not have any
                   7844:    invalid or underspecified CODEs and that none of the codes are
                   7845:    duplicated if this was requested.
                   7846: 
1.423     albertel 7847: =cut
                   7848: 
1.157     albertel 7849: sub scantron_validate_CODE {
                   7850:     my ($r,$currentphase) = @_;
1.257     albertel 7851:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7852:     if ($scantron_config{'CODElocation'} &&
                   7853: 	$scantron_config{'CODEstart'} &&
                   7854: 	$scantron_config{'CODElength'}) {
1.257     albertel 7855: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7856: 	    &FIXME_blow_up()
                   7857: 	}
                   7858:     } else {
                   7859: 	return (0,$currentphase+1);
                   7860:     }
                   7861:     
                   7862:     my %usedCODEs;
                   7863: 
1.194     albertel 7864:     my %allcodes=&get_codes();
1.186     albertel 7865: 
1.582     raeburn  7866:     my $nav_error;
1.649     raeburn  7867:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7868:     if ($nav_error) {
                   7869:         $r->print(&navmap_errormsg());
                   7870:         return(1,$currentphase);
                   7871:     }
1.447     foxr     7872: 
1.186     albertel 7873:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7874:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7875: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7876: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7877: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7878: 						 $scan_data);
                   7879: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7880: 	my $error=0;
1.224     albertel 7881: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7882: 	    &scantron_get_correction($r,$i,$scan_record,
                   7883: 				     \%scantron_config,
                   7884: 				     $line,'incorrectCODE',\%allcodes);
                   7885: 	    return(1,$currentphase);
                   7886: 	}
1.221     albertel 7887: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7888: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7889: 	    &scantron_get_correction($r,$i,$scan_record,
                   7890: 				     \%scantron_config,
1.194     albertel 7891: 				     $line,'incorrectCODE',\%allcodes);
                   7892: 	    return(1,$currentphase);
1.186     albertel 7893: 	}
1.214     albertel 7894: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7895: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7896: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7897: 	    &scantron_get_correction($r,$i,$scan_record,
                   7898: 				     \%scantron_config,
1.194     albertel 7899: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7900: 	    return(1,$currentphase);
1.186     albertel 7901: 	}
1.524     raeburn  7902: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7903:     }
1.157     albertel 7904:     return (0,$currentphase+1);
                   7905: }
                   7906: 
1.423     albertel 7907: =pod
                   7908: 
                   7909: =item scantron_validate_doublebubble
                   7910: 
1.424     albertel 7911:    Validates all scanlines in the selected file to not have any
                   7912:    bubble lines with multiple bubbles marked.
                   7913: 
1.423     albertel 7914: =cut
                   7915: 
1.157     albertel 7916: sub scantron_validate_doublebubble {
                   7917:     my ($r,$currentphase) = @_;
                   7918:     #get student info
                   7919:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7920:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7921:     my (undef,undef,$sequence)=
                   7922:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7923: 
                   7924:     #get scantron line setup
1.257     albertel 7925:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7926:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7927: 
                   7928:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7929:     unless (ref($navmap)) {
                   7930:         $r->print(&navmap_errormsg());
                   7931:         return(1,$currentphase);
                   7932:     }
                   7933:     my $map=$navmap->getResourceByUrl($sequence);
                   7934:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7935:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7936:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7937:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7938: 
1.583     raeburn  7939:     my $nav_error;
1.691     raeburn  7940:     if (ref($map)) {
                   7941:         $randomorder = $map->randomorder();
                   7942:         $randompick = $map->randompick();
                   7943:         if ($randomorder || $randompick) {
                   7944:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7945:             if ($nav_error) {
                   7946:                 $r->print(&navmap_errormsg());
                   7947:                 return(1,$currentphase);
                   7948:             }
                   7949:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7950:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7951:         }
                   7952:     } else {
                   7953:         $r->print(&navmap_errormsg());
                   7954:         return(1,$currentphase);
                   7955:     }
                   7956: 
1.649     raeburn  7957:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7958:     if ($nav_error) {
                   7959:         $r->print(&navmap_errormsg());
                   7960:         return(1,$currentphase);
                   7961:     }
1.447     foxr     7962: 
1.157     albertel 7963:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7964: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7965: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7966: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7967: 						 $scan_data,undef,\%idmap,$randomorder,
                   7968:                                                  $randompick,$sequence,\@master_seq,
                   7969:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7970:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7971: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7972: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7973: 				 'doublebubble',
1.691     raeburn  7974: 				 $$scan_record{'scantron.doubleerror'},
                   7975:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7976:     	return (1,$currentphase);
                   7977:     }
                   7978:     return (0,$currentphase+1);
                   7979: }
                   7980: 
1.423     albertel 7981: 
1.503     raeburn  7982: sub scantron_get_maxbubble {
1.649     raeburn  7983:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7984:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7985: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7986: 	&restore_bubble_lines();
1.257     albertel 7987: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7988:     }
1.330     albertel 7989: 
1.447     foxr     7990:     my (undef, undef, $sequence) =
1.257     albertel 7991: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7992: 
1.447     foxr     7993:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7994:     unless (ref($navmap)) {
                   7995:         if (ref($nav_error)) {
                   7996:             $$nav_error = 1;
                   7997:         }
1.591     raeburn  7998:         return;
1.582     raeburn  7999:     }
1.191     albertel 8000:     my $map=$navmap->getResourceByUrl($sequence);
                   8001:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8002:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8003: 
                   8004:     &Apache::lonxml::clear_problem_counter();
                   8005: 
1.557     raeburn  8006:     my $uname       = $env{'user.name'};
                   8007:     my $udom        = $env{'user.domain'};
1.435     foxr     8008:     my $cid         = $env{'request.course.id'};
                   8009:     my $total_lines = 0;
                   8010:     %bubble_lines_per_response = ();
1.447     foxr     8011:     %first_bubble_line         = ();
1.503     raeburn  8012:     %subdivided_bubble_lines   = ();
                   8013:     %responsetype_per_response = ();
1.691     raeburn  8014:     %masterseq_id_responsenum  = ();
1.554     raeburn  8015: 
1.447     foxr     8016:     my $response_number = 0;
                   8017:     my $bubble_line     = 0;
1.191     albertel 8018:     foreach my $resource (@resources) {
1.691     raeburn  8019:         my $resid = $resource->id(); 
1.672     raeburn  8020:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8021:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8022:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8023: 	    foreach my $part_id (@{$parts}) {
                   8024:                 my $lines;
                   8025: 
                   8026: 	        # TODO - make this a persistent hash not an array.
                   8027: 
                   8028:                 # optionresponse, matchresponse and rankresponse type items 
                   8029:                 # render as separate sub-questions in exam mode.
                   8030:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8031:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8032:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8033:                     my ($numbub,$numshown);
                   8034:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8035:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8036:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8037:                         }
                   8038:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8039:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8040:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8041:                         }
                   8042:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8043:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8044:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8045:                         }
                   8046:                     }
                   8047:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8048:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8049:                     }
1.649     raeburn  8050:                     my $bubbles_per_row =
                   8051:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8052:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8053:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8054:                         $inner_bubble_lines++;
                   8055:                     }
                   8056:                     for (my $i=0; $i<$numshown; $i++) {
                   8057:                         $subdivided_bubble_lines{$response_number} .= 
                   8058:                             $inner_bubble_lines.',';
                   8059:                     }
                   8060:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8061:                     $lines = $numshown * $inner_bubble_lines;
                   8062:                 } else {
                   8063:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8064:                 }
1.542     raeburn  8065: 
                   8066:                 $first_bubble_line{$response_number} = $bubble_line;
                   8067: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8068:                 $responsetype_per_response{$response_number} = 
                   8069:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8070:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8071: 	        $response_number++;
                   8072: 
                   8073: 	        $bubble_line +=  $lines;
                   8074: 	        $total_lines +=  $lines;
                   8075: 	    }
                   8076:         }
                   8077:     }
1.552     raeburn  8078:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8079: 
                   8080:     &save_bubble_lines();
                   8081:     $env{'form.scantron_maxbubble'} =
                   8082: 	$total_lines;
                   8083:     return $env{'form.scantron_maxbubble'};
                   8084: }
1.523     raeburn  8085: 
1.649     raeburn  8086: sub bubblesheet_bubbles_per_row {
                   8087:     my ($scantron_config) = @_;
                   8088:     my $bubbles_per_row;
                   8089:     if (ref($scantron_config) eq 'HASH') {
                   8090:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8091:     }
                   8092:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8093:         $bubbles_per_row = 10;
                   8094:     }
                   8095:     return $bubbles_per_row;
                   8096: }
                   8097: 
1.157     albertel 8098: sub scantron_validate_missingbubbles {
                   8099:     my ($r,$currentphase) = @_;
                   8100:     #get student info
                   8101:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8102:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8103:     my (undef,undef,$sequence)=
                   8104:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8105: 
                   8106:     #get scantron line setup
1.257     albertel 8107:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8108:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8109: 
                   8110:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8111:     unless (ref($navmap)) {
                   8112:         $r->print(&navmap_errormsg());
                   8113:         return(1,$currentphase);
                   8114:     }
                   8115: 
                   8116:     my $map=$navmap->getResourceByUrl($sequence);
                   8117:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8118:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8119:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8120:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8121: 
1.582     raeburn  8122:     my $nav_error;
1.691     raeburn  8123:     if (ref($map)) {
                   8124:         $randomorder = $map->randomorder();
                   8125:         $randompick = $map->randompick();
                   8126:         if ($randomorder || $randompick) {
                   8127:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8128:             if ($nav_error) {
                   8129:                 $r->print(&navmap_errormsg());
                   8130:                 return(1,$currentphase);
                   8131:             }
                   8132:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8133:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8134:         }
                   8135:     } else {
                   8136:         $r->print(&navmap_errormsg());
                   8137:         return(1,$currentphase);
                   8138:     }
                   8139: 
                   8140: 
1.649     raeburn  8141:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8142:     if ($nav_error) {
1.691     raeburn  8143:         $r->print(&navmap_errormsg());
1.693     raeburn  8144:         return(1,$currentphase);
1.582     raeburn  8145:     }
1.691     raeburn  8146: 
1.157     albertel 8147:     if (!$max_bubble) { $max_bubble=2**31; }
                   8148:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8149: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8150: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8151: 	my $scan_record =
                   8152:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8153: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8154:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8155:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8156: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8157: 	my @to_correct;
1.470     foxr     8158: 	
                   8159: 	# Probably here's where the error is...
                   8160: 
1.157     albertel 8161: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8162:             my $lastbubble;
                   8163:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8164:                my $question = $1;
                   8165:                my $subquestion = $2;
1.691     raeburn  8166:                my ($first,$responsenum);
                   8167:                if ($randomorder || $randompick) {
                   8168:                    $responsenum = $respnumlookup{$question-1};
                   8169:                    $first = $startline{$question-1};
                   8170:                } else {
                   8171:                    $responsenum = $question-1; 
                   8172:                    $first = $first_bubble_line{$responsenum};
                   8173:                }
                   8174:                if (!defined($first)) { next; }
                   8175:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8176:                my $subcount = 1;
                   8177:                while ($subcount<$subquestion) {
                   8178:                    $first += $subans[$subcount-1];
                   8179:                    $subcount ++;
                   8180:                }
                   8181:                my $count = $subans[$subquestion-1];
                   8182:                $lastbubble = $first + $count;
                   8183:             } else {
1.691     raeburn  8184:                my ($first,$responsenum);
                   8185:                if ($randomorder || $randompick) {
                   8186:                    $responsenum = $respnumlookup{$missing-1};
                   8187:                    $first = $startline{$missing-1};
                   8188:                } else {
                   8189:                    $responsenum = $missing-1;
                   8190:                    $first = $first_bubble_line{$responsenum};
                   8191:                }
                   8192:                if (!defined($first)) { next; }
                   8193:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8194:             }
                   8195:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8196: 	    push(@to_correct,$missing);
                   8197: 	}
                   8198: 	if (@to_correct) {
                   8199: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8200: 				     $line,'missingbubble',\@to_correct,
                   8201:                                      $randomorder,$randompick,\%respnumlookup,
                   8202:                                      \%startline);
1.157     albertel 8203: 	    return (1,$currentphase);
                   8204: 	}
                   8205: 
                   8206:     }
                   8207:     return (0,$currentphase+1);
                   8208: }
                   8209: 
1.663     raeburn  8210: sub hand_bubble_option {
                   8211:     my (undef, undef, $sequence) =
                   8212:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8213:     return if ($sequence eq '');
                   8214:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8215:     unless (ref($navmap)) {
                   8216:         return;
                   8217:     }
                   8218:     my $needs_hand_bubbles;
                   8219:     my $map=$navmap->getResourceByUrl($sequence);
                   8220:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8221:     foreach my $res (@resources) {
                   8222:         if (ref($res)) {
                   8223:             if ($res->is_problem()) {
                   8224:                 my $partlist = $res->parts();
                   8225:                 foreach my $part (@{ $partlist }) {
                   8226:                     my @types = $res->responseType($part);
                   8227:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8228:                         $needs_hand_bubbles = 1;
                   8229:                         last;
                   8230:                     }
                   8231:                 }
                   8232:             }
                   8233:         }
                   8234:     }
                   8235:     if ($needs_hand_bubbles) {
                   8236:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8237:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8238:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8239:                &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 />').
                   8240:                '<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;'.
                   8241:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8242:     }
                   8243:     return;
                   8244: }
1.423     albertel 8245: 
1.82      albertel 8246: sub scantron_process_students {
1.608     www      8247:     my ($r,$symb) = @_;
1.513     foxr     8248: 
1.257     albertel 8249:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8250:     if (!$symb) {
                   8251: 	return '';
                   8252:     }
1.324     albertel 8253:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8254: 
1.257     albertel 8255:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8256:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8257:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8258:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8259:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8260:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8261:     unless (ref($navmap)) {
                   8262:         $r->print(&navmap_errormsg());
                   8263:         return '';
1.691     raeburn  8264:     }
1.83      albertel 8265:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8266:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8267:         %grader_randomlists_by_symb);
1.677     raeburn  8268:     if (ref($map)) {
                   8269:         $randomorder = $map->randomorder();
1.689     raeburn  8270:         $randompick = $map->randompick();
1.691     raeburn  8271:     } else {
                   8272:         $r->print(&navmap_errormsg());
                   8273:         return '';
1.677     raeburn  8274:     }
1.691     raeburn  8275:     my $nav_error;
1.83      albertel 8276:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8277:     if ($randomorder || $randompick) {
                   8278:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8279:         if ($nav_error) {
                   8280:             $r->print(&navmap_errormsg());
                   8281:             return '';
                   8282:         }
                   8283:     }
1.557     raeburn  8284:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8285:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8286: 
1.554     raeburn  8287:     my ($uname,$udom);
1.82      albertel 8288:     my $result= <<SCANTRONFORM;
1.81      albertel 8289: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8290:   <input type="hidden" name="command" value="scantron_configphase" />
                   8291:   $default_form_data
                   8292: SCANTRONFORM
1.82      albertel 8293:     $r->print($result);
                   8294: 
                   8295:     my @delayqueue;
1.542     raeburn  8296:     my (%completedstudents,%scandata);
1.140     albertel 8297:     
1.520     www      8298:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8299:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8300:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8301:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8302:     $r->print('<br />');
1.140     albertel 8303:     my $start=&Time::HiRes::time();
1.158     albertel 8304:     my $i=-1;
1.542     raeburn  8305:     my $started;
1.447     foxr     8306: 
1.649     raeburn  8307:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8308:     if ($nav_error) {
                   8309:         $r->print(&navmap_errormsg());
                   8310:         return '';
                   8311:     }
                   8312: 
1.513     foxr     8313:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8314:     # the user and return.
                   8315: 
                   8316:     if ($ssi_error) {
                   8317: 	$r->print("</form>");
                   8318: 	&ssi_print_error($r);
1.520     www      8319:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8320: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8321:     }
1.447     foxr     8322: 
1.542     raeburn  8323:     my %lettdig = &letter_to_digits();
                   8324:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8325:     my %orderedforcode;
1.542     raeburn  8326: 
1.157     albertel 8327:     while ($i<$scanlines->{'count'}) {
                   8328:  	($uname,$udom)=('','');
                   8329:  	$i++;
1.200     albertel 8330:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8331:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8332: 	if ($started) {
1.667     www      8333: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8334: 	}
                   8335: 	$started=1;
1.691     raeburn  8336:         my %respnumlookup = ();
                   8337:         my %startline = ();
                   8338:         my $total;
1.157     albertel 8339:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8340:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8341:                                                  $randompick,$sequence,\@master_seq,
                   8342:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8343:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8344:                                                  \$total);
1.157     albertel 8345:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8346:  					      \%idmap,$i)) {
                   8347:   	    &scantron_add_delay(\@delayqueue,$line,
                   8348:  				'Unable to find a student that matches',1);
                   8349:  	    next;
                   8350:   	}
                   8351:  	if (exists $completedstudents{$uname}) {
                   8352:  	    &scantron_add_delay(\@delayqueue,$line,
                   8353:  				'Student '.$uname.' has multiple sheets',2);
                   8354:  	    next;
                   8355:  	}
1.677     raeburn  8356:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8357:         my $user = $uname.':'.$usec;
1.157     albertel 8358:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8359: 
1.677     raeburn  8360:         my $scancode;
                   8361:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8362:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8363:             $scancode = $scan_record->{'scantron.CODE'};
                   8364:         } else {
                   8365:             $scancode = '';
                   8366:         }
                   8367: 
                   8368:         my @mapresources = @resources;
1.689     raeburn  8369:         if ($randomorder || $randompick) {
1.678     raeburn  8370:             @mapresources = 
1.691     raeburn  8371:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8372:                              \%orderedforcode);
1.677     raeburn  8373:         }
1.586     raeburn  8374:         my (%partids_by_symb,$res_error);
1.677     raeburn  8375:         foreach my $resource (@mapresources) {
1.586     raeburn  8376:             my $ressymb;
                   8377:             if (ref($resource)) {
                   8378:                 $ressymb = $resource->symb();
                   8379:             } else {
                   8380:                 $res_error = 1;
                   8381:                 last;
                   8382:             }
1.557     raeburn  8383:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8384:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8385:                 my ($analysis,$parts) =
1.672     raeburn  8386:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8387:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8388:                 $partids_by_symb{$ressymb} = $parts;
                   8389:             } else {
                   8390:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8391:             }
1.554     raeburn  8392:         }
                   8393: 
1.586     raeburn  8394:         if ($res_error) {
                   8395:             &scantron_add_delay(\@delayqueue,$line,
                   8396:                                 'An error occurred while grading student '.$uname,2);
                   8397:             next;
                   8398:         }
                   8399: 
1.330     albertel 8400: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8401:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8402: 
                   8403: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8404: 	    &scantron_putfile($scanlines,$scan_data);
                   8405: 	}
1.161     albertel 8406: 	
1.542     raeburn  8407:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8408:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8409:                                    $bubbles_per_row,$randomorder,$randompick,
                   8410:                                    \%respnumlookup,\%startline) 
                   8411:             eq 'ssi_error') {
1.542     raeburn  8412:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8413:             $r->print("</form>");
                   8414:             &ssi_print_error($r);
                   8415:             &Apache::lonnet::remove_lock($lock);
                   8416:             return '';      # Why return ''?  Beats me.
                   8417:         }
1.513     foxr     8418: 
1.692     raeburn  8419:         if (($scancode) && ($randomorder || $randompick)) {
                   8420:             my $parmresult =
                   8421:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8422:                                                        '0_examcode',2,$scancode,
                   8423:                                                        'string_examcode',$uname,
                   8424:                                                        $udom);
                   8425:         }
1.140     albertel 8426: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8427:         if ($env{'form.verifyrecord'}) {
                   8428:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8429:             if ($randompick) {
                   8430:                 if ($total) {
                   8431:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8432:                 }
                   8433:             }
                   8434: 
1.542     raeburn  8435:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8436:             chomp($studentdata);
                   8437:             $studentdata =~ s/\r$//;
                   8438:             my $studentrecord = '';
                   8439:             my $counter = -1;
1.677     raeburn  8440:             foreach my $resource (@mapresources) {
1.554     raeburn  8441:                 my $ressymb = $resource->symb();
1.542     raeburn  8442:                 ($counter,my $recording) =
                   8443:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8444:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8445:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8446:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8447:                 $studentrecord .= $recording;
                   8448:             }
                   8449:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8450:                 &Apache::lonxml::clear_problem_counter();
                   8451:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8452:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8453:                                            $bubbles_per_row,$randomorder,$randompick,
                   8454:                                            \%respnumlookup,\%startline) 
                   8455:                     eq 'ssi_error') {
1.554     raeburn  8456:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8457:                     $r->print("</form>");
                   8458:                     &ssi_print_error($r);
                   8459:                     &Apache::lonnet::remove_lock($lock);
                   8460:                     delete($completedstudents{$uname});
                   8461:                     return '';
                   8462:                 }
1.542     raeburn  8463:                 $counter = -1;
                   8464:                 $studentrecord = '';
1.677     raeburn  8465:                 foreach my $resource (@mapresources) {
1.554     raeburn  8466:                     my $ressymb = $resource->symb();
1.542     raeburn  8467:                     ($counter,my $recording) =
                   8468:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8469:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8470:                                                  \%scantron_config,\%lettdig,$numletts,
                   8471:                                                  $randomorder,$randompick,\%respnumlookup,
                   8472:                                                  \%startline);
1.542     raeburn  8473:                     $studentrecord .= $recording;
                   8474:                 }
                   8475:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8476:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8477:                     if ($scancode eq '') {
1.658     bisitz   8478:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8479:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8480:                     } else {
1.658     bisitz   8481:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8482:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8483:                     }
                   8484:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8485:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8486:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8487:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8488:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8489:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8490:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8491:                               &Apache::loncommon::end_data_table_row().
                   8492:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8493:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8494:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8495:                               &Apache::loncommon::end_data_table_row().
                   8496:                               &Apache::loncommon::end_data_table().'</p>');
                   8497:                 } else {
                   8498:                     $r->print('<br /><span class="LC_warning">'.
                   8499:                              &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 />'.
                   8500:                              &mt("As a consequence, this user's submission history records two tries.").
                   8501:                                  '</span><br />');
                   8502:                 }
                   8503:             }
                   8504:         }
1.543     raeburn  8505:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8506:     } continue {
1.330     albertel 8507: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8508: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8509:     }
1.140     albertel 8510:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8511:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8512: #    my $lasttime = &Time::HiRes::time()-$start;
                   8513: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8514: 
1.200     albertel 8515:     $r->print("</form>");
1.157     albertel 8516:     return '';
1.75      albertel 8517: }
1.157     albertel 8518: 
1.557     raeburn  8519: sub graders_resources_pass {
1.649     raeburn  8520:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8521:         $bubbles_per_row) = @_;
1.557     raeburn  8522:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8523:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8524:         foreach my $resource (@{$resources}) {
                   8525:             my $ressymb = $resource->symb();
                   8526:             my ($analysis,$parts) =
                   8527:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8528:                                           $env{'user.name'},$env{'user.domain'},
                   8529:                                           1,$bubbles_per_row);
1.557     raeburn  8530:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8531:             if (ref($analysis) eq 'HASH') {
                   8532:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8533:                     $grader_randomlists_by_symb->{$ressymb} =
                   8534:                         $analysis->{'parts_withrandomlist'};
                   8535:                 }
                   8536:             }
                   8537:         }
                   8538:     }
                   8539:     return;
                   8540: }
                   8541: 
1.678     raeburn  8542: =pod
                   8543: 
                   8544: =item users_order
                   8545: 
                   8546:   Returns array of resources in current map, ordered based on either CODE,
                   8547:   if this is a CODEd exam, or based on student's identity if this is a 
                   8548:   "NAMEd" exam.
                   8549: 
1.691     raeburn  8550:   Should be used when randomorder and/or randompick applied when the 
                   8551:   corresponding exam was printed, prior to students completing bubblesheets 
                   8552:   for the version of the exam the student received.
1.678     raeburn  8553: 
                   8554: =cut
                   8555: 
                   8556: sub users_order  {
1.691     raeburn  8557:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8558:     my @mapresources;
1.691     raeburn  8559:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8560:         return @mapresources;
1.691     raeburn  8561:     }
                   8562:     if ($scancode) {
                   8563:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8564:             @mapresources = @{$orderedforcode->{$scancode}};
                   8565:         } else {
                   8566:             $env{'form.CODE'} = $scancode;
                   8567:             my $actual_seq =
                   8568:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8569:                                                                $master_seq,
                   8570:                                                                $user,$scancode,1);
                   8571:             if (ref($actual_seq) eq 'ARRAY') {
                   8572:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8573:                 if (ref($orderedforcode) eq 'HASH') {
                   8574:                     if (@mapresources > 0) { 
                   8575:                         $orderedforcode->{$scancode} = \@mapresources;
                   8576:                     }
                   8577:                 }
                   8578:             }
                   8579:             delete($env{'form.CODE'});
1.678     raeburn  8580:         }
                   8581:     } else {
                   8582:         my $actual_seq =
                   8583:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8584:                                                            $master_seq,
1.688     raeburn  8585:                                                            $user,undef,1);
1.678     raeburn  8586:         if (ref($actual_seq) eq 'ARRAY') {
                   8587:             @mapresources = 
                   8588:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8589:         }
1.691     raeburn  8590:     }
                   8591:     return @mapresources;
1.678     raeburn  8592: }
                   8593: 
1.542     raeburn  8594: sub grade_student_bubbles {
1.691     raeburn  8595:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8596:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8597:     my $uselookup = 0;
                   8598:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8599:         (ref($startline) eq 'HASH')) {
                   8600:         $uselookup = 1;
                   8601:     }
                   8602: 
1.554     raeburn  8603:     if (ref($resources) eq 'ARRAY') {
                   8604:         my $count = 0;
                   8605:         foreach my $resource (@{$resources}) {
                   8606:             my $ressymb = $resource->symb();
                   8607:             my %form = ('submitted'      => 'scantron',
                   8608:                         'grade_target'   => 'grade',
                   8609:                         'grade_username' => $uname,
                   8610:                         'grade_domain'   => $udom,
                   8611:                         'grade_courseid' => $env{'request.course.id'},
                   8612:                         'grade_symb'     => $ressymb,
                   8613:                         'CODE'           => $scancode
                   8614:                        );
1.649     raeburn  8615:             if ($bubbles_per_row ne '') {
                   8616:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8617:             }
1.663     raeburn  8618:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8619:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8620:             }
1.554     raeburn  8621:             if (ref($parts) eq 'HASH') {
                   8622:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8623:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8624:                         if ($uselookup) {
                   8625:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8626:                         } else {
                   8627:                             $form{'scantron_questnum_start.'.$part} =
                   8628:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8629:                         }
1.554     raeburn  8630:                         $count++;
                   8631:                     }
                   8632:                 }
                   8633:             }
                   8634:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8635:             return 'ssi_error' if ($ssi_error);
                   8636:             last if (&Apache::loncommon::connection_aborted($r));
                   8637:         }
1.542     raeburn  8638:     }
                   8639:     return;
                   8640: }
                   8641: 
1.157     albertel 8642: sub scantron_upload_scantron_data {
1.608     www      8643:     my ($r,$symb)=@_;
1.565     raeburn  8644:     my $dom = $env{'request.role.domain'};
                   8645:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8646:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8647:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8648: 							  'domainid',
1.565     raeburn  8649: 							  'coursename',$dom);
                   8650:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8651:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8652:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8653:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8654:     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 8655:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8656:     function checkUpload(formname) {
                   8657: 	if (formname.upfile.value == "") {
1.579     raeburn  8658: 	    alert("'.$nofile_alert.'");
1.157     albertel 8659: 	    return false;
                   8660: 	}
1.565     raeburn  8661:         if (formname.courseid.value == "") {
1.579     raeburn  8662:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8663:             return false;
                   8664:         }
1.157     albertel 8665: 	formname.submit();
                   8666:     }
1.565     raeburn  8667: 
                   8668:     function ToSyllabus() {
                   8669:         var cdom = '."'$dom'".';
                   8670:         var cnum = document.rules.courseid.value;
                   8671:         if (cdom == "" || cdom == null) {
                   8672:             return;
                   8673:         }
                   8674:         if (cnum == "" || cnum == null) {
                   8675:            return;
                   8676:         }
                   8677:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8678:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8679:         return;
                   8680:     }
                   8681: 
1.597     wenzelju 8682: '));
                   8683:     $r->print('
1.648     bisitz   8684: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8685: 
1.492     albertel 8686: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8687: '.$default_form_data.
                   8688:   &Apache::lonhtmlcommon::start_pick_box().
                   8689:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8690:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8691:   &Apache::lonhtmlcommon::row_closure().
                   8692:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8693:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8694:   &Apache::lonhtmlcommon::row_closure().
                   8695:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8696:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8697:   &Apache::lonhtmlcommon::row_closure().
                   8698:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8699:   '<input type="file" name="upfile" size="50" />'.
                   8700:   &Apache::lonhtmlcommon::row_closure(1).
                   8701:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8702: 
1.492     albertel 8703: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8704: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8705: </form>
1.492     albertel 8706: ');
1.157     albertel 8707:     return '';
                   8708: }
                   8709: 
1.423     albertel 8710: 
1.157     albertel 8711: sub scantron_upload_scantron_data_save {
1.608     www      8712:     my($r,$symb)=@_;
1.182     albertel 8713:     my $doanotherupload=
                   8714: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8715: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8716: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8717: 	'</form>'."\n";
1.257     albertel 8718:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8719: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8720: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8721: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8722: 	unless ($symb) {
1.182     albertel 8723: 	    $r->print($doanotherupload);
                   8724: 	}
1.162     albertel 8725: 	return '';
                   8726:     }
1.257     albertel 8727:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8728:     my $uploadedfile;
1.710     bisitz   8729:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8730:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8731:         $r->print(
                   8732:             &Apache::lonhtmlcommon::confirm_success(
                   8733:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8734:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8735:     } else {
1.568     raeburn  8736:         my $result = 
                   8737:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8738:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8739:         if ($result =~ m{^/uploaded/}) {
                   8740:             $r->print(
                   8741:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8742:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8743:                         (length($env{'form.upfile'})-1),
                   8744:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8745:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8746:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8747:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8748:         } else {
                   8749:             $r->print(
                   8750:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8751:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8752:                           $result,
1.568     raeburn  8753: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8754: 	}
                   8755:     }
1.174     albertel 8756:     if ($symb) {
1.612     www      8757: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8758:     } else {
1.182     albertel 8759: 	$r->print($doanotherupload);
1.174     albertel 8760:     }
1.157     albertel 8761:     return '';
                   8762: }
                   8763: 
1.567     raeburn  8764: sub validate_uploaded_scantron_file {
                   8765:     my ($cdom,$cname,$fname) = @_;
                   8766:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8767:     my @lines;
                   8768:     if ($scanlines ne '-1') {
                   8769:         @lines=split("\n",$scanlines,-1);
                   8770:     }
                   8771:     my $output;
                   8772:     if (@lines) {
                   8773:         my (%counts,$max_match_format);
1.710     bisitz   8774:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8775:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8776:         my %idmap = &username_to_idmap($classlist);
                   8777:         foreach my $key (keys(%idmap)) {
                   8778:             my $lckey = lc($key);
                   8779:             $idmap{$lckey} = $idmap{$key};
                   8780:         }
                   8781:         my %unique_formats;
                   8782:         my @formatlines = &get_scantronformat_file();
                   8783:         foreach my $line (@formatlines) {
                   8784:             chomp($line);
                   8785:             my @config = split(/:/,$line);
                   8786:             my $idstart = $config[5];
                   8787:             my $idlength = $config[6];
                   8788:             if (($idstart ne '') && ($idlength > 0)) {
                   8789:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8790:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8791:                 } else {
                   8792:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8793:                 }
                   8794:             }
                   8795:         }
                   8796:         foreach my $key (keys(%unique_formats)) {
                   8797:             my ($idstart,$idlength) = split(':',$key);
                   8798:             %{$counts{$key}} = (
                   8799:                                'found'   => 0,
                   8800:                                'total'   => 0,
                   8801:                               );
                   8802:             foreach my $line (@lines) {
                   8803:                 next if ($line =~ /^#/);
                   8804:                 next if ($line =~ /^[\s\cz]*$/);
                   8805:                 my $id = substr($line,$idstart-1,$idlength);
                   8806:                 $id = lc($id);
                   8807:                 if (exists($idmap{$id})) {
                   8808:                     $counts{$key}{'found'} ++;
                   8809:                 }
                   8810:                 $counts{$key}{'total'} ++;
                   8811:             }
                   8812:             if ($counts{$key}{'total'}) {
                   8813:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8814:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8815:                     $max_match_pct = $percent_match;
                   8816:                     $max_match_format = $key;
1.710     bisitz   8817:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8818:                     $max_match_count = $counts{$key}{'total'};
                   8819:                 }
                   8820:             }
                   8821:         }
                   8822:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8823:             my $format_descs;
                   8824:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8825:             for (my $i=0; $i<$numwithformat; $i++) {
                   8826:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8827:                 if ($i<$numwithformat-2) {
                   8828:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8829:                 } elsif ($i==$numwithformat-2) {
                   8830:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8831:                 } elsif ($i==$numwithformat-1) {
                   8832:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8833:                 }
                   8834:             }
                   8835:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8836:             $output .= '<br />';
                   8837:             if ($found_match_count == $max_match_count) {
                   8838:                 # 100% matching entries
                   8839:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8840:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8841:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8842:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8843:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8844:                     ' in the file (for the format defined for [_3]).',
                   8845:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8846:             } else {
                   8847:                 # Not all entries matching? -> Show warning and additional info
                   8848:                 $output .=
                   8849:                     &Apache::lonhtmlcommon::confirm_success(
                   8850:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8851:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8852:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8853:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8854:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8855:                         ' in the file (for the format defined for [_3]).',
                   8856:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8857:                     '<p class="LC_info">'.
                   8858:                     &mt('A low percentage of matches results from one of the following:').
                   8859:                     '</p><ul>'.
                   8860:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8861:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8862:                                '<i>'.$cdom.'</i>').'</li>'.
                   8863:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8864:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8865:                     '</ul>';
                   8866:             }
1.567     raeburn  8867:         }
                   8868:     } else {
1.710     bisitz   8869:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8870:     }
                   8871:     return $output;
                   8872: }
                   8873: 
1.202     albertel 8874: sub valid_file {
                   8875:     my ($requested_file)=@_;
                   8876:     foreach my $filename (sort(&scantron_filenames())) {
                   8877: 	if ($requested_file eq $filename) { return 1; }
                   8878:     }
                   8879:     return 0;
                   8880: }
                   8881: 
                   8882: sub scantron_download_scantron_data {
1.608     www      8883:     my ($r,$symb)=@_;
                   8884:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8885:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8886:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8887:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8888:     if (! &valid_file($file)) {
1.492     albertel 8889: 	$r->print('
1.202     albertel 8890: 	<p>
1.686     bisitz   8891: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8892:         </p>
1.492     albertel 8893: ');
1.202     albertel 8894: 	return;
                   8895:     }
                   8896:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8897:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8898:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8899:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8900:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8901:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8902:     $r->print('
1.202     albertel 8903:     <p>
1.711     bisitz   8904: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
1.492     albertel 8905: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8906:     </p>
                   8907:     <p>
1.492     albertel 8908: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8909: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8910:     </p>
                   8911:     <p>
1.492     albertel 8912: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8913: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8914:     </p>
1.492     albertel 8915: ');
1.202     albertel 8916:     return '';
                   8917: }
1.157     albertel 8918: 
1.523     raeburn  8919: sub checkscantron_results {
1.608     www      8920:     my ($r,$symb) = @_;
1.523     raeburn  8921:     if (!$symb) {return '';}
                   8922:     my $cid = $env{'request.course.id'};
1.542     raeburn  8923:     my %lettdig = &letter_to_digits();
1.523     raeburn  8924:     my $numletts = scalar(keys(%lettdig));
                   8925:     my $cnum = $env{'course.'.$cid.'.num'};
                   8926:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8927:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8928:     my %record;
                   8929:     my %scantron_config =
                   8930:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8931:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8932:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8933:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8934:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8935:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8936:     unless (ref($navmap)) {
                   8937:         $r->print(&navmap_errormsg());
                   8938:         return '';
                   8939:     }
1.523     raeburn  8940:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8941:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8942:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8943:     if (ref($map)) { 
                   8944:         $randomorder=$map->randomorder();
1.689     raeburn  8945:         $randompick=$map->randompick();
1.677     raeburn  8946:     }
1.557     raeburn  8947:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8948:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8949:     if ($nav_error) {
                   8950:         $r->print(&navmap_errormsg());
                   8951:         return '';
1.678     raeburn  8952:     }
1.673     raeburn  8953:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8954:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8955:     my ($uname,$udom);
1.523     raeburn  8956:     my (%scandata,%lastname,%bylast);
                   8957:     $r->print('
                   8958: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8959: 
                   8960:     my @delayqueue;
                   8961:     my %completedstudents;
                   8962: 
1.691     raeburn  8963:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8964:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8965:     my ($username,$domain,$started);
1.649     raeburn  8966:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8967:     if ($nav_error) {
                   8968:         $r->print(&navmap_errormsg());
                   8969:         return '';
                   8970:     }
1.523     raeburn  8971: 
1.667     www      8972:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8973:     my $start=&Time::HiRes::time();
                   8974:     my $i=-1;
                   8975: 
                   8976:     while ($i<$scanlines->{'count'}) {
                   8977:         ($username,$domain,$uname)=('','','');
                   8978:         $i++;
                   8979:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8980:         if ($line=~/^[\s\cz]*$/) { next; }
                   8981:         if ($started) {
1.667     www      8982:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8983:         }
                   8984:         $started=1;
                   8985:         my $scan_record=
                   8986:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8987:                                                      $scan_data);
1.693     raeburn  8988:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8989:                                               \%idmap,$i)) {
1.523     raeburn  8990:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8991:                                 'Unable to find a student that matches',1);
                   8992:             next;
                   8993:         }
                   8994:         if (exists $completedstudents{$uname}) {
                   8995:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8996:                                 'Student '.$uname.' has multiple sheets',2);
                   8997:             next;
                   8998:         }
                   8999:         my $pid = $scan_record->{'scantron.ID'};
                   9000:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9001:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9002:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9003:         my $user = $uname.':'.$usec;
1.523     raeburn  9004:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9005: 
1.678     raeburn  9006:         my $scancode;
1.677     raeburn  9007:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9008:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9009:             $scancode = $scan_record->{'scantron.CODE'};
                   9010:         } else {
                   9011:             $scancode = '';
                   9012:         }
                   9013: 
                   9014:         my @mapresources = @resources;
1.691     raeburn  9015:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9016:         my %respnumlookup=();
                   9017:         my %startline=();
1.689     raeburn  9018:         if ($randomorder || $randompick) {
1.678     raeburn  9019:             @mapresources =
1.691     raeburn  9020:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9021:                              \%orderedforcode);
                   9022:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9023:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9024:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9025:                                              \%respnumlookup,\%startline);
                   9026:             if ($randompick && $total) {
                   9027:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9028:             }
1.677     raeburn  9029:         }
1.691     raeburn  9030:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9031:         chomp($scandata{$pid});
                   9032:         $scandata{$pid} =~ s/\r$//;
                   9033: 
1.523     raeburn  9034:         my $counter = -1;
1.677     raeburn  9035:         foreach my $resource (@mapresources) {
1.557     raeburn  9036:             my $parts;
1.554     raeburn  9037:             my $ressymb = $resource->symb();
1.557     raeburn  9038:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9039:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9040:                 (my $analysis,$parts) =
1.672     raeburn  9041:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9042:                                               $username,$domain,undef,
                   9043:                                               $bubbles_per_row);
1.557     raeburn  9044:             } else {
                   9045:                 $parts = $grader_partids_by_symb{$ressymb};
                   9046:             }
1.542     raeburn  9047:             ($counter,my $recording) =
                   9048:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9049:                                          $scandata{$pid},$parts,
1.691     raeburn  9050:                                          \%scantron_config,\%lettdig,$numletts,
                   9051:                                          $randomorder,$randompick,
                   9052:                                          \%respnumlookup,\%startline);
1.542     raeburn  9053:             $record{$pid} .= $recording;
1.523     raeburn  9054:         }
                   9055:     }
                   9056:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9057:     $r->print('<br />');
                   9058:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9059:     $passed = 0;
                   9060:     $failed = 0;
                   9061:     $numstudents = 0;
                   9062:     foreach my $last (sort(keys(%bylast))) {
                   9063:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9064:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9065:                 my $showscandata = $scandata{$pid};
                   9066:                 my $showrecord = $record{$pid};
                   9067:                 $showscandata =~ s/\s/&nbsp;/g;
                   9068:                 $showrecord =~ s/\s/&nbsp;/g;
                   9069:                 if ($scandata{$pid} eq $record{$pid}) {
                   9070:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9071:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9072: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9073: '</tr>'."\n".
                   9074: '<tr class="'.$css_class.'">'."\n".
                   9075: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   9076:                     $passed ++;
                   9077:                 } else {
                   9078:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9079:                     $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  9080: '</tr>'."\n".
                   9081: '<tr class="'.$css_class.'">'."\n".
                   9082: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   9083: '</tr>'."\n";
                   9084:                     $failed ++;
                   9085:                 }
                   9086:                 $numstudents ++;
                   9087:             }
                   9088:         }
                   9089:     }
1.648     bisitz   9090:     $r->print(
                   9091:         '<p>'
                   9092:        .&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).',
                   9093:             '<b>',
                   9094:             $numstudents,
                   9095:             '</b>',
                   9096:             $env{'form.scantron_maxbubble'})
                   9097:        .'</p>'
                   9098:     );
1.682     raeburn  9099:     $r->print('<p>'
1.683     raeburn  9100:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9101:              .'<br />'
                   9102:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9103:              .'</p>'
                   9104:     );
1.523     raeburn  9105:     if ($passed) {
1.572     www      9106:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9107:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9108:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9109:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9110:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9111:                  $okstudents."\n".
                   9112:                  &Apache::loncommon::end_data_table().'<br />');
                   9113:     }
                   9114:     if ($failed) {
1.572     www      9115:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9116:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9117:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9118:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9119:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9120:                  $badstudents."\n".
                   9121:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9122:                  &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  9123:     }
1.614     www      9124:     $r->print('</form><br />');
1.523     raeburn  9125:     return;
                   9126: }
                   9127: 
1.542     raeburn  9128: sub verify_scantron_grading {
1.554     raeburn  9129:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9130:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9131:         $respnumlookup,$startline) = @_;
1.542     raeburn  9132:     my ($record,%expected,%startpos);
                   9133:     return ($counter,$record) if (!ref($resource));
                   9134:     return ($counter,$record) if (!$resource->is_problem());
                   9135:     my $symb = $resource->symb();
1.554     raeburn  9136:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9137:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9138:         $counter ++;
                   9139:         $expected{$part_id} = 0;
1.691     raeburn  9140:         my $respnum = $counter;
                   9141:         if ($randomorder || $randompick) {
                   9142:             $respnum = $respnumlookup->{$counter};
                   9143:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9144:         } else {
                   9145:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9146:         }
                   9147:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9148:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9149:             foreach my $item (@sub_lines) {
                   9150:                 $expected{$part_id} += $item;
                   9151:             }
                   9152:         } else {
1.691     raeburn  9153:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9154:         }
                   9155:     }
                   9156:     if ($symb) {
                   9157:         my %recorded;
                   9158:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9159:         if ($returnhash{'version'}) {
                   9160:             my %lasthash=();
                   9161:             my $version;
                   9162:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9163:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9164:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9165:                 }
                   9166:             }
                   9167:             foreach my $key (keys(%lasthash)) {
                   9168:                 if ($key =~ /\.scantron$/) {
                   9169:                     my $value = &unescape($lasthash{$key});
                   9170:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9171:                     if ($value eq '') {
                   9172:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9173:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9174:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9175:                             }
                   9176:                         }
                   9177:                     } else {
                   9178:                         my @tocheck;
                   9179:                         my @items = split(//,$value);
                   9180:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9181:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9182:                             if (@items < $expected{$part_id}) {
                   9183:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9184:                                 my @singles = split(//,$fragment);
                   9185:                                 foreach my $pos (@singles) {
                   9186:                                     if ($pos eq ' ') {
                   9187:                                         push(@tocheck,$pos);
                   9188:                                     } else {
                   9189:                                         my $next = shift(@items);
                   9190:                                         push(@tocheck,$next);
                   9191:                                     }
                   9192:                                 }
                   9193:                             } else {
                   9194:                                 @tocheck = @items;
                   9195:                             }
                   9196:                             foreach my $letter (@tocheck) {
                   9197:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9198:                                     if ($letter !~ /^[A-J]$/) {
                   9199:                                         $letter = $scantron_config->{'Qoff'};
                   9200:                                     }
                   9201:                                     $recorded{$part_id} .= $letter;
                   9202:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9203:                                     my $digit;
                   9204:                                     if ($letter !~ /^[A-J]$/) {
                   9205:                                         $digit = $scantron_config->{'Qoff'};
                   9206:                                     } else {
                   9207:                                         $digit = $lettdig->{$letter};
                   9208:                                     }
                   9209:                                     $recorded{$part_id} .= $digit;
                   9210:                                 }
                   9211:                             }
                   9212:                         } else {
                   9213:                             @tocheck = @items;
                   9214:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9215:                                 my $curr_sub = shift(@tocheck);
                   9216:                                 my $digit;
                   9217:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9218:                                     $digit = $lettdig->{$curr_sub}-1;
                   9219:                                 }
                   9220:                                 if ($curr_sub eq 'J') {
                   9221:                                     $digit += scalar($numletts);
                   9222:                                 }
                   9223:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9224:                                     if ($j == $digit) {
                   9225:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9226:                                     } else {
                   9227:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9228:                                     }
                   9229:                                 }
                   9230:                             }
                   9231:                         }
                   9232:                     }
                   9233:                 }
                   9234:             }
                   9235:         }
1.554     raeburn  9236:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9237:             if ($recorded{$part_id} eq '') {
                   9238:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9239:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9240:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9241:                     }
                   9242:                 }
                   9243:             }
                   9244:             $record .= $recorded{$part_id};
                   9245:         }
                   9246:     }
                   9247:     return ($counter,$record);
                   9248: }
                   9249: 
1.691     raeburn  9250: sub letter_to_digits {
1.542     raeburn  9251:     my %lettdig = (
                   9252:                     A => 1,
                   9253:                     B => 2,
                   9254:                     C => 3,
                   9255:                     D => 4,
                   9256:                     E => 5,
                   9257:                     F => 6,
                   9258:                     G => 7,
                   9259:                     H => 8,
                   9260:                     I => 9,
                   9261:                     J => 0,
                   9262:                   );
                   9263:     return %lettdig;
                   9264: }
                   9265: 
1.423     albertel 9266: 
1.75      albertel 9267: #-------- end of section for handling grading scantron forms -------
                   9268: #
                   9269: #-------------------------------------------------------------------
                   9270: 
1.72      ng       9271: #-------------------------- Menu interface -------------------------
                   9272: #
1.614     www      9273: #--- Href with symb and command ---
                   9274: 
                   9275: sub href_symb_cmd {
                   9276:     my ($symb,$cmd)=@_;
1.669     raeburn  9277:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9278: }
                   9279: 
1.443     banghart 9280: sub grading_menu {
1.608     www      9281:     my ($request,$symb) = @_;
1.443     banghart 9282:     if (!$symb) {return '';}
                   9283: 
                   9284:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9285:                   'command'=>'individual');
1.538     schulted 9286:     
1.598     www      9287:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9288: 
                   9289:     $fields{'command'}='ungraded';
                   9290:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9291: 
                   9292:     $fields{'command'}='table';
                   9293:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9294: 
                   9295:     $fields{'command'}='all_for_one';
                   9296:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9297: 
1.621     www      9298:     $fields{'command'}='downloadfilesselect';
                   9299:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9300: 
1.443     banghart 9301:     $fields{'command'} = 'csvform';
1.538     schulted 9302:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9303:     
1.443     banghart 9304:     $fields{'command'} = 'processclicker';
1.538     schulted 9305:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9306:     
1.443     banghart 9307:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9308:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9309: 
                   9310:     $fields{'command'} = 'initialverifyreceipt';
                   9311:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9312:     
1.598     www      9313:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9314:             items =>[
1.598     www      9315:                         {	linktext => 'Select individual students to grade',
                   9316:                     		url => $url1a,
1.538     schulted 9317:                     		permission => 'F',
1.636     wenzelju 9318:                     		icon => 'grade_students.png',
1.598     www      9319:                     		linktitle => 'Grade current resource for a selection of students.'
                   9320:                         }, 
                   9321:                         {       linktext => 'Grade ungraded submissions.',
                   9322:                                 url => $url1b,
                   9323:                                 permission => 'F',
1.636     wenzelju 9324:                                 icon => 'ungrade_sub.png',
1.598     www      9325:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9326:                         },
1.598     www      9327: 
                   9328:                         {       linktext => 'Grading table',
                   9329:                                 url => $url1c,
                   9330:                                 permission => 'F',
1.636     wenzelju 9331:                                 icon => 'grading_table.png',
1.598     www      9332:                                 linktitle => 'Grade current resource for all students.'
                   9333:                         },
1.615     www      9334:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9335:                                 url => $url1d,
                   9336:                                 permission => 'F',
1.636     wenzelju 9337:                                 icon => 'grade_PageFolder.png',
1.598     www      9338:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9339:                         },
                   9340:                         {       linktext => 'Download submissions',
                   9341:                                 url => $url1e,
                   9342:                                 permission => 'F',
1.636     wenzelju 9343:                                 icon => 'download_sub.png',
1.621     www      9344:                                 linktitle => 'Download all students submissions.'
1.598     www      9345:                         }]},
                   9346:                          { categorytitle=>'Automated Grading',
                   9347:                items =>[
                   9348: 
1.538     schulted 9349:                 	    {	linktext => 'Upload Scores',
                   9350:                     		url => $url2,
                   9351:                     		permission => 'F',
                   9352:                     		icon => 'uploadscores.png',
                   9353:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9354:                 	    },
                   9355:                 	    {	linktext => 'Process Clicker',
                   9356:                     		url => $url3,
                   9357:                     		permission => 'F',
                   9358:                     		icon => 'addClickerInfoFile.png',
                   9359:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9360:                 	    },
1.587     raeburn  9361:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9362:                     		url => $url4,
                   9363:                     		permission => 'F',
1.636     wenzelju 9364:                     		icon => 'bubblesheet.png',
1.648     bisitz   9365:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9366:                 	    },
1.616     www      9367:                             {   linktext => 'Verify Receipt Number',
1.602     www      9368:                                 url => $url5,
                   9369:                                 permission => 'F',
1.636     wenzelju 9370:                                 icon => 'receipt_number.png',
1.602     www      9371:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9372:                             }
                   9373: 
1.538     schulted 9374:                     ]
                   9375:             });
                   9376: 
1.443     banghart 9377:     # Create the menu
                   9378:     my $Str;
1.445     banghart 9379:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9380:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9381:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9382: 
1.602     www      9383:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9384:     return $Str;    
                   9385: }
                   9386: 
1.598     www      9387: 
                   9388: sub ungraded {
                   9389:     my ($request)=@_;
                   9390:     &submit_options($request);
                   9391: }
                   9392: 
1.599     www      9393: sub submit_options_sequence {
1.608     www      9394:     my ($request,$symb) = @_;
1.599     www      9395:     if (!$symb) {return '';}
1.600     www      9396:     &commonJSfunctions($request);
                   9397:     my $result;
1.599     www      9398: 
1.600     www      9399:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9400:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9401:     $result.=&selectfield(0).
1.601     www      9402:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9403:             <div>
                   9404:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9405:             </div>
                   9406:         </div>
                   9407:   </form>';
                   9408:     return $result;
                   9409: }
                   9410: 
                   9411: sub submit_options_table {
1.608     www      9412:     my ($request,$symb) = @_;
1.600     www      9413:     if (!$symb) {return '';}
1.599     www      9414:     &commonJSfunctions($request);
                   9415:     my $result;
                   9416: 
                   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.599     www      9419: 
1.632     www      9420:     $result.=&selectfield(0).
1.601     www      9421:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9422:             <div>
                   9423:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9424:             </div>
                   9425:         </div>
                   9426:   </form>';
                   9427:     return $result;
                   9428: }
1.443     banghart 9429: 
1.621     www      9430: sub submit_options_download {
                   9431:     my ($request,$symb) = @_;
                   9432:     if (!$symb) {return '';}
                   9433: 
                   9434:     &commonJSfunctions($request);
                   9435: 
                   9436:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9437:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9438:     $result.='
                   9439: <h2>
                   9440:   '.&mt('Select Students for Which to Download Submissions').'
                   9441: </h2>'.&selectfield(1).'
                   9442:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9443:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9444:             </div>
                   9445:           </div>
1.600     www      9446: 
                   9447: 
1.621     www      9448:   </form>';
                   9449:     return $result;
                   9450: }
                   9451: 
1.443     banghart 9452: #--- Displays the submissions first page -------
                   9453: sub submit_options {
1.608     www      9454:     my ($request,$symb) = @_;
1.72      ng       9455:     if (!$symb) {return '';}
                   9456: 
1.118     ng       9457:     &commonJSfunctions($request);
1.473     albertel 9458:     my $result;
1.533     bisitz   9459: 
1.72      ng       9460:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9461: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9462:     $result.=&selectfield(1).'
1.601     www      9463:                 <input type="hidden" name="command" value="submission" /> 
                   9464: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9465:             </div>
                   9466:           </div>
                   9467: 
                   9468: 
                   9469:   </form>';
                   9470:     return $result;
                   9471: }
1.533     bisitz   9472: 
1.601     www      9473: sub selectfield {
                   9474:    my ($full)=@_;
1.635     raeburn  9475:    my %options = 
                   9476:           (&Apache::lonlocal::texthash(
                   9477:              'yes'       => 'with submissions',
                   9478:              'queued'    => 'in grading queue',
                   9479:              'graded'    => 'with ungraded submissions',
                   9480:              'incorrect' => 'with incorrect submissions',
                   9481:              'all'       => 'with any status'),
                   9482:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9483:    my $result='<div class="LC_columnSection">
1.537     harmsja  9484:   
1.533     bisitz   9485:     <fieldset>
                   9486:       <legend>
                   9487:        '.&mt('Sections').'
                   9488:       </legend>
1.601     www      9489:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9490:     </fieldset>
1.537     harmsja  9491:   
1.533     bisitz   9492:     <fieldset>
                   9493:       <legend>
                   9494:         '.&mt('Groups').'
                   9495:       </legend>
                   9496:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9497:     </fieldset>
1.537     harmsja  9498:   
1.533     bisitz   9499:     <fieldset>
                   9500:       <legend>
                   9501:         '.&mt('Access Status').'
                   9502:       </legend>
1.601     www      9503:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9504:     </fieldset>';
                   9505:     if ($full) {
                   9506:        $result.='
1.533     bisitz   9507:     <fieldset>
                   9508:       <legend>
                   9509:         '.&mt('Submission Status').'
1.601     www      9510:       </legend>'.
1.635     raeburn  9511:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9512:    '</fieldset>';
                   9513:     }
                   9514:     $result.='</div><br />';
1.44      ng       9515:     return $result;
1.2       albertel 9516: }
                   9517: 
1.285     albertel 9518: sub reset_perm {
                   9519:     undef(%perm);
                   9520: }
                   9521: 
                   9522: sub init_perm {
                   9523:     &reset_perm();
1.300     albertel 9524:     foreach my $test_perm ('vgr','mgr','opa') {
                   9525: 
                   9526: 	my $scope = $env{'request.course.id'};
                   9527: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9528: 
                   9529: 	    $scope .= '/'.$env{'request.course.sec'};
                   9530: 	    if ( $perm{$test_perm}=
                   9531: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9532: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9533: 	    } else {
                   9534: 		delete($perm{$test_perm});
                   9535: 	    }
1.285     albertel 9536: 	}
                   9537:     }
                   9538: }
                   9539: 
1.674     raeburn  9540: sub init_old_essays {
                   9541:     my ($symb,$apath,$adom,$aname) = @_;
                   9542:     if ($symb ne '') {
                   9543:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9544:         if (keys(%essays) > 0) {
                   9545:             $old_essays{$symb} = \%essays;
                   9546:         }
                   9547:     }
                   9548:     return;
                   9549: }
                   9550: 
                   9551: sub reset_old_essays {
                   9552:     undef(%old_essays);
                   9553: }
                   9554: 
1.400     www      9555: sub gather_clicker_ids {
1.408     albertel 9556:     my %clicker_ids;
1.400     www      9557: 
                   9558:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9559: 
                   9560:     # Set up a couple variables.
1.407     albertel 9561:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9562:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9563:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9564: 
1.407     albertel 9565:     foreach my $student (keys(%$classlist)) {
1.438     www      9566:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9567:         my $username = $classlist->{$student}->[$username_idx];
                   9568:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9569:         my $clickers =
1.408     albertel 9570: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9571:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9572:             $id=~s/^[\#0]+//;
1.421     www      9573:             $id=~s/[\-\:]//g;
1.407     albertel 9574:             if (exists($clicker_ids{$id})) {
1.408     albertel 9575: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9576:             } else {
1.408     albertel 9577: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9578:             }
                   9579:         }
                   9580:     }
1.407     albertel 9581:     return %clicker_ids;
1.400     www      9582: }
                   9583: 
1.402     www      9584: sub gather_adv_clicker_ids {
1.408     albertel 9585:     my %clicker_ids;
1.402     www      9586:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9587:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9588:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9589:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9590:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9591:             my ($puname,$pudom)=split(/\:/,$person);
                   9592:             my $clickers =
1.408     albertel 9593: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9594:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9595: 		$id=~s/^[\#0]+//;
1.421     www      9596:                 $id=~s/[\-\:]//g;
1.408     albertel 9597: 		if (exists($clicker_ids{$id})) {
                   9598: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9599: 		} else {
                   9600: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9601: 		}
1.405     www      9602:             }
1.402     www      9603:         }
                   9604:     }
1.407     albertel 9605:     return %clicker_ids;
1.402     www      9606: }
                   9607: 
1.413     www      9608: sub clicker_grading_parameters {
                   9609:     return ('gradingmechanism' => 'scalar',
                   9610:             'upfiletype' => 'scalar',
                   9611:             'specificid' => 'scalar',
                   9612:             'pcorrect' => 'scalar',
                   9613:             'pincorrect' => 'scalar');
                   9614: }
                   9615: 
1.400     www      9616: sub process_clicker {
1.608     www      9617:     my ($r,$symb)=@_;
1.400     www      9618:     if (!$symb) {return '';}
                   9619:     my $result=&checkforfile_js();
1.632     www      9620:     $result.=&Apache::loncommon::start_data_table().
                   9621:              &Apache::loncommon::start_data_table_header_row().
                   9622:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9623:              &Apache::loncommon::end_data_table_header_row().
                   9624:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9625: # Attempt to restore parameters from last session, set defaults if not present
                   9626:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9627:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9628:                                                  \%Saveable_Parameters);
                   9629:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9630:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9631:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9632:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9633: 
                   9634:     my %checked;
1.521     www      9635:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9636:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9637:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9638:        }
                   9639:     }
                   9640: 
1.632     www      9641:     my $upload=&mt("Evaluate File");
1.400     www      9642:     my $type=&mt("Type");
1.402     www      9643:     my $attendance=&mt("Award points just for participation");
                   9644:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9645:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9646:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9647:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9648:     my $pcorrect=&mt("Percentage points for correct solution");
                   9649:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9650:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9651: 						   {'iclicker' => 'i>clicker',
1.666     www      9652:                                                     'interwrite' => 'interwrite PRS',
                   9653:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9654:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9655:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9656: function sanitycheck() {
                   9657: // Accept only integer percentages
                   9658:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9659:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9660: // Find out grading choice
                   9661:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9662:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9663:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9664:       }
                   9665:    }
                   9666: // By default, new choice equals user selection
                   9667:    newgradingchoice=gradingchoice;
                   9668: // Not good to give more points for false answers than correct ones
                   9669:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9670:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9671:    }
                   9672: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9673:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9674:       document.forms.gradesupload.pcorrect.value=100;
                   9675:       document.forms.gradesupload.pincorrect.value=100;
                   9676:    }
                   9677: // If the values are different, cannot be attendance only
                   9678:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9679:        (gradingchoice=='attendance')) {
                   9680:        newgradingchoice='personnel';
                   9681:    }
                   9682: // Change grading choice to new one
                   9683:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9684:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9685:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9686:       } else {
                   9687:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9688:       }
                   9689:    }
                   9690: // Remember the old state
                   9691:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9692: }
1.597     wenzelju 9693: ENDUPFORM
                   9694:     $result.= <<ENDUPFORM;
1.400     www      9695: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9696: <input type="hidden" name="symb" value="$symb" />
                   9697: <input type="hidden" name="command" value="processclickerfile" />
                   9698: <input type="file" name="upfile" size="50" />
                   9699: <br /><label>$type: $selectform</label>
1.632     www      9700: ENDUPFORM
                   9701:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9702:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9703:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9704: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9705: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9706: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9707: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9708: <br />&nbsp;&nbsp;&nbsp;
                   9709: <input type="text" name="givenanswer" size="50" />
1.413     www      9710: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9711: ENDGRADINGFORM
                   9712:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9713:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9714:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9715: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9716: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9717: </form>'
1.632     www      9718: ENDPERCFORM
                   9719:     $result.='</td>'.
                   9720:              &Apache::loncommon::end_data_table_row().
                   9721:              &Apache::loncommon::end_data_table();
1.400     www      9722:     return $result;
                   9723: }
                   9724: 
                   9725: sub process_clicker_file {
1.608     www      9726:     my ($r,$symb)=@_;
1.400     www      9727:     if (!$symb) {return '';}
1.413     www      9728: 
                   9729:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9730:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9731:                                               \%Saveable_Parameters);
1.598     www      9732:     my $result='';
1.404     www      9733:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9734: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9735: 	return $result;
1.404     www      9736:     }
1.522     www      9737:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9738:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9739:         return $result;
1.521     www      9740:     }
1.522     www      9741:     my $foundgiven=0;
1.521     www      9742:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9743:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9744:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9745:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9746:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9747:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9748:         $foundgiven=$#answers+1;
1.521     www      9749:     }
1.407     albertel 9750:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9751:     my %correct_ids;
1.404     www      9752:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9753: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9754:     }
                   9755:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9756: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9757: 	   $correct_id=~tr/a-z/A-Z/;
                   9758: 	   $correct_id=~s/\s//gs;
                   9759: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9760:            $correct_id=~s/[\-\:]//g;
1.414     www      9761:            if ($correct_id) {
                   9762: 	      $correct_ids{$correct_id}='specified';
                   9763:            }
                   9764:         }
1.400     www      9765:     }
1.404     www      9766:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9767: 	$result.=&mt('Score based on attendance only');
1.521     www      9768:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9769:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9770:     } else {
1.408     albertel 9771: 	my $number=0;
1.411     www      9772: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9773: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9774: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9775: 	    if ($correct_ids{$id} eq 'specified') {
                   9776: 		$result.=&mt('specified');
                   9777: 	    } else {
                   9778: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9779: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9780: 	    }
                   9781: 	    $number++;
                   9782: 	}
1.411     www      9783:         $result.="</p>\n";
1.710     bisitz   9784:         if ($number==0) {
                   9785:             $result .=
                   9786:                  &Apache::lonhtmlcommon::confirm_success(
                   9787:                      &mt('No IDs found to determine correct answer'),1);
                   9788:             return $result;
                   9789:         }
1.404     www      9790:     }
1.405     www      9791:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9792:         $result .=
                   9793:             &Apache::lonhtmlcommon::confirm_success(
                   9794:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9795:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9796:         return $result;
1.405     www      9797:     }
1.410     www      9798: 
                   9799: # Were able to get all the info needed, now analyze the file
                   9800: 
1.411     www      9801:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9802:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9803:     $result.=&Apache::loncommon::start_data_table().
                   9804:              &Apache::loncommon::start_data_table_header_row().
                   9805:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9806:              &Apache::loncommon::end_data_table_header_row().
                   9807:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9808: <td>
1.410     www      9809: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9810: <input type="hidden" name="symb" value="$symb" />
                   9811: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9812: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9813: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9814: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9815: ENDHEADER
1.522     www      9816:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9817:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9818:     } 
1.408     albertel 9819:     my %responses;
                   9820:     my @questiontitles;
1.405     www      9821:     my $errormsg='';
                   9822:     my $number=0;
                   9823:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9824: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9825:     }
1.419     www      9826:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9827:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9828:     }
1.666     www      9829:     if ($env{'form.upfiletype'} eq 'turning') {
                   9830:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9831:     }
1.411     www      9832:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9833:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9834:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9835:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9836:              '<br />';
1.522     www      9837:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9838:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9839:        return $result;
1.522     www      9840:     } 
1.414     www      9841: # Remember Question Titles
                   9842: # FIXME: Possibly need delimiter other than ":"
                   9843:     for (my $i=0;$i<$number;$i++) {
                   9844:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9845:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9846:     }
1.411     www      9847:     my $correct_count=0;
                   9848:     my $student_count=0;
                   9849:     my $unknown_count=0;
1.414     www      9850: # Match answers with usernames
                   9851: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9852:     foreach my $id (keys(%responses)) {
1.410     www      9853:        if ($correct_ids{$id}) {
1.414     www      9854:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9855:           $correct_count++;
1.410     www      9856:        } elsif ($clicker_ids{$id}) {
1.437     www      9857:           if ($clicker_ids{$id}=~/\,/) {
                   9858: # More than one user with the same clicker!
1.632     www      9859:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9860:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9861:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9862:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9863:                            "<select name='multi".$id."'>";
                   9864:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9865:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9866:              }
                   9867:              $result.='</select>';
                   9868:              $unknown_count++;
                   9869:           } else {
                   9870: # Good: found one and only one user with the right clicker
                   9871:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9872:              $student_count++;
                   9873:           }
1.410     www      9874:        } else {
1.632     www      9875:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9876:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9877:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9878:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9879:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9880:                    "\n".&mt("Domain").": ".
                   9881:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9882:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9883:           $unknown_count++;
1.410     www      9884:        }
1.405     www      9885:     }
1.412     www      9886:     $result.='<hr />'.
                   9887:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9888:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9889:        if ($correct_count==0) {
1.696     bisitz   9890:           $errormsg.="Found no correct answers for grading!";
1.412     www      9891:        } elsif ($correct_count>1) {
1.414     www      9892:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9893:        }
                   9894:     }
1.428     www      9895:     if ($number<1) {
                   9896:        $errormsg.="Found no questions.";
                   9897:     }
1.412     www      9898:     if ($errormsg) {
                   9899:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9900:     } else {
                   9901:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9902:     }
1.632     www      9903:     $result.='</form></td>'.
                   9904:              &Apache::loncommon::end_data_table_row().
                   9905:              &Apache::loncommon::end_data_table();
1.614     www      9906:     return $result;
1.400     www      9907: }
                   9908: 
1.405     www      9909: sub iclicker_eval {
1.406     www      9910:     my ($questiontitles,$responses)=@_;
1.405     www      9911:     my $number=0;
                   9912:     my $errormsg='';
                   9913:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9914:         my %components=&Apache::loncommon::record_sep($line);
                   9915:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9916: 	if ($entries[0] eq 'Question') {
                   9917: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9918: 		$$questiontitles[$number]=$entries[$i];
                   9919: 		$number++;
                   9920: 	    }
                   9921: 	}
                   9922: 	if ($entries[0]=~/^\#/) {
                   9923: 	    my $id=$entries[0];
                   9924: 	    my @idresponses;
                   9925: 	    $id=~s/^[\#0]+//;
                   9926: 	    for (my $i=0;$i<$number;$i++) {
                   9927: 		my $idx=3+$i*6;
1.644     www      9928:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9929: 		push(@idresponses,$entries[$idx]);
                   9930: 	    }
                   9931: 	    $$responses{$id}=join(',',@idresponses);
                   9932: 	}
1.405     www      9933:     }
                   9934:     return ($errormsg,$number);
                   9935: }
                   9936: 
1.419     www      9937: sub interwrite_eval {
                   9938:     my ($questiontitles,$responses)=@_;
                   9939:     my $number=0;
                   9940:     my $errormsg='';
1.420     www      9941:     my $skipline=1;
                   9942:     my $questionnumber=0;
                   9943:     my %idresponses=();
1.419     www      9944:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9945:         my %components=&Apache::loncommon::record_sep($line);
                   9946:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9947:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9948:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9949:         next if $skipline;
                   9950:         if ($entries[0]!=$questionnumber) {
                   9951:            $questionnumber=$entries[0];
                   9952:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9953:            $number++;
1.419     www      9954:         }
1.420     www      9955:         my $id=$entries[4];
                   9956:         $id=~s/^[\#0]+//;
1.421     www      9957:         $id=~s/^v\d*\://i;
                   9958:         $id=~s/[\-\:]//g;
1.420     www      9959:         $idresponses{$id}[$number]=$entries[6];
                   9960:     }
1.524     raeburn  9961:     foreach my $id (keys(%idresponses)) {
1.420     www      9962:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9963:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9964:     }
                   9965:     return ($errormsg,$number);
                   9966: }
                   9967: 
1.666     www      9968: sub turning_eval {
                   9969:     my ($questiontitles,$responses)=@_;
                   9970:     my $number=0;
                   9971:     my $errormsg='';
                   9972:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9973:         my %components=&Apache::loncommon::record_sep($line);
                   9974:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9975:         if ($#entries>$number) { $number=$#entries; }
                   9976:         my $id=$entries[0];
                   9977:         my @idresponses;
                   9978:         $id=~s/^[\#0]+//;
                   9979:         unless ($id) { next; }
                   9980:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9981:             $entries[$idx]=~s/\,/\;/g;
                   9982:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9983:             push(@idresponses,$entries[$idx]);
                   9984:         }
                   9985:         $$responses{$id}=join(',',@idresponses);
                   9986:     }
                   9987:     for (my $i=1; $i<=$number; $i++) {
                   9988:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9989:     }
                   9990:     return ($errormsg,$number);
                   9991: }
                   9992: 
                   9993: 
1.414     www      9994: sub assign_clicker_grades {
1.608     www      9995:     my ($r,$symb)=@_;
1.414     www      9996:     if (!$symb) {return '';}
1.416     www      9997: # See which part we are saving to
1.582     raeburn  9998:     my $res_error;
                   9999:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10000:     if ($res_error) {
                   10001:         return &navmap_errormsg();
                   10002:     }
1.416     www      10003: # FIXME: This should probably look for the first handgradeable part
                   10004:     my $part=$$partlist[0];
                   10005: # Start screen output
1.632     www      10006:     my $result=&Apache::loncommon::start_data_table().
                   10007:              &Apache::loncommon::start_data_table_header_row().
                   10008:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10009:              &Apache::loncommon::end_data_table_header_row().
                   10010:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10011: # Get correct result
                   10012: # FIXME: Possibly need delimiter other than ":"
                   10013:     my @correct=();
1.415     www      10014:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10015:     my $number=$env{'form.number'};
                   10016:     if ($gradingmechanism ne 'attendance') {
1.414     www      10017:        foreach my $key (keys(%env)) {
                   10018:           if ($key=~/^form\.correct\:/) {
                   10019:              my @input=split(/\,/,$env{$key});
                   10020:              for (my $i=0;$i<=$#input;$i++) {
                   10021:                  if (($correct[$i]) && ($input[$i]) &&
                   10022:                      ($correct[$i] ne $input[$i])) {
                   10023:                     $result.='<br /><span class="LC_warning">'.
                   10024:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10025:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10026:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10027:                     $correct[$i]=$input[$i];
                   10028:                  }
                   10029:              }
                   10030:           }
                   10031:        }
1.415     www      10032:        for (my $i=0;$i<$number;$i++) {
1.644     www      10033:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10034:              $result.='<br /><span class="LC_error">'.
                   10035:                       &mt('No correct result given for question "[_1]"!',
                   10036:                           $env{'form.question:'.$i}).'</span>';
                   10037:           }
                   10038:        }
1.644     www      10039:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10040:     }
                   10041: # Start grading
1.415     www      10042:     my $pcorrect=$env{'form.pcorrect'};
                   10043:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10044:     my $storecount=0;
1.632     www      10045:     my %users=();
1.415     www      10046:     foreach my $key (keys(%env)) {
1.420     www      10047:        my $user='';
1.415     www      10048:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10049:           $user=$1;
                   10050:        }
                   10051:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10052:           my $id=$1;
                   10053:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10054:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10055:           } elsif ($env{'form.multi'.$id}) {
                   10056:              $user=$env{'form.multi'.$id};
1.420     www      10057:           }
                   10058:        }
1.632     www      10059:        if ($user) {
                   10060:           if ($users{$user}) {
                   10061:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10062:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10063:                       '</span><br />';
                   10064:           }
                   10065:           $users{$user}=1; 
1.415     www      10066:           my @answer=split(/\,/,$env{$key});
                   10067:           my $sum=0;
1.522     www      10068:           my $realnumber=$number;
1.415     www      10069:           for (my $i=0;$i<$number;$i++) {
1.576     www      10070:              if  ($correct[$i] eq '-') {
                   10071:                 $realnumber--;
1.644     www      10072:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10073:                 if ($gradingmechanism eq 'attendance') {
                   10074:                    $sum+=$pcorrect;
1.576     www      10075:                 } elsif ($correct[$i] eq '*') {
1.522     www      10076:                    $sum+=$pcorrect;
1.415     www      10077:                 } else {
1.644     www      10078: # We actually grade if correct or not
                   10079:                    my $increment=$pincorrect;
                   10080: # Special case: numerical answer "0"
                   10081:                    if ($correct[$i] eq '0') {
                   10082:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10083:                          $increment=$pcorrect;
                   10084:                       }
                   10085: # General numerical answer, both evaluate to something non-zero
                   10086:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10087:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10088:                          $increment=$pcorrect;
                   10089:                       }
                   10090: # Must be just alphanumeric
                   10091:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10092:                       $increment=$pcorrect;
1.415     www      10093:                    }
1.644     www      10094:                    $sum+=$increment;
1.415     www      10095:                 }
                   10096:              }
                   10097:           }
1.522     www      10098:           my $ave=$sum/(100*$realnumber);
1.416     www      10099: # Store
                   10100:           my ($username,$domain)=split(/\:/,$user);
                   10101:           my %grades=();
                   10102:           $grades{"resource.$part.solved"}='correct_by_override';
                   10103:           $grades{"resource.$part.awarded"}=$ave;
                   10104:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10105:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10106:                                                  $env{'request.course.id'},
                   10107:                                                  $domain,$username);
                   10108:           if ($returncode ne 'ok') {
                   10109:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10110:           } else {
                   10111:              $storecount++;
                   10112:           }
1.415     www      10113:        }
                   10114:     }
                   10115: # We are done
1.549     hauer    10116:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10117:              '</td>'.
                   10118:              &Apache::loncommon::end_data_table_row().
                   10119:              &Apache::loncommon::end_data_table();
1.614     www      10120:     return $result;
1.414     www      10121: }
                   10122: 
1.582     raeburn  10123: sub navmap_errormsg {
                   10124:     return '<div class="LC_error">'.
                   10125:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10126:            &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  10127:            '</div>';
                   10128: }
1.607     droeschl 10129: 
1.609     www      10130: sub startpage {
1.671     raeburn  10131:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10132:     if ($nomenu) {
                   10133:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10134:     } else {
                   10135:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10136:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10137:                                                  {'bread_crumbs' => $crumbs}));
                   10138:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10139:     }
1.613     www      10140:     unless ($nodisplayflag) {
1.671     raeburn  10141:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10142:     }
1.607     droeschl 10143: }
1.582     raeburn  10144: 
1.622     www      10145: sub select_problem {
                   10146:     my ($r)=@_;
1.632     www      10147:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10148:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10149:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10150:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10151: }
                   10152: 
1.1       albertel 10153: sub handler {
1.41      ng       10154:     my $request=$_[0];
1.434     albertel 10155:     &reset_caches();
1.646     raeburn  10156:     if ($request->header_only) {
                   10157:         &Apache::loncommon::content_type($request,'text/html');
                   10158:         $request->send_http_header;
                   10159:         return OK;
                   10160:     }
                   10161:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10162: 
1.664     raeburn  10163: # see what command we need to execute
                   10164: 
                   10165:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10166:     my $command=$commands[0];
                   10167: 
1.646     raeburn  10168:     &init_perm();
                   10169:     if (!$env{'request.course.id'}) {
1.664     raeburn  10170:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10171:                 ($command =~ /^scantronupload/)) {
                   10172:             # Not in a course.
                   10173:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10174:             return HTTP_NOT_ACCEPTABLE;
                   10175:         }
1.646     raeburn  10176:     } elsif (!%perm) {
                   10177:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10178:         return OK;
1.41      ng       10179:     }
1.646     raeburn  10180:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10181:     $request->send_http_header;
1.646     raeburn  10182: 
1.160     albertel 10183:     if ($#commands > 0) {
                   10184: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10185:     }
1.608     www      10186: 
                   10187: # see what the symb is
                   10188: 
                   10189:     my $symb=$env{'form.symb'};
                   10190:     unless ($symb) {
                   10191:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10192:        $symb=&Apache::lonnet::symbread($url);
                   10193:     }
1.646     raeburn  10194:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10195: 
1.513     foxr     10196:     $ssi_error = 0;
1.637     www      10197:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10198: #
1.637     www      10199: # Not called from a resource, but inside a course
1.601     www      10200: #    
1.622     www      10201:         &startpage($request,undef,[],1,1);
                   10202:         &select_problem($request);
1.41      ng       10203:     } else {
1.104     albertel 10204: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10205:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10206:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10207:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10208:                     &choose_task_version_form($symb,$env{'form.student'},
                   10209:                                               $env{'form.userdom'});
                   10210:             }
                   10211:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10212:             if ($versionform) {
                   10213:                 $request->print($versionform);
                   10214:             }
                   10215:             $request->print('<br clear="all" />');
1.611     www      10216: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10217:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10218:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10219:                 &choose_task_version_form($symb,$env{'form.student'},
                   10220:                                           $env{'form.userdom'},
                   10221:                                           $env{'form.inhibitmenu'});
                   10222:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10223:             if ($versionform) {
                   10224:                 $request->print($versionform);
                   10225:             }
                   10226:             $request->print('<br clear="all" />');
                   10227:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10228: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10229:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10230:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10231: 	    &pickStudentPage($request,$symb);
1.103     albertel 10232: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10233:             &startpage($request,$symb,
                   10234:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10235:                                        {href=>'',text=>'Select student'},
                   10236:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10237: 	    &displayPage($request,$symb);
1.104     albertel 10238: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10239:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10240:                                        {href=>'',text=>'Select student'},
                   10241:                                        {href=>'',text=>'Grade student'},
                   10242:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10243: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10244: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10245:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10246:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10247: 	    &processGroup($request,$symb);
1.104     albertel 10248: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10249:             &startpage($request,$symb);
                   10250: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10251: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10252:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10253: 	    $request->print(&submit_options($request,$symb));
1.598     www      10254:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10255:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10256:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10257:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10258:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10259:             $request->print(&submit_options_table($request,$symb));
1.598     www      10260:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10261:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10262:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10263: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10264:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10265: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10266: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10267:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10268:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10269: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10270: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10271:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10272:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10273:                                                                              text=>"Modify grades"},
                   10274:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10275: 	    $request->print(&editgrades($request,$symb));
1.602     www      10276:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10277:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10278:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10279: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10280:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10281:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10282: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10283:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10284:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10285:             $request->print(&process_clicker($request,$symb));
1.400     www      10286:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10287:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10288:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10289:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10290:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10291:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10292:                                        {href=>'', text=>'Process clicker file'},
                   10293:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10294:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10295: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10296:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10297: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10298: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10299:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10300: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10301: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10302:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10303: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10304: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10305: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10306:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10307: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10308: 	    } else {
1.257     albertel 10309: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10310: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10311: 		} else {
1.257     albertel 10312: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10313: 		}
1.627     www      10314:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10315: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10316: 	    }
1.246     albertel 10317: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10318:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10319: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10320: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10321:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10322: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10323:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10324:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10325:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10326: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10327:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10328: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10329: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10330:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10331: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10332:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10333:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10334: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10336:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10337:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10338:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10339: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10340:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10341:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10342:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10343: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10344:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10345:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10346:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10347:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10348:             $request->print(&checkscantron_results($request,$symb));
                   10349:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10350:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10351:             $request->print(&submit_options_download($request,$symb));
                   10352:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10353:             &startpage($request,$symb,
                   10354:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10355:     {href=>'', text=>'Download submissions'}]);
                   10356:             &submit_download_link($request,$symb);
1.106     albertel 10357: 	} elsif ($command) {
1.620     www      10358:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10359: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10360: 	}
1.2       albertel 10361:     }
1.513     foxr     10362:     if ($ssi_error) {
                   10363: 	&ssi_print_error($request);
                   10364:     }
1.671     raeburn  10365:     if ($env{'form.inhibitmenu'}) {
                   10366:         $request->print(&Apache::loncommon::end_page());
                   10367:     } else {
                   10368:         &Apache::lonquickgrades::endGradeScreen($request);
                   10369:     }
1.434     albertel 10370:     &reset_caches();
1.646     raeburn  10371:     return OK;
1.44      ng       10372: }
                   10373: 
1.1       albertel 10374: 1;
                   10375: 
1.13      albertel 10376: __END__;
1.531     jms      10377: 
                   10378: 
                   10379: =head1 NAME
                   10380: 
                   10381: Apache::grades
                   10382: 
                   10383: =head1 SYNOPSIS
                   10384: 
                   10385: Handles the viewing of grades.
                   10386: 
                   10387: This is part of the LearningOnline Network with CAPA project
                   10388: described at http://www.lon-capa.org.
                   10389: 
                   10390: =head1 OVERVIEW
                   10391: 
                   10392: Do an ssi with retries:
1.715     bisitz   10393: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10394: 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
                   10395: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10396: 
                   10397: At least the logic that drives this has been pulled out into loncommon.
                   10398: 
                   10399: 
                   10400: 
                   10401: ssi_with_retries - Does the server side include of a resource.
                   10402:                      if the ssi call returns an error we'll retry it up to
                   10403:                      the number of times requested by the caller.
1.715     bisitz   10404:                      If we still have a problem, no text is appended to the
1.531     jms      10405:                      output and we set some global variables.
                   10406:                      to indicate to the caller an SSI error occurred.  
                   10407:                      All of this is supposed to deal with the issues described
1.715     bisitz   10408:                      in LON-CAPA BZ 5631 see:
1.531     jms      10409:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10410:                      by informing the user that this happened.
                   10411: 
                   10412: Parameters:
                   10413:   resource   - The resource to include.  This is passed directly, without
                   10414:                interpretation to lonnet::ssi.
                   10415:   form       - The form hash parameters that guide the interpretation of the resource
                   10416:                
                   10417:   retries    - Number of retries allowed before giving up completely.
                   10418: Returns:
                   10419:   On success, returns the rendered resource identified by the resource parameter.
                   10420: Side Effects:
                   10421:   The following global variables can be set:
                   10422:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10423:                               It is up to the caller to initialize this to false
                   10424:                               if desired.
                   10425:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10426:                               of the resource that could not be rendered by the ssi
                   10427:                               call.
                   10428:    ssi_error_message   - The error string fetched from the ssi response
                   10429:                               in the event of an error.
                   10430: 
                   10431: 
                   10432: =head1 HANDLER SUBROUTINE
                   10433: 
                   10434: ssi_with_retries()
                   10435: 
                   10436: =head1 SUBROUTINES
                   10437: 
                   10438: =over
                   10439: 
1.671     raeburn  10440: =head1 Routines to display previous version of a Task for a specific student
                   10441: 
                   10442: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10443: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10444: requires a proctor to check-in the student, a new version of the Task will
                   10445: be created when the student is checked in to the new opportunity.
                   10446: 
                   10447: If a particular student has tried two or more versions of a particular task,
                   10448: the submission screen provides a user with vgr privileges (e.g., a Course
                   10449: Coordinator) the ability to display a previous version worked on by the
                   10450: student.  By default, the current version is displayed. If a previous version
                   10451: has been selected for display, submission data are only shown that pertain
                   10452: to that particular version, and the interface to submit grades is not shown.
                   10453: 
                   10454: =over 4
                   10455: 
                   10456: =item show_previous_task_version()
                   10457: 
                   10458: Displays a specified version of a student's Task, as the student sees it.
                   10459: 
                   10460: Inputs: 2
                   10461:         request - request object
                   10462:         symb    - unique symb for current instance of resource
                   10463: 
                   10464: Output: None.
                   10465: 
                   10466: Side Effects: calls &show_problem() to print version of Task, with
                   10467:               version contained in form item: $env{'form.previousversion'}
                   10468: 
                   10469: =item choose_task_version_form()
                   10470: 
                   10471: Displays a web form used to select which version of a student's view of a
                   10472: Task should be displayed.  Either launches a pop-up window, or replaces
                   10473: content in existing pop-up, or replaces page in main window.
                   10474: 
                   10475: Inputs: 4
                   10476:         symb    - unique symb for current instance of resource
                   10477:         uname   - username of student
                   10478:         udom    - domain of student
                   10479:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10480:                   breadcrumbs etc., are displayed
                   10481: 
                   10482: Output: 4
                   10483:         current   - student's current version
                   10484:         displayed - student's version being displayed
                   10485:         result    - scalar containing HTML for web form used to switch to
                   10486:                     a different version (or a link to close window, if pop-up).
                   10487:         js        - javascript for processing selection in versions web form
                   10488: 
                   10489: Side Effects: None.
                   10490: 
                   10491: =item previous_display_javascript()
                   10492: 
                   10493: Inputs: 2
                   10494:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10495:                   breadcrumbs etc., are displayed.
                   10496:         current - student's current version number.
                   10497: 
                   10498: Output: 1
                   10499:         js      - javascript for processing selection in versions web form.
                   10500: 
                   10501: Side Effects: None.
                   10502: 
                   10503: =back
                   10504: 
                   10505: =head1 Routines to process bubblesheet data.
                   10506: 
                   10507: =over 4
                   10508: 
1.531     jms      10509: =item scantron_get_correction() : 
                   10510: 
                   10511:    Builds the interface screen to interact with the operator to fix a
                   10512:    specific error condition in a specific scanline
                   10513: 
                   10514:  Arguments:
                   10515:     $r           - Apache request object
                   10516:     $i           - number of the current scanline
                   10517:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10518:     $scan_config - hash ref as returned from &get_scantron_config()
                   10519:     $line        - full contents of the current scanline
                   10520:     $error       - error condition, valid values are
                   10521:                    'incorrectCODE', 'duplicateCODE',
                   10522:                    'doublebubble', 'missingbubble',
                   10523:                    'duplicateID', 'incorrectID'
                   10524:     $arg         - extra information needed
                   10525:        For errors:
                   10526:          - duplicateID   - paper number that this studentID was seen before on
                   10527:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10528:                            seen on before
                   10529:          - incorrectCODE - current incorrect CODE 
                   10530:          - doublebubble  - array ref of the bubble lines that have double
                   10531:                            bubble errors
                   10532:          - missingbubble - array ref of the bubble lines that have missing
                   10533:                            bubble errors
                   10534: 
1.691     raeburn  10535:    $randomorder - True if exam folder has randomorder set
                   10536:    $randompick  - True if exam folder has randompick set
                   10537:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10538:                      for current line to question number used for same question
                   10539:                      in "Master Seqence" (as seen by Course Coordinator).
                   10540:    $startline   - Reference to hash where key is question number (0 is first)
                   10541:                   and value is number of first bubble line for current student
                   10542:                   or code-based randompick and/or randomorder.
                   10543: 
                   10544: 
                   10545: 
1.531     jms      10546: =item  scantron_get_maxbubble() : 
                   10547: 
1.582     raeburn  10548:    Arguments:
                   10549:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10550:                       failure to retrieve a navmap object.
                   10551:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10552:        calling routine should trap the error condition and display the warning
                   10553:        found in &navmap_errormsg().
                   10554: 
1.649     raeburn  10555:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10556: 
1.531     jms      10557:    Returns the maximum number of bubble lines that are expected to
                   10558:    occur. Does this by walking the selected sequence rendering the
                   10559:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10560:    for what the current value of the problem counter is.
                   10561: 
                   10562:    Caches the results to $env{'form.scantron_maxbubble'},
                   10563:    $env{'form.scantron.bubble_lines.n'}, 
                   10564:    $env{'form.scantron.first_bubble_line.n'} and
                   10565:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10566:    which are the total number of bubble lines, the number of bubble
1.531     jms      10567:    lines for response n and number of the first bubble line for response n,
                   10568:    and a comma separated list of numbers of bubble lines for sub-questions
                   10569:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10570: 
                   10571: 
                   10572: =item  scantron_validate_missingbubbles() : 
                   10573: 
                   10574:    Validates all scanlines in the selected file to not have any
                   10575:     answers that don't have bubbles that have not been verified
                   10576:     to be bubble free.
                   10577: 
                   10578: =item  scantron_process_students() : 
                   10579: 
1.659     raeburn  10580:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10581: 
                   10582:    The parsed scanline hash is added to %env 
                   10583: 
                   10584:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10585:    foreach resource , with the form data of
                   10586: 
                   10587: 	'submitted'     =>'scantron' 
                   10588: 	'grade_target'  =>'grade',
                   10589: 	'grade_username'=> username of student
                   10590: 	'grade_domain'  => domain of student
                   10591: 	'grade_courseid'=> of course
                   10592: 	'grade_symb'    => symb of resource to grade
                   10593: 
                   10594:     This triggers a grading pass. The problem grading code takes care
                   10595:     of converting the bubbled letter information (now in %env) into a
                   10596:     valid submission.
                   10597: 
                   10598: =item  scantron_upload_scantron_data() :
                   10599: 
1.659     raeburn  10600:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10601: 
                   10602: =item  scantron_upload_scantron_data_save() : 
                   10603: 
                   10604:    Adds a provided bubble information data file to the course if user
                   10605:    has the correct privileges to do so. 
                   10606: 
                   10607: =item  valid_file() :
                   10608: 
                   10609:    Validates that the requested bubble data file exists in the course.
                   10610: 
                   10611: =item  scantron_download_scantron_data() : 
                   10612: 
                   10613:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10614:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10615:    course.
                   10616: 
                   10617: =item  scantron_validate_ID() : 
                   10618: 
                   10619:    Validates all scanlines in the selected file to not have any
1.556     weissno  10620:    invalid or underspecified student/employee IDs
1.531     jms      10621: 
1.582     raeburn  10622: =item navmap_errormsg() :
                   10623: 
                   10624:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10625:    Should be called whenever the request to instantiate a navmap object fails.
                   10626: 
                   10627: =back
1.582     raeburn  10628: 
1.531     jms      10629: =back
                   10630: 
                   10631: =cut

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