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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.715   ! bisitz      4: # $Id: grades.pm,v 1.714 2014/01/18 01:44:47 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
                    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.440     albertel  440:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    441: 	$answer = 
                    442: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    443: 							      $answer);
1.122     ng        444:     }
1.118     ng        445:     return $answer;
                    446: }
                    447: 
                    448: #-- A couple of common js functions
                    449: sub commonJSfunctions {
                    450:     my $request = shift;
1.597     wenzelju  451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        452:     function radioSelection(radioButton) {
                    453: 	var selection=null;
                    454: 	if (radioButton.length > 1) {
                    455: 	    for (var i=0; i<radioButton.length; i++) {
                    456: 		if (radioButton[i].checked) {
                    457: 		    return radioButton[i].value;
                    458: 		}
                    459: 	    }
                    460: 	} else {
                    461: 	    if (radioButton.checked) return radioButton.value;
                    462: 	}
                    463: 	return selection;
                    464:     }
                    465: 
                    466:     function pullDownSelection(selectOne) {
                    467: 	var selection="";
                    468: 	if (selectOne.length > 1) {
                    469: 	    for (var i=0; i<selectOne.length; i++) {
                    470: 		if (selectOne[i].selected) {
                    471: 		    return selectOne[i].value;
                    472: 		}
                    473: 	    }
                    474: 	} else {
1.138     albertel  475:             // only one value it must be the selected one
                    476: 	    return selectOne.value;
1.118     ng        477: 	}
                    478:     }
                    479: COMMONJSFUNCTIONS
                    480: }
                    481: 
1.44      ng        482: #--- Dumps the class list with usernames,list of sections,
                    483: #--- section, ids and fullnames for each user.
                    484: sub getclasslist {
1.449     banghart  485:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  486:     my @getsec;
1.450     banghart  487:     my @getgroup;
1.442     banghart  488:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  489:     if (!ref($getsec)) {
                    490: 	if ($getsec ne '' && $getsec ne 'all') {
                    491: 	    @getsec=($getsec);
                    492: 	}
                    493:     } else {
                    494: 	@getsec=@{$getsec};
                    495:     }
                    496:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  497:     if (!ref($getgroup)) {
                    498: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    499: 	    @getgroup=($getgroup);
                    500: 	}
                    501:     } else {
                    502: 	@getgroup=@{$getgroup};
                    503:     }
                    504:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  505: 
1.449     banghart  506:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  507:     # Bail out if we were unable to get the classlist
1.56      matthew   508:     return if (! defined($classlist));
1.449     banghart  509:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   510:     #
                    511:     my %sections;
                    512:     my %fullnames;
1.205     matthew   513:     foreach my $student (keys(%$classlist)) {
                    514:         my $end      = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    516:         my $start    = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    518:         my $id       = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    520:         my $section  = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    522:         my $fullname = 
                    523:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    524:         my $status   = 
                    525:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  526:         my $group   = 
                    527:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        528: 	# filter students according to status selected
1.442     banghart  529: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    530: 	    if (!($stu_status =~ $status)) {
1.450     banghart  531: 		delete($classlist->{$student});
1.76      ng        532: 		next;
                    533: 	    }
                    534: 	}
1.450     banghart  535: 	# filter students according to groups selected
1.453     banghart  536: 	my @stu_groups = split(/,/,$group);
1.450     banghart  537: 	if (@getgroup) {
                    538: 	    my $exclude = 1;
1.454     banghart  539: 	    foreach my $grp (@getgroup) {
                    540: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  541: 	            if ($stu_group eq $grp) {
                    542: 	                $exclude = 0;
                    543:     	            } 
1.450     banghart  544: 	        }
1.453     banghart  545:     	        if (($grp eq 'none') && !$group) {
                    546:         	        $exclude = 0;
                    547:         	}
1.450     banghart  548: 	    }
                    549: 	    if ($exclude) {
                    550: 	        delete($classlist->{$student});
                    551: 	    }
                    552: 	}
1.205     matthew   553: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  554: 	if (&canview($section)) {
1.291     albertel  555: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  556: 		$sections{$section}++;
1.450     banghart  557: 		if ($classlist->{$student}) {
                    558: 		    $fullnames{$student}=$fullname;
                    559: 		}
1.103     albertel  560: 	    } else {
1.205     matthew   561: 		delete($classlist->{$student});
1.103     albertel  562: 	    }
                    563: 	} else {
1.205     matthew   564: 	    delete($classlist->{$student});
1.103     albertel  565: 	}
1.44      ng        566:     }
                    567:     my %seen = ();
1.56      matthew   568:     my @sections = sort(keys(%sections));
                    569:     return ($classlist,\@sections,\%fullnames);
1.44      ng        570: }
                    571: 
1.103     albertel  572: sub canmodify {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'mgr'}) {
                    575: 	if (!defined($perm{'mgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'mgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
                    592: sub canview {
                    593:     my ($sec)=@_;
                    594:     if ($perm{'vgr'}) {
                    595: 	if (!defined($perm{'vgr_section'})) {
                    596: 	    # can modify whole class
                    597: 	    return 1;
                    598: 	} else {
                    599: 	    if ($sec eq $perm{'vgr_section'}) {
                    600: 		#can modify the requested section
                    601: 		return 1;
                    602: 	    } else {
                    603: 		# can't modify the request section
                    604: 		return 0;
                    605: 	    }
                    606: 	}
                    607:     }
                    608:     #can't modify
                    609:     return 0;
                    610: }
                    611: 
1.44      ng        612: #--- Retrieve the grade status of a student for all the parts
                    613: sub student_gradeStatus {
1.324     albertel  614:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  615:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        616:     my %partstatus = ();
                    617:     foreach (@$partlist) {
1.128     ng        618: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        619: 	$status              = 'nothing' if ($status eq '');
                    620: 	$partstatus{$_}      = $status;
                    621: 	my $subkey           = "resource.$_.submitted_by";
                    622: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    623:     }
                    624:     return %partstatus;
                    625: }
                    626: 
1.45      ng        627: # hidden form and javascript that calls the form
                    628: # Use by verifyscript and viewgrades
                    629: # Shows a student's view of problem and submission
                    630: sub jscriptNform {
1.324     albertel  631:     my ($symb) = @_;
1.442     banghart  632:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  633:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        634: 	'    function viewOneStudent(user,domain) {'."\n".
                    635: 	'	document.onestudent.student.value = user;'."\n".
                    636: 	'	document.onestudent.userdom.value = domain;'."\n".
                    637: 	'	document.onestudent.submit();'."\n".
                    638: 	'    }'."\n".
1.597     wenzelju  639: 	"\n");
1.45      ng        640:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  641: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        643: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    644: 	'<input type="hidden" name="student" value="" />'."\n".
                    645: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    646: 	'</form>'."\n";
                    647:     return $jscript;
                    648: }
1.39      ng        649: 
1.447     foxr      650: 
                    651: 
1.315     bowersj2  652: # Given the score (as a number [0-1] and the weight) what is the final
                    653: # point value? This function will round to the nearest tenth, third,
                    654: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  655: sub compute_points {
1.315     bowersj2  656:     my ($score, $weight) = @_;
                    657:     
                    658:     my $tolerance = .00001;
                    659:     my $points = $score * $weight;
                    660: 
                    661:     # Check for nearness to 1/x.
                    662:     my $check_for_nearness = sub {
                    663:         my ($factor) = @_;
                    664:         my $num = ($points * $factor) + $tolerance;
                    665:         my $floored_num = floor($num);
1.316     albertel  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  667:             return $floored_num / $factor;
                    668:         }
                    669:         return $points;
                    670:     };
                    671: 
                    672:     $points = $check_for_nearness->(10);
                    673:     $points = $check_for_nearness->(3);
                    674:     $points = $check_for_nearness->(4);
                    675:     
                    676:     return $points;
                    677: }
                    678: 
1.44      ng        679: #------------------ End of general use routines --------------------
1.87      www       680: 
                    681: #
                    682: # Find most similar essay
                    683: #
                    684: 
                    685: sub most_similar {
1.674     raeburn   686:     my ($uname,$udom,$symb,$uessay)=@_;
                    687: 
                    688:     unless ($symb) { return ''; }
                    689: 
                    690:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       691: 
                    692: # ignore spaces and punctuation
                    693: 
                    694:     $uessay=~s/\W+/ /gs;
                    695: 
1.282     www       696: # ignore empty submissions (occuring when only files are sent)
                    697: 
1.598     www       698:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       699: 
1.87      www       700: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       701:     my $limit=0.6;
1.87      www       702:     my $sname='';
                    703:     my $sdom='';
                    704:     my $scrsid='';
                    705:     my $sessay='';
                    706: # go through all essays ...
1.674     raeburn   707:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  708: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       709: # ... except the same student
1.426     albertel  710:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   711: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  712: 	$tessay=~s/\W+/ /gs;
1.87      www       713: # String similarity gives up if not even limit
1.426     albertel  714: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       715: # Found one
1.426     albertel  716: 	if ($tsimilar>$limit) {
                    717: 	    $limit=$tsimilar;
                    718: 	    $sname=$tname;
                    719: 	    $sdom=$tdom;
                    720: 	    $scrsid=$tcrsid;
1.674     raeburn   721: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  722: 	}
1.87      www       723:     }
1.88      www       724:     if ($limit>0.6) {
1.87      www       725:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    726:     } else {
                    727:        return ('','','','',0);
                    728:     }
                    729: }
                    730: 
1.44      ng        731: #-------------------------------------------------------------------
                    732: 
                    733: #------------------------------------ Receipt Verification Routines
1.45      ng        734: #
1.602     www       735: 
                    736: sub initialverifyreceipt {
1.608     www       737:    my ($request,$symb) = @_;
1.602     www       738:    &commonJSfunctions($request);
1.694     bisitz    739:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       740:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    741:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       742:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    743:         '<input type="hidden" name="command" value="verify" />'.
                    744:         "</form>\n";
1.602     www       745: }
                    746: 
1.44      ng        747: #--- Check whether a receipt number is valid.---
                    748: sub verifyreceipt {
1.608     www       749:     my ($request,$symb)  = @_;
1.44      ng        750: 
1.257     albertel  751:     my $courseid = $env{'request.course.id'};
1.184     www       752:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  753: 	$env{'form.receipt'};
1.44      ng        754:     $receipt     =~ s/[^\-\d]//g;
                    755: 
1.487     albertel  756:     my $title.=
                    757: 	'<h3><span class="LC_info">'.
1.605     www       758: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    759: 	'</span></h3>'."\n";
1.44      ng        760: 
                    761:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   762:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  763:     
                    764:     my $receiptparts=0;
1.390     albertel  765:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    766: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  767:     my $parts=['0'];
1.582     raeburn   768:     if ($receiptparts) {
                    769:         my $res_error; 
                    770:         ($parts)=&response_type($symb,\$res_error);
                    771:         if ($res_error) {
                    772:             return &navmap_errormsg();
                    773:         } 
                    774:     }
1.486     albertel  775:     
                    776:     my $header = 
                    777: 	&Apache::loncommon::start_data_table().
                    778: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  779: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    780: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    781: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  782:     if ($receiptparts) {
1.487     albertel  783: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  784:     }
                    785:     $header.=
                    786: 	&Apache::loncommon::end_data_table_header_row();
                    787: 
1.294     albertel  788:     foreach (sort 
                    789: 	     {
                    790: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    791: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    792: 		 }
                    793: 		 return $a cmp $b;
                    794: 	     } (keys(%$fullname))) {
1.44      ng        795: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  796: 	foreach my $part (@$parts) {
                    797: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  798: 		$contents.=
                    799: 		    &Apache::loncommon::start_data_table_row().
                    800: 		    '<td>&nbsp;'."\n".
1.177     albertel  801: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  802: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  803: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    804: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    805: 		if ($receiptparts) {
                    806: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    807: 		}
1.486     albertel  808: 		$contents.= 
                    809: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  810: 		
                    811: 		$matches++;
                    812: 	    }
1.44      ng        813: 	}
                    814:     }
                    815:     if ($matches == 0) {
1.584     bisitz    816:         $string = $title
                    817:                  .'<p class="LC_warning">'
                    818:                  .&mt('No match found for the above receipt number.')
                    819:                  .'</p>';
1.44      ng        820:     } else {
1.324     albertel  821: 	$string = &jscriptNform($symb).$title.
1.487     albertel  822: 	    '<p>'.
1.584     bisitz    823: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  824: 	    '</p>'.
1.486     albertel  825: 	    $header.
                    826: 	    $contents.
                    827: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        828:     }
1.614     www       829:     return $string;
1.44      ng        830: }
                    831: 
                    832: #--- This is called by a number of programs.
                    833: #--- Called from the Grading Menu - View/Grade an individual student
                    834: #--- Also called directly when one clicks on the subm button 
                    835: #    on the problem page.
1.30      ng        836: sub listStudents {
1.617     www       837:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  838: 
1.257     albertel  839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  842:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       843:     unless ($submitonly) {
                    844:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    845:     }
1.49      albertel  846: 
1.632     www       847:     my $result='';
1.623     www       848:     my $res_error;
                    849:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  850: 
1.559     raeburn   851:     my %lt = &Apache::lonlocal::texthash (
                    852: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    853: 		'single'   => 'Please select the student before clicking on the Next button.',
                    854: 	     );
1.597     wenzelju  855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        856:     function checkSelect(checkBox) {
                    857: 	var ctr=0;
                    858: 	var sense="";
                    859: 	if (checkBox.length > 1) {
                    860: 	    for (var i=0; i<checkBox.length; i++) {
                    861: 		if (checkBox[i].checked) {
                    862: 		    ctr++;
                    863: 		}
                    864: 	    }
1.485     albertel  865: 	    sense = '$lt{'multiple'}';
1.110     ng        866: 	} else {
                    867: 	    if (checkBox.checked) {
                    868: 		ctr = 1;
                    869: 	    }
1.485     albertel  870: 	    sense = '$lt{'single'}';
1.110     ng        871: 	}
                    872: 	if (ctr == 0) {
1.485     albertel  873: 	    alert(sense);
1.110     ng        874: 	    return false;
                    875: 	}
                    876: 	document.gradesub.submit();
                    877:     }
                    878: 
                    879:     function reLoadList(formname) {
1.112     ng        880: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        881: 	formname.command.value = 'submission';
                    882: 	formname.submit();
                    883:     }
1.45      ng        884: LISTJAVASCRIPT
                    885: 
1.118     ng        886:     &commonJSfunctions($request);
1.41      ng        887:     $request->print($result);
1.39      ng        888: 
1.154     albertel  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       890: 	"\n";
1.485     albertel  891: 	
1.561     bisitz    892:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    893:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    894:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    895:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    897:                   .&Apache::lonhtmlcommon::row_closure();
                    898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    899:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    900:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    902:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  903: 
                    904:     my $submission_options;
1.442     banghart  905:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    906:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  907:     $env{'form.Status'} = $saveStatus;
1.485     albertel  908:     $submission_options.=
1.592     bisitz    909:         '<span class="LC_nobreak">'.
1.624     www       910:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     911:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    912:         '<span class="LC_nobreak">'.
                    913:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     914:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    915:         '<span class="LC_nobreak">'.
1.628     www       916:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     917:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    918:         '<span class="LC_nobreak">'.
                    919:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     920:         &mt('all submissions with details').'</label></span>';
                    921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    922:                   .$submission_options
                    923:                   .&Apache::lonhtmlcommon::row_closure();
                    924: 
                    925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    926:                   .'<select name="increment">'
                    927:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    928:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    929:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    930:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    931:                   .'</select>'
                    932:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  933: 
                    934:     $gradeTable .= 
1.432     banghart  935:         &build_section_inputs().
1.45      ng        936: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    939: 
1.618     www       940:     if (exists($env{'form.Status'})) {
1.561     bisitz    941: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        942:     } else {
1.561     bisitz    943:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    944:                       .&Apache::lonhtmlcommon::StatusOptions(
                    945:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    946:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        947:     }
1.112     ng        948: 
1.561     bisitz    949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    950:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    951:                   .&Apache::lonhtmlcommon::row_closure(1)
                    952:                   .&Apache::lonhtmlcommon::end_pick_box();
                    953: 
                    954:     $gradeTable .= '<p>'
1.618     www       955:                   .&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    956:                   .'<input type="hidden" name="command" value="processGroup" />'
                    957:                   .'</p>';
1.249     albertel  958: 
                    959: # checkall buttons
                    960:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        961:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    962:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    963:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  964:     $gradeTable.=&check_buttons();
1.450     banghart  965:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  966:     $gradeTable.= &Apache::loncommon::start_data_table().
                    967: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        968:     my $loop = 0;
                    969:     while ($loop < 2) {
1.485     albertel  970: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    971: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       972: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  973: 	    foreach my $part (sort(@$partlist)) {
                    974: 		my $display_part=
                    975: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    976: 		$gradeTable.=
                    977: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        978: 	    }
1.301     albertel  979: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  980: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        981: 	}
                    982: 	$loop++;
1.126     ng        983: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        984:     }
1.474     albertel  985:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        986: 
1.45      ng        987:     my $ctr = 0;
1.294     albertel  988:     foreach my $student (sort 
                    989: 			 {
                    990: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    991: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    992: 			     }
                    993: 			     return $a cmp $b;
                    994: 			 }
                    995: 			 (keys(%$fullname))) {
1.41      ng        996: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  997: 
1.110     ng        998: 	my %status = ();
1.301     albertel  999: 
                   1000: 	if ($submitonly eq 'queued') {
                   1001: 	    my %queue_status = 
                   1002: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1003: 							$udom,$uname);
                   1004: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1005: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1006: 	}
                   1007: 
1.618     www      1008: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1009: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1010: 	    my $submitted = 0;
1.164     albertel 1011: 	    my $graded = 0;
1.248     albertel 1012: 	    my $incorrect = 0;
1.110     ng       1013: 	    foreach (keys(%status)) {
1.145     albertel 1014: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1015: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1016: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1017: 		
1.110     ng       1018: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1019: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1020: 		    $submitted = 0;
1.150     albertel 1021: 		    my ($part)=split(/\./,$partid);
1.110     ng       1022: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1023: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1024: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1025: 		}
1.41      ng       1026: 	    }
1.248     albertel 1027: 	    
1.156     albertel 1028: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1029: 				     $submitonly eq 'incorrect' ||
                   1030: 				     $submitonly eq 'graded'));
1.248     albertel 1031: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1032: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1033: 	}
1.34      ng       1034: 
1.45      ng       1035: 	$ctr++;
1.249     albertel 1036: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1037:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1038: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1039: 	    if ($ctr%2 ==1) {
                   1040: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1041: 	    }
1.126     ng       1042: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1043:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1044:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1045: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1046: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1047: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1048: 
1.618     www      1049: 	    if ($submitonly ne 'all') {
1.524     raeburn  1050: 		foreach (sort(keys(%status))) {
1.485     albertel 1051: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1052: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1053: 		}
1.41      ng       1054: 	    }
1.126     ng       1055: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1056: 	    if ($ctr%2 ==0) {
                   1057: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1058: 	    }
1.41      ng       1059: 	}
                   1060:     }
1.110     ng       1061:     if ($ctr%2 ==1) {
1.126     ng       1062: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1063: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1064: 		foreach (@$partlist) {
                   1065: 		    $gradeTable.='<td>&nbsp;</td>';
                   1066: 		}
1.301     albertel 1067: 	    } elsif ($submitonly eq 'queued') {
                   1068: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1069: 	    }
1.474     albertel 1070: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1071:     }
                   1072: 
1.474     albertel 1073:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1074:         '<input type="button" '.
                   1075:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1076:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1077:     if ($ctr == 0) {
1.96      albertel 1078: 	my $num_students=(scalar(keys(%$fullname)));
                   1079: 	if ($num_students eq 0) {
1.485     albertel 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1081: 	} else {
1.171     albertel 1082: 	    my $submissions='submissions';
                   1083: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1084: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1085: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1086: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1087: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1088: 		    $num_students).
                   1089: 		'</span><br />';
1.96      albertel 1090: 	}
1.46      ng       1091:     } elsif ($ctr == 1) {
1.474     albertel 1092: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1093:     }
                   1094:     $request->print($gradeTable);
1.44      ng       1095:     return '';
1.10      ng       1096: }
                   1097: 
1.44      ng       1098: #---- Called from the listStudents routine
1.249     albertel 1099: 
                   1100: sub check_script {
                   1101:     my ($form, $type)=@_;
1.597     wenzelju 1102:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1103:     function checkall() {
                   1104:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1105:             ele = document.forms.'.$form.'.elements[i];
                   1106:             if (ele.name == "'.$type.'") {
                   1107:             document.forms.'.$form.'.elements[i].checked=true;
                   1108:                                        }
                   1109:         }
                   1110:     }
                   1111: 
                   1112:     function checksec() {
                   1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1114:             ele = document.forms.'.$form.'.elements[i];
                   1115:            string = document.forms.'.$form.'.chksec.value;
                   1116:            if
                   1117:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1118:               document.forms.'.$form.'.elements[i].checked=true;
                   1119:             }
                   1120:         }
                   1121:     }
                   1122: 
                   1123: 
                   1124:     function uncheckall() {
                   1125:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1126:             ele = document.forms.'.$form.'.elements[i];
                   1127:             if (ele.name == "'.$type.'") {
                   1128:             document.forms.'.$form.'.elements[i].checked=false;
                   1129:                                        }
                   1130:         }
                   1131:     }
                   1132: 
1.597     wenzelju 1133: '."\n");
1.249     albertel 1134:     return $chkallscript;
                   1135: }
                   1136: 
                   1137: sub check_buttons {
1.485     albertel 1138:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1139:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1140:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1141:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1142:     return $buttons;
                   1143: }
                   1144: 
1.44      ng       1145: #     Displays the submissions for one student or a group of students
1.34      ng       1146: sub processGroup {
1.619     www      1147:     my ($request,$symb)  = @_;
1.41      ng       1148:     my $ctr        = 0;
1.155     albertel 1149:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1150:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1151: 
1.396     banghart 1152:     foreach my $student (@stuchecked) {
                   1153: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1154: 	$env{'form.student'}        = $uname;
                   1155: 	$env{'form.userdom'}        = $udom;
                   1156: 	$env{'form.fullname'}       = $fullname;
1.619     www      1157: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1158: 	$ctr++;
                   1159:     }
                   1160:     return '';
1.35      ng       1161: }
1.34      ng       1162: 
1.44      ng       1163: #------------------------------------------------------------------------------------
                   1164: #
                   1165: #-------------------------- Next few routines handles grading by student, essentially
                   1166: #                           handles essay response type problem/part
                   1167: #
                   1168: #--- Javascript to handle the submission page functionality ---
                   1169: sub sub_page_js {
                   1170:     my $request = shift;
1.539     riegler  1171: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1172:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1173:     function updateRadio(formname,id,weight) {
1.125     ng       1174: 	var gradeBox = formname["GD_BOX"+id];
                   1175: 	var radioButton = formname["RADVAL"+id];
                   1176: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1177: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1178: 	gradeBox.value = pts;
                   1179: 	var resetbox = false;
                   1180: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1181: 	    alert("$alertmsg"+pts);
1.71      ng       1182: 	    for (var i=0; i<radioButton.length; i++) {
                   1183: 		if (radioButton[i].checked) {
                   1184: 		    gradeBox.value = i;
                   1185: 		    resetbox = true;
                   1186: 		}
                   1187: 	    }
                   1188: 	    if (!resetbox) {
                   1189: 		formtextbox.value = "";
                   1190: 	    }
                   1191: 	    return;
1.44      ng       1192: 	}
1.71      ng       1193: 
                   1194: 	if (pts > weight) {
                   1195: 	    var resp = confirm("You entered a value ("+pts+
                   1196: 			       ") greater than the weight for the part. Accept?");
                   1197: 	    if (resp == false) {
1.125     ng       1198: 		gradeBox.value = oldpts;
1.71      ng       1199: 		return;
                   1200: 	    }
1.44      ng       1201: 	}
1.13      albertel 1202: 
1.71      ng       1203: 	for (var i=0; i<radioButton.length; i++) {
                   1204: 	    radioButton[i].checked=false;
                   1205: 	    if (pts == i && pts != "") {
                   1206: 		radioButton[i].checked=true;
                   1207: 	    }
                   1208: 	}
                   1209: 	updateSelect(formname,id);
1.125     ng       1210: 	formname["stores"+id].value = "0";
1.41      ng       1211:     }
1.5       albertel 1212: 
1.72      ng       1213:     function writeBox(formname,id,pts) {
1.125     ng       1214: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1215: 	if (checkSolved(formname,id) == 'update') {
                   1216: 	    gradeBox.value = pts;
                   1217: 	} else {
1.125     ng       1218: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1219: 	    gradeBox.value = oldpts;
1.125     ng       1220: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1221: 	    for (var i=0; i<radioButton.length; i++) {
                   1222: 		radioButton[i].checked=false;
1.72      ng       1223: 		if (i == oldpts) {
1.71      ng       1224: 		    radioButton[i].checked=true;
                   1225: 		}
                   1226: 	    }
1.41      ng       1227: 	}
1.125     ng       1228: 	formname["stores"+id].value = "0";
1.71      ng       1229: 	updateSelect(formname,id);
                   1230: 	return;
1.41      ng       1231:     }
1.44      ng       1232: 
1.71      ng       1233:     function clearRadBox(formname,id) {
                   1234: 	if (checkSolved(formname,id) == 'noupdate') {
                   1235: 	    updateSelect(formname,id);
                   1236: 	    return;
                   1237: 	}
1.125     ng       1238: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1239: 	for (var i=0; i<gradeSelect.length; i++) {
                   1240: 	    if (gradeSelect[i].selected) {
                   1241: 		var selectx=i;
                   1242: 	    }
                   1243: 	}
1.125     ng       1244: 	var stores = formname["stores"+id];
1.71      ng       1245: 	if (selectx == stores.value) { return };
1.125     ng       1246: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1247: 	gradeBox.value = "";
1.125     ng       1248: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1249: 	for (var i=0; i<radioButton.length; i++) {
                   1250: 	    radioButton[i].checked=false;
                   1251: 	}
                   1252: 	stores.value = selectx;
                   1253:     }
1.5       albertel 1254: 
1.71      ng       1255:     function checkSolved(formname,id) {
1.125     ng       1256: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1257: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1258: 	    if (!reply) {return "noupdate";}
1.120     ng       1259: 	    formname.overRideScore.value = 'yes';
1.41      ng       1260: 	}
1.71      ng       1261: 	return "update";
1.13      albertel 1262:     }
1.71      ng       1263: 
                   1264:     function updateSelect(formname,id) {
1.125     ng       1265: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1266: 	return;
1.41      ng       1267:     }
1.33      ng       1268: 
1.121     ng       1269: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1270:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1271: 	formname.gradeOpt.value = val;
1.71      ng       1272: 	if (val == "Save & Next") {
                   1273: 	    for (i=0;i<=total;i++) {
                   1274: 		for (j=0;j<parttot;j++) {
1.125     ng       1275: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1276: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1277: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1278: 			if (points == "") {
1.125     ng       1279: 			    var name = formname["name"+i].value;
1.129     ng       1280: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1281: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1282: 					       ", part "+partid+". Continue?");
1.71      ng       1283: 			    if (resp == false) {
1.125     ng       1284: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1285: 				return false;
                   1286: 			    }
                   1287: 			}
                   1288: 		    }
                   1289: 		    
                   1290: 		}
                   1291: 	    }
                   1292: 	    
                   1293: 	}
1.120     ng       1294: 	formname.submit();
                   1295:     }
                   1296: 
1.71      ng       1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1298:     function checkSubmitPage(formname,total) {
                   1299: 	noscore = new Array(100);
                   1300: 	var ptr = 0;
                   1301: 	for (i=1;i<total;i++) {
1.125     ng       1302: 	    var partid = formname["q_"+i].value;
1.127     ng       1303: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1304: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1305: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1306: 		if (points == "" && status != "correct_by_student") {
                   1307: 		    noscore[ptr] = i;
                   1308: 		    ptr++;
                   1309: 		}
                   1310: 	    }
                   1311: 	}
                   1312: 	if (ptr != 0) {
                   1313: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1314: 	    var prolist = "";
                   1315: 	    if (ptr == 1) {
                   1316: 		prolist = noscore[0];
                   1317: 	    } else {
                   1318: 		var i = 0;
                   1319: 		while (i < ptr-1) {
                   1320: 		    prolist += noscore[i]+", ";
                   1321: 		    i++;
                   1322: 		}
                   1323: 		prolist += "and "+noscore[i];
                   1324: 	    }
                   1325: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1326: 	    if (resp == false) {
                   1327: 		return false;
                   1328: 	    }
                   1329: 	}
1.45      ng       1330: 
1.71      ng       1331: 	formname.submit();
                   1332:     }
                   1333: SUBJAVASCRIPT
                   1334: }
1.45      ng       1335: 
1.71      ng       1336: #--- javascript for essay type problem --
                   1337: sub sub_page_kw_js {
                   1338:     my $request = shift;
1.80      ng       1339:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1340:     &commonJSfunctions($request);
1.350     albertel 1341: 
1.629     www      1342:     my $inner_js_msg_central= (<<INNERJS);
                   1343: <script type="text/javascript">
1.350     albertel 1344:     function checkInput() {
                   1345:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1346:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1347:       var usrctr = document.msgcenter.usrctr.value;
                   1348:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1349:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1350: 
                   1351:       var msgchk = "";
                   1352:       if (document.msgcenter.subchk.checked) {
                   1353:          msgchk = "msgsub,";
                   1354:       }
                   1355:       var includemsg = 0;
                   1356:       for (var i=1; i<=nmsg; i++) {
                   1357:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1358:           var frmmsg = document.msgcenter["msg"+i];
                   1359:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1360:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1361:           showflg.value = "1";
                   1362:           var chkbox = document.msgcenter["msgn"+i];
                   1363:           if (chkbox.checked) {
                   1364:              msgchk += "savemsg"+i+",";
                   1365:              includemsg = 1;
                   1366:           }
                   1367:       }
                   1368:       if (document.msgcenter.newmsgchk.checked) {
                   1369:          msgchk += "newmsg"+usrctr;
                   1370:          includemsg = 1;
                   1371:       }
                   1372:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1373:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1374:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1375:       includemsg.value = msgchk;
                   1376: 
                   1377:       self.close()
                   1378: 
                   1379:     }
1.629     www      1380: </script>
1.350     albertel 1381: INNERJS
                   1382: 
1.629     www      1383:     my $inner_js_highlight_central= (<<INNERJS);
                   1384: <script type="text/javascript">
1.351     albertel 1385:     function updateChoice(flag) {
                   1386:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1387:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1388:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1389:       opener.document.SCORE.refresh.value = "on";
                   1390:       if (opener.document.SCORE.keywords.value!=""){
                   1391:          opener.document.SCORE.submit();
                   1392:       }
                   1393:       self.close()
                   1394:     }
1.629     www      1395: </script>
1.351     albertel 1396: INNERJS
                   1397: 
                   1398:     my $start_page_msg_central = 
                   1399:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1400: 				       {'js_ready'  => 1,
                   1401: 					'only_body' => 1,
                   1402: 					'bgcolor'   =>'#FFFFFF',});
                   1403:     my $end_page_msg_central = 
                   1404: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1405: 
                   1406: 
                   1407:     my $start_page_highlight_central = 
                   1408:         &Apache::loncommon::start_page('Highlight Central',
                   1409: 				       $inner_js_highlight_central,
1.350     albertel 1410: 				       {'js_ready'  => 1,
                   1411: 					'only_body' => 1,
                   1412: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1413:     my $end_page_highlight_central = 
1.350     albertel 1414: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1415: 
1.219     www      1416:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1417:     $docopen=~s/^document\.//;
1.652     raeburn  1418:     my %lt = &Apache::lonlocal::texthash(
                   1419:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1420:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1421:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1422:                 comp => 'Compose Message for: ',
                   1423:                 incl => 'Include',
1.656     raeburn  1424:                 type => 'Type',
1.652     raeburn  1425:                 subj => 'Subject',
                   1426:                 mesa => 'Message',
                   1427:                 new  => 'New',
                   1428:                 save => 'Save',
                   1429:                 canc => 'Cancel',
                   1430:                 kehi => 'Keyword Highlight Options',
                   1431:                 txtc => 'Text Color',
                   1432:                 font => 'Font Size',
1.656     raeburn  1433:                 fnst => 'Font Style',
1.652     raeburn  1434:              );
1.597     wenzelju 1435:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1436: 
1.44      ng       1437: //===================== Show list of keywords ====================
1.122     ng       1438:   function keywords(formname) {
1.652     raeburn  1439:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1440:     if (nret==null) return;
1.122     ng       1441:     formname.keywords.value = nret;
1.44      ng       1442: 
1.122     ng       1443:     if (formname.keywords.value != "") {
1.128     ng       1444: 	formname.refresh.value = "on";
1.122     ng       1445: 	formname.submit();
1.44      ng       1446:     }
                   1447:     return;
                   1448:   }
                   1449: 
                   1450: //===================== Script to view submitted by ==================
                   1451:   function viewSubmitter(submitter) {
                   1452:     document.SCORE.refresh.value = "on";
                   1453:     document.SCORE.NCT.value = "1";
                   1454:     document.SCORE.unamedom0.value = submitter;
                   1455:     document.SCORE.submit();
                   1456:     return;
                   1457:   }
                   1458: 
                   1459: //===================== Script to add keyword(s) ==================
                   1460:   function getSel() {
                   1461:     if (document.getSelection) txt = document.getSelection();
                   1462:     else if (document.selection) txt = document.selection.createRange().text;
                   1463:     else return;
                   1464:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1465:     if (cleantxt=="") {
1.652     raeburn  1466: 	alert("$lt{'plse'}");
1.44      ng       1467: 	return;
                   1468:     }
1.652     raeburn  1469:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1470:     if (nret==null) return;
1.127     ng       1471:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1472:     if (document.SCORE.keywords.value != "") {
1.127     ng       1473: 	document.SCORE.refresh.value = "on";
1.44      ng       1474: 	document.SCORE.submit();
                   1475:     }
                   1476:     return;
                   1477:   }
                   1478: 
                   1479: //====================== Script for composing message ==============
1.80      ng       1480:    // preload images
                   1481:    img1 = new Image();
                   1482:    img1.src = "$iconpath/mailbkgrd.gif";
                   1483:    img2 = new Image();
                   1484:    img2.src = "$iconpath/mailto.gif";
                   1485: 
1.44      ng       1486:   function msgCenter(msgform,usrctr,fullname) {
                   1487:     var Nmsg  = msgform.savemsgN.value;
                   1488:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1489:     var subject = msgform.msgsub.value;
1.127     ng       1490:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1491:     re = /msgsub/;
                   1492:     var shwsel = "";
                   1493:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1494:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1495:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1496:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1497: 	var testmsg = "savemsg"+i+",";
                   1498: 	re = new RegExp(testmsg,"g");
1.44      ng       1499: 	shwsel = "";
                   1500: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1501: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1502: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1503: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1504: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1505:     }
1.125     ng       1506:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1507:     shwsel = "";
                   1508:     re = /newmsg/;
                   1509:     if (re.test(msgchk)) { shwsel = "checked" }
                   1510:     newMsg(newmsg,shwsel);
                   1511:     msgTail(); 
                   1512:     return;
                   1513:   }
                   1514: 
1.123     ng       1515:   function checkEntities(strx) {
                   1516:     if (strx.length == 0) return strx;
                   1517:     var orgStr = ["&", "<", ">", '"']; 
                   1518:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1519:     var counter = 0;
                   1520:     while (counter < 4) {
                   1521: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1522: 	counter++;
                   1523:     }
                   1524:     return strx;
                   1525:   }
                   1526: 
                   1527:   function strReplace(strx, orgStr, newStr) {
                   1528:     return strx.split(orgStr).join(newStr);
                   1529:   }
                   1530: 
1.44      ng       1531:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1532:     var height = 70*Nmsg+250;
1.44      ng       1533:     if (height > 600) {
                   1534: 	height = 600;
                   1535:     }
1.118     ng       1536:     var xpos = (screen.width-600)/2;
                   1537:     xpos = (xpos < 0) ? '0' : xpos;
                   1538:     var ypos = (screen.height-height)/2-30;
                   1539:     ypos = (ypos < 0) ? '0' : ypos;
                   1540: 
1.668     www      1541:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1542:     pWin.focus();
                   1543:     pDoc = pWin.document;
1.219     www      1544:     pDoc.$docopen;
1.351     albertel 1545:     pDoc.write('$start_page_msg_central');
1.76      ng       1546: 
                   1547:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1548:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1549:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1550: 
1.676     golterma 1551:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1552:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1553: }
                   1554:     function displaySubject(msg,shwsel) {
1.76      ng       1555:     pDoc = pWin.document;
1.676     golterma 1556:     pDoc.write("<tr>");
                   1557:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1558:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1559:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1560: }
                   1561: 
1.72      ng       1562:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1563:     pDoc = pWin.document;
1.676     golterma 1564:     pDoc.write("<tr>");
                   1565:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1566:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1567:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1568: }
                   1569: 
                   1570:   function newMsg(newmsg,shwsel) {
1.76      ng       1571:     pDoc = pWin.document;
1.676     golterma 1572:     pDoc.write("<tr>");
                   1573:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1574:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1575:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1576: }
                   1577: 
                   1578:   function msgTail() {
1.76      ng       1579:     pDoc = pWin.document;
1.676     golterma 1580:     //pDoc.write("<\\/table>");
1.465     albertel 1581:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1582:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1584:     pDoc.write("<\\/form>");
1.351     albertel 1585:     pDoc.write('$end_page_msg_central');
1.128     ng       1586:     pDoc.close();
1.44      ng       1587: }
                   1588: 
                   1589: //====================== Script for keyword highlight options ==============
                   1590:   function kwhighlight() {
                   1591:     var kwclr    = document.SCORE.kwclr.value;
                   1592:     var kwsize   = document.SCORE.kwsize.value;
                   1593:     var kwstyle  = document.SCORE.kwstyle.value;
                   1594:     var redsel = "";
                   1595:     var grnsel = "";
                   1596:     var blusel = "";
                   1597:     if (kwclr=="red")   {var redsel="checked"};
                   1598:     if (kwclr=="green") {var grnsel="checked"};
                   1599:     if (kwclr=="blue")  {var blusel="checked"};
                   1600:     var sznsel = "";
                   1601:     var sz1sel = "";
                   1602:     var sz2sel = "";
                   1603:     if (kwsize=="0")  {var sznsel="checked"};
                   1604:     if (kwsize=="+1") {var sz1sel="checked"};
                   1605:     if (kwsize=="+2") {var sz2sel="checked"};
                   1606:     var synsel = "";
                   1607:     var syisel = "";
                   1608:     var sybsel = "";
                   1609:     if (kwstyle=="")    {var synsel="checked"};
                   1610:     if (kwstyle=="<i>") {var syisel="checked"};
                   1611:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1612:     highlightCentral();
                   1613:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1614:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1615:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1616:     highlightend();
                   1617:     return;
                   1618:   }
                   1619: 
                   1620:   function highlightCentral() {
1.76      ng       1621: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1622:     var xpos = (screen.width-400)/2;
                   1623:     xpos = (xpos < 0) ? '0' : xpos;
                   1624:     var ypos = (screen.height-330)/2-30;
                   1625:     ypos = (ypos < 0) ? '0' : ypos;
                   1626: 
1.206     albertel 1627:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1628:     hwdWin.focus();
                   1629:     var hDoc = hwdWin.document;
1.219     www      1630:     hDoc.$docopen;
1.351     albertel 1631:     hDoc.write('$start_page_highlight_central');
1.76      ng       1632:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1633:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1634: 
1.564     bisitz   1635:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1636:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1637:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1638:   }
                   1639: 
                   1640:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1641:     var hDoc = hwdWin.document;
                   1642:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1643:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1644:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1645:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1646:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1647:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1648:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1649:     hDoc.write("<\\/tr>");
1.44      ng       1650:   }
                   1651: 
                   1652:   function highlightend() { 
1.76      ng       1653:     var hDoc = hwdWin.document;
1.465     albertel 1654:     hDoc.write("<\\/table>");
                   1655:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1656:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1658:     hDoc.write("<\\/form>");
1.351     albertel 1659:     hDoc.write('$end_page_highlight_central');
1.128     ng       1660:     hDoc.close();
1.44      ng       1661:   }
                   1662: 
                   1663: SUBJAVASCRIPT
                   1664: }
                   1665: 
1.349     albertel 1666: sub get_increment {
1.348     bowersj2 1667:     my $increment = $env{'form.increment'};
                   1668:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1669:         $increment != .1) {
                   1670:         $increment = 1;
                   1671:     }
                   1672:     return $increment;
                   1673: }
                   1674: 
1.585     bisitz   1675: sub gradeBox_start {
                   1676:     return (
                   1677:         &Apache::loncommon::start_data_table()
                   1678:        .&Apache::loncommon::start_data_table_header_row()
                   1679:        .'<th>'.&mt('Part').'</th>'
                   1680:        .'<th>'.&mt('Points').'</th>'
                   1681:        .'<th>&nbsp;</th>'
                   1682:        .'<th>'.&mt('Assign Grade').'</th>'
                   1683:        .'<th>'.&mt('Weight').'</th>'
                   1684:        .'<th>'.&mt('Grade Status').'</th>'
                   1685:        .&Apache::loncommon::end_data_table_header_row()
                   1686:     );
                   1687: }
                   1688: 
                   1689: sub gradeBox_end {
                   1690:     return (
                   1691:         &Apache::loncommon::end_data_table()
                   1692:     );
                   1693: }
1.71      ng       1694: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1695: sub gradeBox {
1.322     albertel 1696:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1697:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1698: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1699:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1700:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1701:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1702:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1703:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1704: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1705:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1706:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1707:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1708: 				       [$partid]);
                   1709:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1710:     if ($last_resets{$partid}) {
                   1711:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1712:     }
1.695     bisitz   1713:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1714:     my $ctr = 0;
1.348     bowersj2 1715:     my $thisweight = 0;
1.349     albertel 1716:     my $increment = &get_increment();
1.485     albertel 1717: 
                   1718:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1719:     while ($thisweight<=$wgt) {
1.532     bisitz   1720: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1721:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1722: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1723: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1724: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1725:         $thisweight += $increment;
1.71      ng       1726: 	$ctr++;
                   1727:     }
1.485     albertel 1728:     $radio.='</tr></table>';
                   1729: 
                   1730:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1731: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1732: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1733: 	$wgt.')" /></td>'."\n";
1.485     albertel 1734:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1735: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1736: 	' </td>'."\n";
                   1737:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1738: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1739:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1740: 	$line.='<option></option>'.
                   1741: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1742:     } else {
1.485     albertel 1743: 	$line.='<option selected="selected"></option>'.
                   1744: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1745:     }
1.485     albertel 1746:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1747: 
                   1748: 
                   1749:     $result .= 
1.695     bisitz   1750: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1751:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1752:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1753:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1754: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1755: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1756: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1757:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1758:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1759:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1760:         $aggtries.'" />'."\n";
1.582     raeburn  1761:     my $res_error;
                   1762:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1763:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1764:     if ($res_error) {
                   1765:         return &navmap_errormsg();
                   1766:     }
1.318     banghart 1767:     return $result;
                   1768: }
1.322     albertel 1769: 
                   1770: sub handback_box {
1.623     www      1771:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1772:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1773:     my (@respids);
1.652     raeburn  1774:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1775:     foreach my $part_response_id (@part_response_id) {
                   1776:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1777:         if ($part eq $partid) {
1.375     albertel 1778:             push(@respids,$resp);
1.323     banghart 1779:         }
                   1780:     }
1.318     banghart 1781:     my $result;
1.323     banghart 1782:     foreach my $respid (@respids) {
1.322     albertel 1783: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1784: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1785: 	next if (!@$files);
1.654     raeburn  1786: 	my $file_counter = 0;
1.313     banghart 1787: 	foreach my $file (@$files) {
1.368     banghart 1788: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1789:                 $file_counter++;
1.368     banghart 1790:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1791:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1792:     	        $file_disp = "$name.$ext";
                   1793:     	        $file = $file_path.$file_disp;
                   1794:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1795:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1796:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1797:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1798: 	    }
1.322     albertel 1799: 	}
1.654     raeburn  1800:         if ($file_counter) {
                   1801:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1802:                        '<span class="LC_info">'.
                   1803:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1804:         }
1.313     banghart 1805:     }
1.318     banghart 1806:     return $result;    
1.71      ng       1807: }
1.44      ng       1808: 
1.58      albertel 1809: sub show_problem {
1.382     albertel 1810:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1811:     my $rendered;
1.382     albertel 1812:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1813:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1814:     if ($mode eq 'both' or $mode eq 'text') {
                   1815: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1816: 						       $env{'request.course.id'},
                   1817: 						       undef,\%form);
1.144     albertel 1818:     }
1.58      albertel 1819:     if ($removeform) {
                   1820: 	$rendered=~s|<form(.*?)>||g;
                   1821: 	$rendered=~s|</form>||g;
1.374     albertel 1822: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1823:     }
1.144     albertel 1824:     my $companswer;
                   1825:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1826: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1827: 	$companswer=
                   1828: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1829: 						    $env{'request.course.id'},
                   1830: 						    %form);
1.144     albertel 1831:     }
1.58      albertel 1832:     if ($removeform) {
                   1833: 	$companswer=~s|<form(.*?)>||g;
                   1834: 	$companswer=~s|</form>||g;
1.144     albertel 1835: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1836:     }
1.671     raeburn  1837:     my $renderheading = &mt('View of the problem');
                   1838:     my $answerheading = &mt('Correct answer');
                   1839:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1840:         my $stu_fullname = $env{'form.fullname'};
                   1841:         if ($stu_fullname eq '') {
                   1842:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1843:         }
                   1844:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1845:         if ($forwhom ne '') {
                   1846:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1847:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1848:         }
                   1849:     }
1.468     albertel 1850:     $rendered=
1.588     bisitz   1851:         '<div class="LC_Box">'
1.671     raeburn  1852:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1853:        .$rendered
                   1854:        .'</div>';
1.468     albertel 1855:     $companswer=
1.588     bisitz   1856:         '<div class="LC_Box">'
1.671     raeburn  1857:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1858:        .$companswer
                   1859:        .'</div>';
1.468     albertel 1860:     my $result;
1.144     albertel 1861:     if ($mode eq 'both') {
1.588     bisitz   1862:         $result=$rendered.$companswer;
1.144     albertel 1863:     } elsif ($mode eq 'text') {
1.588     bisitz   1864:         $result=$rendered;
1.144     albertel 1865:     } elsif ($mode eq 'answer') {
1.588     bisitz   1866:         $result=$companswer;
1.144     albertel 1867:     }
1.71      ng       1868:     return $result;
1.58      albertel 1869: }
1.397     albertel 1870: 
1.396     banghart 1871: sub files_exist {
                   1872:     my ($r, $symb) = @_;
                   1873:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1874: 
1.396     banghart 1875:     foreach my $student (@students) {
                   1876:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1877:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1878: 					      $udom,$uname);
1.396     banghart 1879:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1880:         foreach my $submission (@$string) {
                   1881:             my ($partid,$respid) =
                   1882: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1883:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1884: 					   \%record);
                   1885:             return 1 if (@$files);
1.396     banghart 1886:         }
                   1887:     }
1.397     albertel 1888:     return 0;
1.396     banghart 1889: }
1.397     albertel 1890: 
1.394     banghart 1891: sub download_all_link {
                   1892:     my ($r,$symb) = @_;
1.621     www      1893:     unless (&files_exist($r, $symb)) {
                   1894:        $r->print(&mt('There are currently no submitted documents.'));
                   1895:        return;
                   1896:     }
                   1897: 
1.395     albertel 1898:     my $all_students = 
                   1899: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1900: 
                   1901:     my $parts =
                   1902: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1903: 
1.394     banghart 1904:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1905:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1906:                              'cgi.'.$identifier.'.symb' => $symb,
                   1907:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1908:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1909: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1910:     return;
                   1911: }
                   1912: 
                   1913: sub submit_download_link {
                   1914:     my ($request,$symb) = @_;
                   1915:     if (!$symb) { return ''; }
                   1916: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1917:     &download_all_link($request,$symb);
1.394     banghart 1918: }
1.395     albertel 1919: 
1.432     banghart 1920: sub build_section_inputs {
                   1921:     my $section_inputs;
                   1922:     if ($env{'form.section'} eq '') {
                   1923:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1924:     } else {
                   1925:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1926:         foreach my $section (@sections) {
1.432     banghart 1927:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1928:         }
                   1929:     }
                   1930:     return $section_inputs;
                   1931: }
                   1932: 
1.44      ng       1933: # --------------------------- show submissions of a student, option to grade 
                   1934: sub submission {
1.608     www      1935:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1936:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1937:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1938:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1939:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1940: 
1.605     www      1941:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1942:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1943: 
                   1944:     if (!&canview($usec)) {
1.712     bisitz   1945:         $request->print(
                   1946:             '<span class="LC_warning">'.
1.713     bisitz   1947:             &mt('Unable to view requested student.').
1.712     bisitz   1948:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1949:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1950:             '</span>');
1.104     albertel 1951: 	return;
                   1952:     }
                   1953: 
1.257     albertel 1954:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1955:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1956:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1957:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1958:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1959: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1960: 	'/check.gif" height="16" border="0" />';
1.41      ng       1961: 
                   1962:     # header info
                   1963:     if ($counter == 0) {
                   1964: 	&sub_page_js($request);
1.621     www      1965: 	&sub_page_kw_js($request);
1.118     ng       1966: 
1.44      ng       1967: 	# option to display problem, only once else it cause problems 
                   1968:         # with the form later since the problem has a form.
1.257     albertel 1969: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1970: 	    my $mode;
1.257     albertel 1971: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1972: 		$mode='both';
1.257     albertel 1973: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1974: 		$mode='text';
1.257     albertel 1975: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1976: 		$mode='answer';
                   1977: 	    }
1.329     albertel 1978: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1979: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1980: 	}
1.441     www      1981: 
1.704     raeburn  1982: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       1983:         # if this subroutine has been called once.
1.41      ng       1984: 	my %keyhash = ();
1.624     www      1985: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1986:         if (1) {
1.41      ng       1987: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1988: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1989: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1990: 
1.257     albertel 1991: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1992: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1993: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1994: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1995: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1996: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1997: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1998: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1999: 	}
1.257     albertel 2000: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2001: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2002: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2003: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2004: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2005: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2006: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2007: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2008: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2009: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2010: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2011: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2012: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2013: 			&build_section_inputs().
1.326     albertel 2014: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2015: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2016: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2017: #	if ($env{'form.handgrade'} eq 'yes') {
                   2018:         if (1) {
1.257     albertel 2019: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2020: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2021: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2022: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2023: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2024: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2025: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2026: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2027: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2028: 	    }
1.123     ng       2029: 	}
1.41      ng       2030: 	
                   2031: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2032: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2033: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2034: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2035: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2036: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2037: 		'" />'."\n".
                   2038: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2039: 	    $cts++;
                   2040: 	}
                   2041: 	$request->print($prnmsg);
1.32      ng       2042: 
1.624     www      2043: #	if ($env{'form.handgrade'} eq 'yes') {
                   2044:         if (1) {
1.652     raeburn  2045: 
                   2046:             my %lt = &Apache::lonlocal::texthash(
                   2047:                           keyw => 'Keyword Options',
1.655     raeburn  2048:                           list => 'List',
1.652     raeburn  2049:                           past => 'Paste Selection to List',
1.661     www      2050:                           high => 'Highlight Attribute',
1.652     raeburn  2051:                      );    
1.88      www      2052: #
                   2053: # Print out the keyword options line
                   2054: #
1.41      ng       2055: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2056: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2057: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2058: <a href="#" onmousedown="javascript:getSel(); return false"
1.695     bisitz   2059:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
1.652     raeburn  2060: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2061: KEYWORDS
1.88      www      2062: #
                   2063: # Load the other essays for similarity check
                   2064: #
1.324     albertel 2065:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2066: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2067: 	    $apath=&escape($apath);
1.88      www      2068: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2069:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2070:         }
                   2071:     }
1.44      ng       2072: 
1.441     www      2073: # This is where output for one specific student would start
1.592     bisitz   2074:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2075:     $request->print(
                   2076:         "\n\n"
                   2077:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2078:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2079:        ."\n"
                   2080:     );
1.441     www      2081: 
1.592     bisitz   2082:     # Show additional functions if allowed
                   2083:     if ($perm{'vgr'}) {
                   2084:         $request->print(
                   2085:             &Apache::loncommon::track_student_link(
1.708     bisitz   2086:                 'View recent activity',
1.592     bisitz   2087:                 $uname,$udom,'check')
                   2088:            .' '
                   2089:         );
                   2090:     }
                   2091:     if ($perm{'opa'}) {
                   2092:         $request->print(
                   2093:             &Apache::loncommon::pprmlink(
                   2094:                 &mt('Set/Change parameters'),
                   2095:                 $uname,$udom,$symb,'check'));
                   2096:     }
                   2097: 
                   2098:     # Show Problem
1.257     albertel 2099:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2100: 	my $mode;
1.257     albertel 2101: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2102: 	    $mode='both';
1.257     albertel 2103: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2104: 	    $mode='text';
1.257     albertel 2105: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2106: 	    $mode='answer';
                   2107: 	}
1.329     albertel 2108: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2109: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2110:     }
1.144     albertel 2111: 
1.257     albertel 2112:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2113:     my $res_error;
                   2114:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2115:     if ($res_error) {
                   2116:         $request->print(&navmap_errormsg());
                   2117:         return;
                   2118:     }
1.41      ng       2119: 
1.44      ng       2120:     # Display student info
1.41      ng       2121:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2122: 
                   2123:     my $result='<div class="LC_Box">'
                   2124:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2125:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2126:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2127: #    if ($env{'form.handgrade'} eq 'no') {
                   2128:     if (1) {
1.588     bisitz   2129:         $result.='<p class="LC_info">'
                   2130:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2131:                 ."</p>\n";
1.469     albertel 2132:     }
                   2133: 
1.118     ng       2134:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2135:     my $fullname;
                   2136:     my $col_fullnames = [];
1.624     www      2137: #    if ($env{'form.handgrade'} eq 'yes') {
                   2138:     if (1) {
1.464     albertel 2139: 	(my $sub_result,$fullname,$col_fullnames)=
                   2140: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2141: 				 $counter);
                   2142: 	$result.=$sub_result;
1.41      ng       2143:     }
1.44      ng       2144:     $request->print($result."\n");
1.702     kruse    2145:     
1.44      ng       2146:     # print student answer/submission
1.588     bisitz   2147:     # Options are (1) Handgraded submission only
1.44      ng       2148:     #             (2) Last submission, includes submission that is not handgraded 
                   2149:     #                  (for multi-response type part)
                   2150:     #             (3) Last submission plus the parts info
                   2151:     #             (4) The whole record for this student
1.702     kruse    2152:     
                   2153:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2154: 	
1.702     kruse    2155:     my $lastsubonly;
1.468     albertel 2156: 
1.702     kruse    2157:     if ($$timestamp eq '') {
                   2158:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2159:     } else {
                   2160:         $lastsubonly =
                   2161:             '<div class="LC_grade_submissions_body">'
                   2162:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2163: 
                   2164: 	my %seenparts;
                   2165: 	my @part_response_id = &flatten_responseType($responseType);
                   2166: 	foreach my $part (@part_response_id) {
                   2167: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2168: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2169: 
1.702     kruse    2170: 	    my ($partid,$respid) = @{ $part };
                   2171: 	    my $display_part=&get_display_part($partid,$symb);
                   2172: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2173: 		if (exists($seenparts{$partid})) { next; }
                   2174: 		$seenparts{$partid}=1;
                   2175:                 $request->print(
                   2176:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2177:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2178:                                '<a href="javascript:viewSubmitter(\''.
                   2179:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2180:                                '\');" target="_self">'.
                   2181:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2182:                     '<br />');
                   2183: 		next;
                   2184: 		}
                   2185: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2186: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2187:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2188:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2189:                     ' <span class="LC_internal_info">'.
                   2190:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2191:                     '</span>&nbsp; &nbsp;'.
                   2192: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2193: 		next;
                   2194: 	    }
                   2195: 	    foreach my $submission (@$string) {
                   2196: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2197: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2198: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
                   2199: 		# Similarity check
                   2200:                 my $similar='';
                   2201:                 my ($type,$trial,$rndseed);
                   2202:                 if ($hide eq 'rand') {
                   2203:                     $type = 'randomizetry';
                   2204:                     $trial = $record{"resource.$partid.tries"};
                   2205:                     $rndseed = $record{"resource.$partid.rndseed"};
                   2206:                 }
                   2207: 	        if ($env{'form.checkPlag'}) {
                   2208:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2209: 		        &most_similar($uname,$udom,$symb,$subval);
                   2210: 		    if ($osim) {
                   2211: 			$osim=int($osim*100.0);
                   2212: 			my %old_course_desc = 
                   2213: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2214: 							{'one_time' => 1});
                   2215: 
                   2216:                         if ($hide eq 'anon') {
                   2217:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2218:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2219:                         } else {
                   2220: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2221: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2222: 				    $osim,
                   2223: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2224: 				        $old_course_desc{'description'},
                   2225: 				        $old_course_desc{'num'},
                   2226: 				        $old_course_desc{'domain'}).
                   2227: 				    '</span></h3><blockquote><i>'.
                   2228: 				    &keywords_highlight($oessay).
                   2229: 				    '</i></blockquote><hr />';
1.702     kruse    2230:                         }
                   2231: 	            }
                   2232: 		}
                   2233: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2234:                                      undef,$type,$trial,$rndseed);
                   2235:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2236: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2237: 		    my $display_part=&get_display_part($partid,$symb);
                   2238:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2239:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2240:                         ' <span class="LC_internal_info">'.
                   2241:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2242:                         '</span>&nbsp; &nbsp;';
                   2243: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2244:                         
                   2245: 		    if (@$files) {
                   2246:                         if ($hide eq 'anon') {
                   2247:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2248:                         } else {
                   2249:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2250:                                         .'<br /><span class="LC_warning">';
                   2251:                             if(@$files == 1) {
                   2252:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2253:                             } else {
1.702     kruse    2254:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2255:                             }
                   2256:                             $lastsubonly .= '</span>';                         
                   2257:                             foreach my $file (@$files) {
                   2258:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2259:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2260:                             }
                   2261:                         }
1.702     kruse    2262: 			$lastsubonly.='<br />';
                   2263:                     }
                   2264:                     if ($hide eq 'anon') {
                   2265:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2266:                     } else {
                   2267:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
                   2268: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2269: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2270:                     }
                   2271: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2272: 		    $lastsubonly.='</div>';
1.41      ng       2273: 		}
1.702     kruse    2274:             }
1.151     albertel 2275: 	}
1.702     kruse    2276: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2277:     }
                   2278:     $request->print($lastsubonly);
                   2279:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2280:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2281: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.702     kruse    2282:     } 
                   2283:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2284:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2285: 								 $env{'request.course.id'},
1.44      ng       2286: 								 $last,'.submission',
                   2287: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2288:     }
1.121     ng       2289:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2290: 	.$udom.'" />'."\n");
1.44      ng       2291:     # return if view submission with no grading option
1.618     www      2292:     if (!&canmodify($usec)) {
1.633     www      2293: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2294: 	return;
1.180     albertel 2295:     } else {
1.468     albertel 2296: 	$request->print('</div>'."\n");
1.41      ng       2297:     }
1.33      ng       2298: 
1.121     ng       2299:     # essay grading message center
1.624     www      2300: #    if ($env{'form.handgrade'} eq 'yes') {
                   2301:     if (1) {
1.468     albertel 2302: 	my $result='<div class="LC_grade_message_center">';
                   2303:     
                   2304: 	$result.='<div class="LC_grade_message_center_header">'.
                   2305: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2306: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2307: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2308: 	if (scalar(@$col_fullnames) > 0) {
                   2309: 	    my $lastone = pop(@$col_fullnames);
                   2310: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2311: 	}
                   2312: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2313: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2314: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2315: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2316: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2317: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2318: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2319: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2320: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2321: 	    '<br />&nbsp;('.
1.468     albertel 2322: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2323: 	$result.='</div></div>';
1.121     ng       2324: 	$request->print($result);
1.118     ng       2325:     }
1.41      ng       2326: 
                   2327:     my %seen = ();
                   2328:     my @partlist;
1.129     ng       2329:     my @gradePartRespid;
1.375     albertel 2330:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2331:     $request->print(
1.588     bisitz   2332:         '<div class="LC_Box">'
                   2333:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2334:     );
1.592     bisitz   2335:     $request->print(&gradeBox_start());
1.375     albertel 2336:     foreach my $part_response_id (@part_response_id) {
                   2337:     	my ($partid,$respid) = @{ $part_response_id };
                   2338: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2339: 	next if ($seen{$partid} > 0);
1.41      ng       2340: 	$seen{$partid}++;
1.393     albertel 2341: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2342: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2343: 	push(@partlist,$partid);
                   2344: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2345: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2346:     }
1.585     bisitz   2347:     $request->print(&gradeBox_end()); # </div>
                   2348:     $request->print('</div>');
1.468     albertel 2349: 
                   2350:     $request->print('<div class="LC_grade_info_links">');
                   2351:     $request->print('</div>');
                   2352: 
1.45      ng       2353:     $result='<input type="hidden" name="partlist'.$counter.
                   2354: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2355:     $result.='<input type="hidden" name="gradePartRespid'.
                   2356: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2357:     my $ctr = 0;
                   2358:     while ($ctr < scalar(@partlist)) {
                   2359: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2360: 	    $partlist[$ctr].'" />'."\n";
                   2361: 	$ctr++;
                   2362:     }
1.468     albertel 2363:     $request->print($result.''."\n");
1.41      ng       2364: 
1.441     www      2365: # Done with printing info for one student
                   2366: 
1.468     albertel 2367:     $request->print('</div>');#LC_grade_show_user
1.441     www      2368: 
                   2369: 
1.41      ng       2370:     # print end of form
                   2371:     if ($counter == $total) {
1.592     bisitz   2372:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2373: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2374: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2375: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2376: 	my $ntstu ='<select name="NTSTU">'.
                   2377: 	    '<option>1</option><option>2</option>'.
                   2378: 	    '<option>3</option><option>5</option>'.
                   2379: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2380: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2381: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2382:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2383: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2384: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2385: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2386: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2387:         $endform.='<span class="LC_warning">'.
                   2388:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2389:                   '</span>'."\n" ;
1.349     albertel 2390:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2391:             "' name='increment' />";
1.485     albertel 2392: 	$endform.='</td></tr></table></form>';
1.41      ng       2393: 	$request->print($endform);
                   2394:     }
                   2395:     return '';
1.38      ng       2396: }
                   2397: 
1.464     albertel 2398: sub check_collaborators {
                   2399:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2400:     my ($result,@col_fullnames);
                   2401:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2402:     foreach my $part (keys(%$handgrade)) {
                   2403: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2404: 					'.maxcollaborators',
                   2405: 					$symb,$udom,$uname);
                   2406: 	next if ($ncol <= 0);
                   2407: 	$part =~ s/\_/\./g;
                   2408: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2409: 	my (@good_collaborators, @bad_collaborators);
                   2410: 	foreach my $possible_collaborator
1.630     www      2411: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2412: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2413: 	    next if ($possible_collaborator eq '');
1.631     www      2414: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2415: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2416: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2417: 	    # Doing this grep allows 'fuzzy' specification
                   2418: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2419: 			       keys(%$classlist));
                   2420: 	    if (! scalar(@matches)) {
                   2421: 		push(@bad_collaborators, $possible_collaborator);
                   2422: 	    } else {
                   2423: 		push(@good_collaborators, @matches);
                   2424: 	    }
                   2425: 	}
                   2426: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2427: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2428: 	    foreach my $name (@good_collaborators) {
                   2429: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2430: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2431: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2432: 	    }
1.630     www      2433: 	    $result.='</ol><br />'."\n";
1.466     albertel 2434: 	    my ($part)=split(/\./,$part);
1.464     albertel 2435: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2436: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2437: 		"\n";
                   2438: 	}
                   2439: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2440: 	    $result.='<div class="LC_warning">';
1.464     albertel 2441: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2442: 	    $result .= '</div>';
                   2443: 	}         
                   2444: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2445: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2446: 	    $result .= &mt('This student has submitted too many '.
                   2447: 		'collaborators.  Maximum is [_1].',$ncol);
                   2448: 	    $result .= '</div>';
                   2449: 	}
                   2450:     }
                   2451:     return ($result,$fullname,\@col_fullnames);
                   2452: }
                   2453: 
1.44      ng       2454: #--- Retrieve the last submission for all the parts
1.38      ng       2455: sub get_last_submission {
1.119     ng       2456:     my ($returnhash)=@_;
1.596     raeburn  2457:     my (@string,$timestamp,%lasthidden);
1.119     ng       2458:     if ($$returnhash{'version'}) {
1.46      ng       2459: 	my %lasthash=();
                   2460: 	my ($version);
1.119     ng       2461: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2462: 	    foreach my $key (sort(split(/\:/,
                   2463: 					$$returnhash{$version.':keys'}))) {
                   2464: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2465: 		$timestamp = 
1.545     raeburn  2466: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2467: 	    }
                   2468: 	}
1.640     raeburn  2469:         my (%typeparts,%randombytry);
1.596     raeburn  2470:         my $showsurv = 
                   2471:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2472:         foreach my $key (sort(keys(%lasthash))) {
                   2473:             if ($key =~ /\.type$/) {
                   2474:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2475:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2476:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2477:                     my ($ign,@parts) = split(/\./,$key);
                   2478:                     pop(@parts);
1.641     raeburn  2479:                     my $id = join('.',@parts);
1.640     raeburn  2480:                     if ($lasthash{$key} eq 'randomizetry') {
                   2481:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2482:                     } else {
                   2483:                         unless ($showsurv) {
                   2484:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2485:                         }
1.596     raeburn  2486:                     }
                   2487:                     delete($lasthash{$key});
                   2488:                 }
                   2489:             }
                   2490:         }
                   2491:         my @hidden = keys(%typeparts);
1.640     raeburn  2492:         my @randomize = keys(%randombytry);
1.397     albertel 2493: 	foreach my $key (keys(%lasthash)) {
                   2494: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2495:             my $hide;
                   2496:             if (@hidden) {
                   2497:                 foreach my $id (@hidden) {
                   2498:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2499:                         $hide = 'anon';
1.596     raeburn  2500:                         last;
                   2501:                     }
                   2502:                 }
                   2503:             }
1.640     raeburn  2504:             unless ($hide) {
                   2505:                 if (@randomize) {
                   2506:                     foreach my $id (@hidden) {
                   2507:                         if ($key =~ /^\Q$id\E/) {
                   2508:                             $hide = 'rand';
                   2509:                             last;
                   2510:                         }
                   2511:                     }
                   2512:                 }
                   2513:             }
1.397     albertel 2514: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2515: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2516: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2517: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2518: 	}
                   2519:     }
1.397     albertel 2520:     if (!@string) {
                   2521: 	$string[0] =
1.539     riegler  2522: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2523:     }
                   2524:     return (\@string,\$timestamp);
1.38      ng       2525: }
1.35      ng       2526: 
1.44      ng       2527: #--- High light keywords, with style choosen by user.
1.38      ng       2528: sub keywords_highlight {
1.44      ng       2529:     my $string    = shift;
1.257     albertel 2530:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2531:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2532:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2533:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2534:     foreach my $keyword (@keylist) {
                   2535: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2536:     }
                   2537:     return $string;
1.38      ng       2538: }
1.36      ng       2539: 
1.671     raeburn  2540: # For Tasks provide a mechanism to display previous version for one specific student
                   2541: 
                   2542: sub show_previous_task_version {
                   2543:     my ($request,$symb) = @_;
                   2544:     if ($symb eq '') {
                   2545:         $request->print("Unable to handle ambiguous references.");
                   2546: 
                   2547:         return '';
                   2548:     }
                   2549:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2550:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2551:     if (!&canview($usec)) {
1.712     bisitz   2552:         $request->print(
                   2553:             '<span class="LC_warning">'.
1.713     bisitz   2554:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2555:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2556:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2557:             '</span>');
1.671     raeburn  2558:         return;
                   2559:     }
                   2560:     my $mode = 'both';
                   2561:     my $isTask = ($symb =~/\.task$/);
                   2562:     if ($isTask) {
                   2563:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2564:             if ($env{'form.fullname'} eq '') {
                   2565:                 $env{'form.fullname'} =
                   2566:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2567:             }
                   2568:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2569:             $request->print("\n\n".
                   2570:                             '<div class="LC_grade_show_user">'.
                   2571:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2572:                             '</h2>'."\n");
                   2573:             &Apache::lonxml::clear_problem_counter();
                   2574:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2575:                             {'previousversion' => $env{'form.previousversion'} }));
                   2576:             $request->print("\n</div>");
                   2577:         }
                   2578:     }
                   2579:     return;
                   2580: }
                   2581: 
                   2582: sub choose_task_version_form {
                   2583:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2584:     my $isTask = ($symb =~/\.task$/);
                   2585:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2586:     if ($isTask) {
                   2587:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2588:                                               $udom,$uname);
                   2589:         if (($record{'resource.0.version'} eq '') ||
                   2590:             ($record{'resource.0.version'} < 2)) {
                   2591:             return ($record{'resource.0.version'},
                   2592:                     $record{'resource.0.version'},$result,$js);
                   2593:         } else {
                   2594:             $current = $record{'resource.0.version'};
                   2595:         }
                   2596:         if ($env{'form.previousversion'}) {
                   2597:             $displayed = $env{'form.previousversion'};
                   2598:             $rowtitle = &mt('Choose another version:')
                   2599:         } else {
                   2600:             $displayed = $current;
                   2601:             $rowtitle = &mt('Show earlier version:');
                   2602:         }
                   2603:         $result = '<div class="LC_left_float">';
                   2604:         my $list;
                   2605:         my $numversions = 0;
                   2606:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2607:             if ($i == $current) {
                   2608:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2609:                     next;
                   2610:                 } else {
                   2611:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2612:                     $numversions ++;
                   2613:                 }
                   2614:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2615:                 unless ($i == $env{'form.previousversion'}) {
                   2616:                     $numversions ++;
                   2617:                 }
                   2618:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2619:             }
                   2620:         }
                   2621:         if ($numversions) {
                   2622:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2623:             $result .=
                   2624:                 '<form name="getprev" method="post" action=""'.
                   2625:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2626:                 &Apache::loncommon::start_data_table().
                   2627:                 &Apache::loncommon::start_data_table_row().
                   2628:                 '<th align="left">'.$rowtitle.'</th>'.
                   2629:                 '<td><select name="version">'.
                   2630:                 '<option>'.&mt('Select').'</option>'.
                   2631:                 $list.
                   2632:                 '</select></td>'.
                   2633:                 &Apache::loncommon::end_data_table_row();
                   2634:             unless ($nomenu) {
                   2635:                 $result .= &Apache::loncommon::start_data_table_row().
                   2636:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2637:                 '<td><span class="LC_nobreak">'.
                   2638:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2639:                 &mt('Yes').'</label>'.
                   2640:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2641:                 '</span></td>'.
                   2642:                 &Apache::loncommon::end_data_table_row();
                   2643:             }
                   2644:             $result .=
                   2645:                 &Apache::loncommon::start_data_table_row().
                   2646:                 '<th align="left">&nbsp;</th>'.
                   2647:                 '<td>'.
                   2648:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2649:                 '</td>'.
                   2650:                 &Apache::loncommon::end_data_table_row().
                   2651:                 &Apache::loncommon::end_data_table().
                   2652:                 '</form>';
                   2653:             $js = &previous_display_javascript($nomenu,$current);
                   2654:         } elsif ($displayed && $nomenu) {
                   2655:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2656:         } else {
                   2657:             $result .= &mt('No previous versions to show for this student');
                   2658:         }
                   2659:         $result .= '</div>';
                   2660:     }
                   2661:     return ($current,$displayed,$result,$js);
                   2662: }
                   2663: 
                   2664: sub previous_display_javascript {
                   2665:     my ($nomenu,$current) = @_;
                   2666:     my $js = <<"JSONE";
                   2667: <script type="text/javascript">
                   2668: // <![CDATA[
                   2669: function previousVersion(uname,udom,symb) {
                   2670:     var current = '$current';
                   2671:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2672:     var prevstr = new RegExp("^\\\\d+\$");
                   2673:     if (!prevstr.test(version)) {
                   2674:         return false;
                   2675:     }
                   2676:     var url = '';
                   2677:     if (version == current) {
                   2678:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2679:     } else {
                   2680:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2681:     }
                   2682: JSONE
                   2683:     if ($nomenu) {
                   2684:         $js .= <<"JSTWO";
                   2685:     document.location.href = url;
                   2686: JSTWO
                   2687:     } else {
                   2688:         $js .= <<"JSTHREE";
                   2689:     var newwin = 0;
                   2690:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2691:         if (document.getprev.prevwin[i].checked == true) {
                   2692:             newwin = document.getprev.prevwin[i].value;
                   2693:         }
                   2694:     }
                   2695:     if (newwin == 1) {
                   2696:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2697:         url = url+'&inhibitmenu=yes';
                   2698:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2699:             previousWin = window.open(url,'',options,1);
                   2700:         } else {
                   2701:             previousWin.location.href = url;
                   2702:         }
                   2703:         previousWin.focus();
                   2704:         return false;
                   2705:     } else {
                   2706:         document.location.href = url;
                   2707:         return false;
                   2708:     }
                   2709: JSTHREE
                   2710:     }
                   2711:     $js .= <<"ENDJS";
                   2712:     return false;
                   2713: }
                   2714: // ]]>
                   2715: </script>
                   2716: ENDJS
                   2717: 
                   2718: }
                   2719: 
1.44      ng       2720: #--- Called from submission routine
1.38      ng       2721: sub processHandGrade {
1.608     www      2722:     my ($request,$symb) = @_;
1.324     albertel 2723:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2724:     my $button = $env{'form.gradeOpt'};
                   2725:     my $ngrade = $env{'form.NCT'};
                   2726:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2727:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2728:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2729: 
1.44      ng       2730:     if ($button eq 'Save & Next') {
                   2731: 	my $ctr = 0;
                   2732: 	while ($ctr < $ngrade) {
1.257     albertel 2733: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2734: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2735: 	    if ($errorflag eq 'no_score') {
                   2736: 		$ctr++;
                   2737: 		next;
                   2738: 	    }
1.104     albertel 2739: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2740: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2741: 		$ctr++;
                   2742: 		next;
                   2743: 	    }
1.257     albertel 2744: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2745: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2746: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2747:             my ($feedurl,$showsymb) =
                   2748: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2749: 	    my $messagetail;
1.62      albertel 2750: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2751: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2752: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2753: 		$subject.=' ['.$restitle.']';
1.44      ng       2754: 		my (@msgnum) = split(/,/,$includemsg);
                   2755: 		foreach (@msgnum) {
1.257     albertel 2756: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2757: 		}
1.80      ng       2758: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2759: 		if ($env{'form.withgrades'.$ctr}) {
                   2760: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2761: 		    $messagetail = " for <a href=\"".
1.605     www      2762: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2763: 		}
                   2764: 		$msgstatus = 
                   2765:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2766: 						     $message.$messagetail,
1.418     albertel 2767:                                                      undef,$feedurl,undef,
1.386     raeburn  2768:                                                      undef,undef,$showsymb,
                   2769:                                                      $restitle);
1.574     bisitz   2770: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2771: 				$msgstatus.'<br />');
1.44      ng       2772: 	    }
1.257     albertel 2773: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2774: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2775: 		foreach my $collabstr (@collabstrs) {
                   2776: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2777: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2778: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2779: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2780: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2781: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2782: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2783: 			    next;
1.418     albertel 2784: 			} elsif ($message ne '') {
                   2785: 			    my ($baseurl,$showsymb) = 
                   2786: 				&get_feedurl_and_symb($symb,$collaborator,
                   2787: 						      $udom);
                   2788: 			    if ($env{'form.withgrades'.$ctr}) {
                   2789: 				$messagetail = " for <a href=\"".
1.605     www      2790:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2791: 			    }
1.418     albertel 2792: 			    $msgstatus = 
                   2793: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2794: 			}
1.44      ng       2795: 		    }
                   2796: 		}
                   2797: 	    }
                   2798: 	    $ctr++;
                   2799: 	}
                   2800:     }
                   2801: 
1.624     www      2802: #    if ($env{'form.handgrade'} eq 'yes') {
                   2803:     if (1) {
1.119     ng       2804: 	# Keywords sorted in alphabatical order
1.257     albertel 2805: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2806: 	my %keyhash = ();
1.257     albertel 2807: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2808: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2809: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2810: 	$env{'form.keywords'} = join(' ',@keywords);
                   2811: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2812: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2813: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2814: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2815: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2816: 
                   2817: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2818: 	# New messages are saved in env for the next student.
1.119     ng       2819: 	# All messages are saved in nohist_handgrade.db
                   2820: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2821: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2822: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2823: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2824: 		$idx++;
                   2825: 	    }
                   2826: 	    $ctr++;
1.41      ng       2827: 	}
1.119     ng       2828: 	$ctr = 0;
                   2829: 	while ($ctr < $ngrade) {
1.257     albertel 2830: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2831: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2832: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2833: 		$idx++;
                   2834: 	    }
                   2835: 	    $ctr++;
1.41      ng       2836: 	}
1.257     albertel 2837: 	$env{'form.savemsgN'} = --$idx;
                   2838: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2839: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2840: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2841:     }
1.44      ng       2842:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2843:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2844:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2845: 	my ($ctr,$total) = (0,0);
                   2846: 	while ($ctr < $ngrade) {
1.257     albertel 2847: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2848: 	    $ctr++;
                   2849: 	}
1.257     albertel 2850: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2851: 	$ctr = 0;
                   2852: 	while ($ctr < $total) {
1.257     albertel 2853: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2854: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2855: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2856: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2857: 	    $ctr++;
                   2858: 	}
                   2859: 	return '';
                   2860:     }
1.36      ng       2861: 
1.44      ng       2862:     # Get the next/previous one or group of students
1.257     albertel 2863:     my $firststu = $env{'form.unamedom0'};
                   2864:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2865:     my $ctr = 2;
1.41      ng       2866:     while ($laststu eq '') {
1.257     albertel 2867: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2868: 	$ctr++;
                   2869: 	$laststu = $firststu if ($ctr > $ngrade);
                   2870:     }
1.44      ng       2871: 
1.41      ng       2872:     my (@parsedlist,@nextlist);
                   2873:     my ($nextflg) = 0;
1.524     raeburn  2874:     foreach my $item (sort 
1.294     albertel 2875: 	     {
                   2876: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2877: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2878: 		 }
                   2879: 		 return $a cmp $b;
                   2880: 	     } (keys(%$fullname))) {
1.605     www      2881: # FIXME: this is fishy, looks like the button label
1.41      ng       2882: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2883: 	    push(@parsedlist,$item);
1.41      ng       2884: 	}
1.524     raeburn  2885: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2886: 	if ($button eq 'Previous') {
1.524     raeburn  2887: 	    last if ($item eq $firststu);
                   2888: 	    push(@parsedlist,$item);
1.41      ng       2889: 	}
                   2890:     }
                   2891:     $ctr = 0;
1.605     www      2892: # FIXME: this is fishy, looks like the button label
1.41      ng       2893:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2894:     my $res_error;
                   2895:     my ($partlist) = &response_type($symb,\$res_error);
                   2896:     if ($res_error) {
                   2897:         $request->print(&navmap_errormsg());
                   2898:         return;
                   2899:     }
1.41      ng       2900:     foreach my $student (@parsedlist) {
1.257     albertel 2901: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2902: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2903: 	
                   2904: 	if ($submitonly eq 'queued') {
                   2905: 	    my %queue_status = 
                   2906: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2907: 							$udom,$uname);
                   2908: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2909: 	}
                   2910: 
1.156     albertel 2911: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2912: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2913: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2914: 	    my $submitted = 0;
1.248     albertel 2915: 	    my $ungraded = 0;
                   2916: 	    my $incorrect = 0;
1.524     raeburn  2917: 	    foreach my $item (keys(%status)) {
                   2918: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2919: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2920: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2921: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2922: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2923: 		    $submitted = 0;
                   2924: 		}
1.41      ng       2925: 	    }
1.156     albertel 2926: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2927: 				     $submitonly eq 'incorrect' ||
                   2928: 				     $submitonly eq 'graded'));
1.248     albertel 2929: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2930: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2931: 	}
1.524     raeburn  2932: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2933: 	last if ($ctr == $ntstu);
1.41      ng       2934: 	$ctr++;
                   2935:     }
1.36      ng       2936: 
1.41      ng       2937:     $ctr = 0;
                   2938:     my $total = scalar(@nextlist)-1;
1.39      ng       2939: 
1.524     raeburn  2940:     foreach (sort(@nextlist)) {
1.41      ng       2941: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2942: 	$env{'form.student'}  = $uname;
                   2943: 	$env{'form.userdom'}  = $udom;
                   2944: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2945: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2946: 	$ctr++;
                   2947:     }
                   2948:     if ($total < 0) {
1.653     raeburn  2949: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2950: 	$request->print($the_end);
                   2951:     }
                   2952:     return '';
1.38      ng       2953: }
1.36      ng       2954: 
1.44      ng       2955: #---- Save the score and award for each student, if changed
1.38      ng       2956: sub saveHandGrade {
1.324     albertel 2957:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2958:     my @version_parts;
1.104     albertel 2959:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2960: 					   $env{'request.course.id'});
1.104     albertel 2961:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2962:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2963:     my @parts_graded;
1.77      ng       2964:     my %newrecord  = ();
                   2965:     my ($pts,$wgt) = ('','');
1.269     raeburn  2966:     my %aggregate = ();
                   2967:     my $aggregateflag = 0;
1.301     albertel 2968:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2969:     foreach my $new_part (@parts) {
1.337     banghart 2970: 	#collaborator ($submi may vary for different parts
1.259     banghart 2971: 	if ($submitter && $new_part ne $part) { next; }
                   2972: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2973: 	if ($dropMenu eq 'excused') {
1.259     banghart 2974: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2975: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2976: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2977: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2978: 		}
1.364     banghart 2979: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2980: 	    }
1.125     ng       2981: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2982: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2983: 	    foreach my $key (keys(%record)) {
1.259     banghart 2984: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2985: 	    }
1.259     banghart 2986: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2987: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2988:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2989: 
                   2990:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2991: 					       [$new_part]);
                   2992:             my $aggtries =$totaltries;
1.269     raeburn  2993:             if ($last_resets{$new_part}) {
1.270     albertel 2994:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2995: 					   $new_part);
1.269     raeburn  2996:             }
1.270     albertel 2997: 
                   2998:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2999:             if ($aggtries > 0) {
1.327     albertel 3000:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3001:                 $aggregateflag = 1;
                   3002:             }
1.125     ng       3003: 	} elsif ($dropMenu eq '') {
1.259     banghart 3004: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3005: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3006: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3007: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3008: 		next;
                   3009: 	    }
1.259     banghart 3010: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3011: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3012: 	    my $partial= $pts/$wgt;
1.259     banghart 3013: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3014: 		#do not update score for part if not changed.
1.346     banghart 3015:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3016: 		next;
1.251     banghart 3017: 	    } else {
1.524     raeburn  3018: 	        push(@parts_graded,$new_part);
1.153     albertel 3019: 	    }
1.259     banghart 3020: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3021: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3022: 	    }
1.259     banghart 3023: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3024: 	    if ($partial == 0) {
1.153     albertel 3025: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3026: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3027: 		}
1.41      ng       3028: 	    } else {
1.153     albertel 3029: 		if ($record{$reckey} ne 'correct_by_override') {
                   3030: 		    $newrecord{$reckey} = 'correct_by_override';
                   3031: 		}
                   3032: 	    }	    
                   3033: 	    if ($submitter && 
1.259     banghart 3034: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3035: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3036: 	    }
1.259     banghart 3037: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3038: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3039: 	}
1.259     banghart 3040: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3041: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3042: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3043: 	        $dropMenu eq 'reset status')
                   3044: 	   {
1.524     raeburn  3045: 	    push(@version_parts,$new_part);
1.259     banghart 3046: 	}
1.41      ng       3047:     }
1.301     albertel 3048:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3049:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3050: 
1.344     albertel 3051:     if (%newrecord) {
                   3052:         if (@version_parts) {
1.364     banghart 3053:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3054:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3055: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3056: 	    foreach my $new_part (@version_parts) {
                   3057: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3058: 				$new_part,\%newrecord);
                   3059: 	    }
1.259     banghart 3060:         }
1.44      ng       3061: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3062: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3063: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3064: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3065:     }
1.269     raeburn  3066:     if ($aggregateflag) {
                   3067:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3068: 			      $cdom,$cnum);
1.269     raeburn  3069:     }
1.301     albertel 3070:     return ('',$pts,$wgt);
1.36      ng       3071: }
1.322     albertel 3072: 
1.380     albertel 3073: sub check_and_remove_from_queue {
                   3074:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3075:     my @ungraded_parts;
                   3076:     foreach my $part (@{$parts}) {
                   3077: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3078: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3079: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3080: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3081: 		) {
                   3082: 	    push(@ungraded_parts, $part);
                   3083: 	}
                   3084:     }
                   3085:     if ( !@ungraded_parts ) {
                   3086: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3087: 					       $cnum,$domain,$stuname);
                   3088:     }
                   3089: }
                   3090: 
1.337     banghart 3091: sub handback_files {
                   3092:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3093:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3094:     my $res_error;
                   3095:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3096:     if ($res_error) {
                   3097:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3098:         return;
                   3099:     }
1.654     raeburn  3100:     my @handedback;
                   3101:     my $file_msg;
1.375     albertel 3102:     my @part_response_id = &flatten_responseType($responseType);
                   3103:     foreach my $part_response_id (@part_response_id) {
                   3104:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3105: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3106:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3107:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3108:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3109:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3110:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3111:                     my ($directory,$answer_file) = 
1.654     raeburn  3112:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3113:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3114: 		        &file_name_version_ext($answer_file);
1.355     banghart 3115: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3116:                     my $getpropath = 1;
1.662     raeburn  3117:                     my ($dir_list,$listerror) = 
                   3118:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3119:                                                  $domain,$stuname,$getpropath);
                   3120: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3121:                     # fix filename
1.355     banghart 3122:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3123:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3124:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3125:             	                                $save_file_name);
1.337     banghart 3126:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3127:                         $request->print('<br /><span class="LC_error">'.
                   3128:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3129:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3130:                                         '</span>');
1.356     banghart 3131:                     } else {
1.360     banghart 3132:                         # mark the file as read only
1.654     raeburn  3133:                         push(@handedback,$save_file_name);
1.367     albertel 3134: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3135: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3136: 			}
                   3137:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3138: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3139:                     }
1.686     bisitz   3140:                     $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 3141:                 }
                   3142:             }
                   3143:         }
1.654     raeburn  3144:     }
                   3145:     if (@handedback > 0) {
                   3146:         $request->print('<br />');
                   3147:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3148:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3149:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3150:         my ($subject,$message);
                   3151:         if (scalar(@handedback) == 1) {
                   3152:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3153:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3154:         } else {
                   3155:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3156:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3157:         }
                   3158:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3159:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3160:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3161:         my ($feedurl,$showsymb) =
                   3162:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3163:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3164:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3165:         my $msgstatus =
                   3166:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3167:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3168:                  $restitle);
                   3169:         if ($msgstatus) {
                   3170:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3171:         }
                   3172:     }
1.338     banghart 3173:     return;
1.337     banghart 3174: }
                   3175: 
1.418     albertel 3176: sub get_feedurl_and_symb {
                   3177:     my ($symb,$uname,$udom) = @_;
                   3178:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3179:     $url = &Apache::lonnet::clutter($url);
                   3180:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3181: 					$symb,$udom,$uname);
                   3182:     if ($encrypturl =~ /^yes$/i) {
                   3183: 	&Apache::lonenc::encrypted(\$url,1);
                   3184: 	&Apache::lonenc::encrypted(\$symb,1);
                   3185:     }
                   3186:     return ($url,$symb);
                   3187: }
                   3188: 
1.313     banghart 3189: sub get_submitted_files {
                   3190:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3191:     my @files;
                   3192:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3193:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3194:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3195:     	    push(@files,$file_url.$file);
                   3196:         }
                   3197:     }
                   3198:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3199:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3200:     }
                   3201:     return (\@files);
                   3202: }
1.322     albertel 3203: 
1.269     raeburn  3204: # ----------- Provides number of tries since last reset.
                   3205: sub get_num_tries {
                   3206:     my ($record,$last_reset,$part) = @_;
                   3207:     my $timestamp = '';
                   3208:     my $num_tries = 0;
                   3209:     if ($$record{'version'}) {
                   3210:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3211:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3212:                 $timestamp = $$record{$version.':timestamp'};
                   3213:                 if ($timestamp > $last_reset) {
                   3214:                     $num_tries ++;
                   3215:                 } else {
                   3216:                     last;
                   3217:                 }
                   3218:             }
                   3219:         }
                   3220:     }
                   3221:     return $num_tries;
                   3222: }
                   3223: 
                   3224: # ----------- Determine decrements required in aggregate totals 
                   3225: sub decrement_aggs {
                   3226:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3227:     my %decrement = (
                   3228:                         attempts => 0,
                   3229:                         users => 0,
                   3230:                         correct => 0
                   3231:                     );
                   3232:     $decrement{'attempts'} = $aggtries;
                   3233:     if ($solvedstatus =~ /^correct/) {
                   3234:         $decrement{'correct'} = 1;
                   3235:     }
                   3236:     if ($aggtries == $totaltries) {
                   3237:         $decrement{'users'} = 1;
                   3238:     }
1.524     raeburn  3239:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3240:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3241:     }
                   3242:     return;
                   3243: }
                   3244: 
                   3245: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3246: sub get_last_resets {
1.270     albertel 3247:     my ($symb,$courseid,$partids) =@_;
                   3248:     my %last_resets;
1.269     raeburn  3249:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3250:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3251:     my @keys;
                   3252:     foreach my $part (@{$partids}) {
                   3253: 	push(@keys,"$symb\0$part\0resettime");
                   3254:     }
                   3255:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3256: 				     $cdom,$cname);
                   3257:     foreach my $part (@{$partids}) {
                   3258: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3259:     }
1.270     albertel 3260:     return %last_resets;
1.269     raeburn  3261: }
                   3262: 
1.251     banghart 3263: # ----------- Handles creating versions for portfolio files as answers
                   3264: sub version_portfiles {
1.343     banghart 3265:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3266:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3267:     my @returned_keys;
1.255     banghart 3268:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3269:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3270:     foreach my $key (keys(%$record)) {
1.259     banghart 3271:         my $new_portfiles;
1.263     banghart 3272:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3273:             my @versioned_portfiles;
1.367     albertel 3274:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3275:             foreach my $file (@portfiles) {
1.306     banghart 3276:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3277:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3278: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3279: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3280:                 my $getpropath = 1;    
1.662     raeburn  3281:                 my ($dir_list,$listerror) = 
                   3282:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3283:                                              $stu_name,$getpropath);
                   3284:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3285:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3286:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3287:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3288:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3289:                         [$directory.$new_answer],
1.306     banghart 3290:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3291:                 }
1.252     banghart 3292:             }
1.343     banghart 3293:             $$record{$key} = join(',',@versioned_portfiles);
                   3294:             push(@returned_keys,$key);
1.251     banghart 3295:         }
                   3296:     } 
1.343     banghart 3297:     return (@returned_keys);   
1.305     banghart 3298: }
                   3299: 
1.307     banghart 3300: sub get_next_version {
1.341     banghart 3301:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3302:     my $version;
1.662     raeburn  3303:     if (ref($dir_list) eq 'ARRAY') {
                   3304:         foreach my $row (@{$dir_list}) {
                   3305:             my ($file) = split(/\&/,$row,2);
                   3306:             my ($file_name,$file_version,$file_ext) =
                   3307: 	        &file_name_version_ext($file);
                   3308:             if (($file_name eq $answer_name) && 
                   3309: 	        ($file_ext eq $answer_ext)) {
                   3310:                      # gets here if filename and extension match, 
                   3311:                      # regardless of version
1.307     banghart 3312:                 if ($file_version ne '') {
1.662     raeburn  3313:                     # a versioned file is found  so save it for later
                   3314:                     if ($file_version > $version) {
                   3315: 		        $version = $file_version;
                   3316: 	            }
                   3317:                 }
1.307     banghart 3318:             }
                   3319:         }
1.662     raeburn  3320:     }
1.307     banghart 3321:     $version ++;
                   3322:     return($version);
                   3323: }
                   3324: 
1.305     banghart 3325: sub version_selected_portfile {
1.306     banghart 3326:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3327:     my ($answer_name,$answer_ver,$answer_ext) =
                   3328:         &file_name_version_ext($file_name);
                   3329:     my $new_answer;
                   3330:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3331:     if($env{'form.copy'} eq '-1') {
                   3332:         $new_answer = 'problem getting file';
                   3333:     } else {
                   3334:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3335:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3336:                             $stu_name,$domain,'copy',
                   3337: 		        '/portfolio'.$directory.$new_answer);
                   3338:     }    
                   3339:     return ($new_answer);
1.251     banghart 3340: }
                   3341: 
1.304     albertel 3342: sub file_name_version_ext {
                   3343:     my ($file)=@_;
                   3344:     my @file_parts = split(/\./, $file);
                   3345:     my ($name,$version,$ext);
                   3346:     if (@file_parts > 1) {
                   3347: 	$ext=pop(@file_parts);
                   3348: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3349: 	    $version=pop(@file_parts);
                   3350: 	}
                   3351: 	$name=join('.',@file_parts);
                   3352:     } else {
                   3353: 	$name=join('.',@file_parts);
                   3354:     }
                   3355:     return($name,$version,$ext);
                   3356: }
                   3357: 
1.44      ng       3358: #--------------------------------------------------------------------------------------
                   3359: #
                   3360: #-------------------------- Next few routines handles grading by section or whole class
                   3361: #
                   3362: #--- Javascript to handle grading by section or whole class
1.42      ng       3363: sub viewgrades_js {
                   3364:     my ($request) = shift;
                   3365: 
1.539     riegler  3366:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3367:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3368:    function writePoint(partid,weight,point) {
1.125     ng       3369: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3370: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3371: 	if (point == "textval") {
1.125     ng       3372: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3373: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3374: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3375: 		var resetbox = false;
                   3376: 		for (var i=0; i<radioButton.length; i++) {
                   3377: 		    if (radioButton[i].checked) {
                   3378: 			textbox.value = i;
                   3379: 			resetbox = true;
                   3380: 		    }
                   3381: 		}
                   3382: 		if (!resetbox) {
                   3383: 		    textbox.value = "";
                   3384: 		}
                   3385: 		return;
                   3386: 	    }
1.109     matthew  3387: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3388: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3389: 				   ") greater than the weight for the part. Accept?");
                   3390: 		if (resp == false) {
                   3391: 		    textbox.value = "";
                   3392: 		    return;
                   3393: 		}
                   3394: 	    }
1.42      ng       3395: 	    for (var i=0; i<radioButton.length; i++) {
                   3396: 		radioButton[i].checked=false;
1.109     matthew  3397: 		if (parseFloat(point) == i) {
1.42      ng       3398: 		    radioButton[i].checked=true;
                   3399: 		}
                   3400: 	    }
1.41      ng       3401: 
1.42      ng       3402: 	} else {
1.125     ng       3403: 	    textbox.value = parseFloat(point);
1.42      ng       3404: 	}
1.41      ng       3405: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3406: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3407: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3408: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3409: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3410: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3411: 	    if (saveval != "correct") {
                   3412: 		scorename.value = point;
1.43      ng       3413: 		if (selname[0].selected != true) {
                   3414: 		    selname[0].selected = true;
                   3415: 		}
1.42      ng       3416: 	    }
                   3417: 	}
1.125     ng       3418: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3419:     }
                   3420: 
                   3421:     function writeRadText(partid,weight) {
1.125     ng       3422: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3423: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3424:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3425: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3426: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3427: 	    for (var i=0; i<radioButton.length; i++) {
                   3428: 		radioButton[i].checked=false;
                   3429: 
                   3430: 	    }
                   3431: 	    textbox.value = "";
                   3432: 
                   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.265     www      3439: 		if ((saveval != "correct") || override) {
1.42      ng       3440: 		    scorename.value = "";
1.125     ng       3441: 		    if (selval[1].selected) {
                   3442: 			selname[1].selected = true;
                   3443: 		    } else {
                   3444: 			selname[2].selected = true;
                   3445: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3446: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3447: 		    }
1.42      ng       3448: 		}
                   3449: 	    }
1.43      ng       3450: 	} else {
                   3451: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3452: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3453: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3454: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3455: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3456: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3457: 		if ((saveval != "correct") || override) {
1.125     ng       3458: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3459: 		    selname[0].selected = true;
                   3460: 		}
                   3461: 	    }
                   3462: 	}	    
1.42      ng       3463:     }
                   3464: 
                   3465:     function changeSelect(partid,user) {
1.125     ng       3466: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3467: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3468: 	var point  = textbox.value;
1.125     ng       3469: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3470: 
1.109     matthew  3471: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3472: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3473: 	    textbox.value = "";
                   3474: 	    return;
                   3475: 	}
1.109     matthew  3476: 	if (parseFloat(point) > parseFloat(weight)) {
                   3477: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3478: 			       ") greater than the weight of the part. Accept?");
                   3479: 	    if (resp == false) {
                   3480: 		textbox.value = "";
                   3481: 		return;
                   3482: 	    }
                   3483: 	}
1.42      ng       3484: 	selval[0].selected = true;
                   3485:     }
                   3486: 
                   3487:     function changeOneScore(partid,user) {
1.125     ng       3488: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3489: 	if (selval[1].selected || selval[2].selected) {
                   3490: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3491: 	    if (selval[2].selected) {
                   3492: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3493: 	    }
1.269     raeburn  3494:         }
1.42      ng       3495:     }
                   3496: 
                   3497:     function resetEntry(numpart) {
                   3498: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3499: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3500: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3501: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3502: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3503: 	    for (var i=0; i<radioButton.length; i++) {
                   3504: 		radioButton[i].checked=false;
                   3505: 
                   3506: 	    }
                   3507: 	    textbox.value = "";
                   3508: 	    selval[0].selected = true;
                   3509: 
                   3510: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3511: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3512: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3513: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3514: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3515: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3516: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3517: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3518: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3519: 		if (saveselval == "excused") {
1.43      ng       3520: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3521: 		} else {
1.43      ng       3522: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3523: 		}
                   3524: 	    }
1.41      ng       3525: 	}
1.42      ng       3526:     }
                   3527: 
1.41      ng       3528: VIEWJAVASCRIPT
1.42      ng       3529: }
                   3530: 
1.44      ng       3531: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3532: sub viewgrades {
1.608     www      3533:     my ($request,$symb) = @_;
1.42      ng       3534:     &viewgrades_js($request);
1.41      ng       3535: 
1.168     albertel 3536:     #need to make sure we have the correct data for later EXT calls, 
                   3537:     #thus invalidate the cache
                   3538:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3539:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3540:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3541:     &Apache::lonnet::clear_EXT_cache_status();
                   3542: 
1.398     albertel 3543:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3544: 
                   3545:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3546:     $result.=&jscriptNform($symb);
1.41      ng       3547: 
1.44      ng       3548:     #beginning of class grading form
1.442     banghart 3549:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3550:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3551: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3552: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3553: 	&build_section_inputs().
1.442     banghart 3554: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3555: 
1.560     raeburn  3556:     my ($common_header,$specific_header);
1.257     albertel 3557:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3558: 	$common_header = &mt('Assign Common Grade to Class');
                   3559:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3560:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3561:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3562: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3563:     } else {
1.560     raeburn  3564:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3565:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3566: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3567:     }
1.560     raeburn  3568:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3569:     #radio buttons/text box for assigning points for a section or class.
                   3570:     #handles different parts of a problem
1.582     raeburn  3571:     my $res_error;
                   3572:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3573:     if ($res_error) {
                   3574:         return &navmap_errormsg();
                   3575:     }
1.42      ng       3576:     my %weight = ();
                   3577:     my $ctsparts = 0;
1.45      ng       3578:     my %seen = ();
1.375     albertel 3579:     my @part_response_id = &flatten_responseType($responseType);
                   3580:     foreach my $part_response_id (@part_response_id) {
                   3581:     	my ($partid,$respid) = @{ $part_response_id };
                   3582: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3583: 	next if $seen{$partid};
                   3584: 	$seen{$partid}++;
1.375     albertel 3585: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3586: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3587: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3588: 
1.324     albertel 3589: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3590: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3591: 	my $ctr = 0;
1.42      ng       3592: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3593: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3594: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3595: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3596: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3597: 	    $ctr++;
                   3598: 	}
1.485     albertel 3599: 	$radio.='</tr></table>';
                   3600: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3601: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3602: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3603: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3604:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3605:             '<select name="SELVAL_'.$partid.'" '.
                   3606:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3607:                 $weight{$partid}.')"> '.
1.401     albertel 3608: 	    '<option selected="selected"> </option>'.
1.485     albertel 3609: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3610: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3611: 	    '</select></td>'.
                   3612:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3613: 	$line.='<input type="hidden" name="partid_'.
                   3614: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3615: 	$line.='<input type="hidden" name="weight_'.
                   3616: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3617: 
                   3618: 	$result.=
                   3619: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3620: 	    '<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 3621: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3622: 	$ctsparts++;
1.41      ng       3623:     }
1.474     albertel 3624:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3625: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3626:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3627: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3628: 
1.44      ng       3629:     #table listing all the students in a section/class
                   3630:     #header of table
1.560     raeburn  3631:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3632:               &Apache::loncommon::start_data_table().
                   3633: 	      &Apache::loncommon::start_data_table_header_row().
                   3634: 	      '<th>'.&mt('No.').'</th>'.
                   3635: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3636:     my $partserror;
                   3637:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3638:     if ($partserror) {
                   3639:         return &navmap_errormsg();
                   3640:     }
1.324     albertel 3641:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3642:     my @partids = ();
1.41      ng       3643:     foreach my $part (@parts) {
                   3644: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3645:         my $narrowtext = &mt('Tries');
                   3646: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3647: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3648: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3649:         push(@partids,$partid);
1.628     www      3650: #
                   3651: # FIXME: Looks like $display looks at English text
                   3652: #
1.324     albertel 3653: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3654: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3655: 	    $result.='<th>'.
1.697     bisitz   3656: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3657: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3658: 	    next;
1.485     albertel 3659: 	    
1.207     albertel 3660: 	} else {
1.485     albertel 3661: 	    if ($display =~ /Problem Status/) {
                   3662: 		my $grade_status_mt = &mt('Grade Status');
                   3663: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3664: 	    }
                   3665: 	    my $part_mt = &mt('Part:');
                   3666: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3667: 	}
1.485     albertel 3668: 
1.474     albertel 3669: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3670:     }
1.474     albertel 3671:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3672: 
1.270     albertel 3673:     my %last_resets = 
                   3674: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3675: 
1.41      ng       3676:     #get info for each student
1.44      ng       3677:     #list all the students - with points and grade status
1.257     albertel 3678:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3679:     my $ctr = 0;
1.294     albertel 3680:     foreach (sort 
                   3681: 	     {
                   3682: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3683: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3684: 		 }
                   3685: 		 return $a cmp $b;
                   3686: 	     } (keys(%$fullname))) {
1.126     ng       3687: 	$ctr++;
1.324     albertel 3688: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3689: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3690:     }
1.474     albertel 3691:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3692:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3693:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3694: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3695:     if (scalar(%$fullname) eq 0) {
                   3696: 	my $colspan=3+scalar(@parts);
1.433     banghart 3697: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3698:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3699: 	$result='<span class="LC_warning">'.
1.485     albertel 3700: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3701: 	        $section_display, $stu_status).
1.433     banghart 3702: 	    '</span>';
1.96      albertel 3703:     }
1.41      ng       3704:     return $result;
                   3705: }
                   3706: 
1.44      ng       3707: #--- call by previous routine to display each student
1.41      ng       3708: sub viewstudentgrade {
1.324     albertel 3709:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3710:     my ($uname,$udom) = split(/:/,$student);
                   3711:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3712:     my %aggregates = (); 
1.474     albertel 3713:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3714: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3715: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3716: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3717: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3718: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3719:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3720:     foreach my $apart (@$parts) {
                   3721: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3722: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3723:         $result.='<td align="center">';
1.269     raeburn  3724:         my ($aggtries,$totaltries);
                   3725:         unless (exists($aggregates{$part})) {
1.270     albertel 3726: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3727: 
                   3728: 	    $aggtries = $totaltries;
1.269     raeburn  3729:             if ($$last_resets{$part}) {  
1.270     albertel 3730:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3731: 					   $part);
                   3732:             }
1.269     raeburn  3733:             $result.='<input type="hidden" name="'.
                   3734:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3735:             $result.='<input type="hidden" name="'.
                   3736:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3737:             $aggregates{$part} = 1;
                   3738:         }
1.41      ng       3739: 	if ($type eq 'awarded') {
1.320     albertel 3740: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3741: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3742: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3743: 	    $result.='<input type="text" name="'.
1.89      albertel 3744: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3745:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3746: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3747: 	} elsif ($type eq 'solved') {
                   3748: 	    my ($status,$foo)=split(/_/,$score,2);
                   3749: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3750: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3751: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3752: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3753: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3754:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3755: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3756: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3757: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3758: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3759: 	} else {
                   3760: 	    $result.='<input type="hidden" name="'.
                   3761: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3762: 		    "\n";
1.233     albertel 3763: 	    $result.='<input type="text" name="'.
1.122     ng       3764: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3765: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3766: 	}
                   3767:     }
1.474     albertel 3768:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3769:     return $result;
1.38      ng       3770: }
                   3771: 
1.44      ng       3772: #--- change scores for all the students in a section/class
                   3773: #    record does not get update if unchanged
1.38      ng       3774: sub editgrades {
1.608     www      3775:     my ($request,$symb) = @_;
1.41      ng       3776: 
1.433     banghart 3777:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3778:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3779:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3780: 
1.477     albertel 3781:     my $result= &Apache::loncommon::start_data_table().
                   3782: 	&Apache::loncommon::start_data_table_header_row().
                   3783: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3784: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3785:     my %scoreptr = (
                   3786: 		    'correct'  =>'correct_by_override',
                   3787: 		    'incorrect'=>'incorrect_by_override',
                   3788: 		    'excused'  =>'excused',
                   3789: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3790:                     'credited' =>'credit_attempted',
1.43      ng       3791: 		    'nothing'  => '',
                   3792: 		    );
1.257     albertel 3793:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3794: 
1.44      ng       3795:     my (@partid);
                   3796:     my %weight = ();
1.54      albertel 3797:     my %columns = ();
1.44      ng       3798:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3799: 
1.582     raeburn  3800:     my $partserror;
                   3801:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3802:     if ($partserror) {
                   3803:         return &navmap_errormsg();
                   3804:     }
1.54      albertel 3805:     my $header;
1.257     albertel 3806:     while ($ctr < $env{'form.totalparts'}) {
                   3807: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3808: 	push(@partid,$partid);
1.257     albertel 3809: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3810: 	$ctr++;
1.54      albertel 3811:     }
1.324     albertel 3812:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3813:     foreach my $partid (@partid) {
1.478     albertel 3814: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3815: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3816: 	$columns{$partid}=2;
                   3817: 	foreach my $stores (@parts) {
                   3818: 	    my ($part,$type) = &split_part_type($stores);
                   3819: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3820: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3821: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3822: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3823:             my $narrowtext = &mt('Tries');
                   3824: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3825: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3826: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3827: 	    $columns{$partid}+=2;
                   3828: 	}
                   3829:     }
                   3830:     foreach my $partid (@partid) {
1.324     albertel 3831: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3832: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3833: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3834: 	    '</th>';
1.54      albertel 3835: 
1.44      ng       3836:     }
1.477     albertel 3837:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3838: 	&Apache::loncommon::start_data_table_header_row().
                   3839: 	$header.
                   3840: 	&Apache::loncommon::end_data_table_header_row();
                   3841:     my @noupdate;
1.126     ng       3842:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3843:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3844: 	my $line;
1.257     albertel 3845: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3846: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3847: 	my %newrecord;
                   3848: 	my $updateflag = 0;
1.281     albertel 3849: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3850: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3851: 	if (!&canmodify($usec)) {
1.126     ng       3852: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3853: 	    push(@noupdate,
1.478     albertel 3854: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3855: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3856: 	    next;
                   3857: 	}
1.269     raeburn  3858:         my %aggregate = ();
                   3859:         my $aggregateflag = 0;
1.281     albertel 3860: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3861: 	foreach (@partid) {
1.257     albertel 3862: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3863: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3864: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3865: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3866: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3867: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3868: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3869: 	    my $score;
                   3870: 	    if ($partial eq '') {
1.257     albertel 3871: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3872: 	    } elsif ($partial > 0) {
                   3873: 		$score = 'correct_by_override';
                   3874: 	    } elsif ($partial == 0) {
                   3875: 		$score = 'incorrect_by_override';
                   3876: 	    }
1.257     albertel 3877: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3878: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3879: 
1.292     albertel 3880: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3881: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3882: 	    if ($dropMenu eq 'reset status' &&
                   3883: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3884: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3885: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3886: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3887: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3888: 		$updateflag = 1;
1.269     raeburn  3889:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3890:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3891:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3892:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3893:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3894:                     $aggregateflag = 1;
                   3895:                 }
1.139     albertel 3896: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3897: 		$updateflag = 1;
                   3898: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3899: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3900: 		$rec_update++;
1.125     ng       3901: 	    }
                   3902: 
1.93      albertel 3903: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3904: 		'<td align="center">'.$awarded.
                   3905: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3906: 
1.54      albertel 3907: 
                   3908: 	    my $partid=$_;
                   3909: 	    foreach my $stores (@parts) {
                   3910: 		my ($part,$type) = &split_part_type($stores);
                   3911: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3912: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3913: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3914: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3915: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3916: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3917: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3918: 		    $updateflag=1;
                   3919: 		}
1.93      albertel 3920: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3921: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3922: 	    }
1.44      ng       3923: 	}
1.477     albertel 3924: 	$line.="\n";
1.301     albertel 3925: 
                   3926: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3927: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3928: 
1.44      ng       3929: 	if ($updateflag) {
                   3930: 	    $count++;
1.257     albertel 3931: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3932: 				    $udom,$uname);
1.301     albertel 3933: 
                   3934: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3935: 					      $cnum,$udom,$uname)) {
                   3936: 		# need to figure out if should be in queue.
                   3937: 		my %record =  
                   3938: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3939: 					     $udom,$uname);
                   3940: 		my $all_graded = 1;
                   3941: 		my $none_graded = 1;
                   3942: 		foreach my $part (@parts) {
                   3943: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3944: 			$all_graded = 0;
                   3945: 		    } else {
                   3946: 			$none_graded = 0;
                   3947: 		    }
                   3948: 		}
                   3949: 
                   3950: 		if ($all_graded || $none_graded) {
                   3951: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3952: 							   $symb,$cdom,$cnum,
                   3953: 							   $udom,$uname);
                   3954: 		}
                   3955: 	    }
                   3956: 
1.477     albertel 3957: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3958: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3959: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3960: 	    $updateCtr++;
1.93      albertel 3961: 	} else {
1.477     albertel 3962: 	    push(@noupdate,
                   3963: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3964: 	    $noupdateCtr++;
1.44      ng       3965: 	}
1.269     raeburn  3966:         if ($aggregateflag) {
                   3967:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3968: 				  $cdom,$cnum);
1.269     raeburn  3969:         }
1.93      albertel 3970:     }
1.477     albertel 3971:     if (@noupdate) {
1.126     ng       3972: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3973: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3974: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3975: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3976: 	    &mt('No Changes Occurred For the Students Below').
                   3977: 	    '</td>'.
1.477     albertel 3978: 	    &Apache::loncommon::end_data_table_row();
                   3979: 	foreach my $line (@noupdate) {
                   3980: 	    $result.=
                   3981: 		&Apache::loncommon::start_data_table_row().
                   3982: 		$line.
                   3983: 		&Apache::loncommon::end_data_table_row();
                   3984: 	}
1.44      ng       3985:     }
1.614     www      3986:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3987:     my $msg = '<p><b>'.
                   3988: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3989: 	    $rec_update,$count).'</b><br />'.
                   3990: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3991: 	'</b></p>';
1.44      ng       3992:     return $title.$msg.$result;
1.5       albertel 3993: }
1.54      albertel 3994: 
                   3995: sub split_part_type {
                   3996:     my ($partstr) = @_;
                   3997:     my ($temp,@allparts)=split(/_/,$partstr);
                   3998:     my $type=pop(@allparts);
1.439     albertel 3999:     my $part=join('_',@allparts);
1.54      albertel 4000:     return ($part,$type);
                   4001: }
                   4002: 
1.44      ng       4003: #------------- end of section for handling grading by section/class ---------
                   4004: #
                   4005: #----------------------------------------------------------------------------
                   4006: 
1.5       albertel 4007: 
1.44      ng       4008: #----------------------------------------------------------------------------
                   4009: #
                   4010: #-------------------------- Next few routines handles grading by csv upload
                   4011: #
                   4012: #--- Javascript to handle csv upload
1.27      albertel 4013: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4014:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4015:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4016:   return(<<ENDPICK);
                   4017:   function verify(vf) {
                   4018:     var foundsomething=0;
                   4019:     var founduname=0;
1.243     albertel 4020:     var foundID=0;
1.27      albertel 4021:     for (i=0;i<=vf.nfields.value;i++) {
                   4022:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4023:       if (i==0 && tw!=0) { foundID=1; }
                   4024:       if (i==1 && tw!=0) { founduname=1; }
                   4025:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4026:     }
1.246     albertel 4027:     if (founduname==0 && foundID==0) {
                   4028: 	alert('$error1');
                   4029: 	return;
1.27      albertel 4030:     }
                   4031:     if (foundsomething==0) {
1.246     albertel 4032: 	alert('$error2');
                   4033: 	return;
1.27      albertel 4034:     }
                   4035:     vf.submit();
                   4036:   }
                   4037:   function flip(vf,tf) {
                   4038:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4039:     var i;
                   4040:     for (i=0;i<=vf.nfields.value;i++) {
                   4041:       //can not pick the same destination field for both name and domain
                   4042:       if (((i ==0)||(i ==1)) && 
                   4043:           ((tf==0)||(tf==1)) && 
                   4044:           (i!=tf) &&
                   4045:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4046:         eval('vf.f'+i+'.selectedIndex=0;')
                   4047:       }
                   4048:     }
                   4049:   }
                   4050: ENDPICK
                   4051: }
                   4052: 
                   4053: sub csvupload_javascript_forward_associate {
1.573     bisitz   4054:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4055:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4056:   return(<<ENDPICK);
                   4057:   function verify(vf) {
                   4058:     var foundsomething=0;
                   4059:     var founduname=0;
1.243     albertel 4060:     var foundID=0;
1.27      albertel 4061:     for (i=0;i<=vf.nfields.value;i++) {
                   4062:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4063:       if (tw==1) { foundID=1; }
                   4064:       if (tw==2) { founduname=1; }
                   4065:       if (tw>3) { foundsomething=1; }
1.27      albertel 4066:     }
1.246     albertel 4067:     if (founduname==0 && foundID==0) {
                   4068: 	alert('$error1');
                   4069: 	return;
1.27      albertel 4070:     }
                   4071:     if (foundsomething==0) {
1.246     albertel 4072: 	alert('$error2');
                   4073: 	return;
1.27      albertel 4074:     }
                   4075:     vf.submit();
                   4076:   }
                   4077:   function flip(vf,tf) {
                   4078:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4079:     var i;
                   4080:     //can not pick the same destination field twice
                   4081:     for (i=0;i<=vf.nfields.value;i++) {
                   4082:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4083:         eval('vf.f'+i+'.selectedIndex=0;')
                   4084:       }
                   4085:     }
                   4086:   }
                   4087: ENDPICK
                   4088: }
                   4089: 
1.26      albertel 4090: sub csvuploadmap_header {
1.324     albertel 4091:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4092:     my $javascript;
1.257     albertel 4093:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4094: 	$javascript=&csvupload_javascript_reverse_associate();
                   4095:     } else {
                   4096: 	$javascript=&csvupload_javascript_forward_associate();
                   4097:     }
1.45      ng       4098: 
1.418     albertel 4099:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4100:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4101:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4102:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4103:     my $reverse=&mt("Reverse Association");
1.41      ng       4104:     $request->print(<<ENDPICK);
1.632     www      4105: <br />
                   4106: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4107: <input type="hidden" name="associate"  value="" />
                   4108: <input type="hidden" name="phase"      value="three" />
                   4109: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4110: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4111: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4112: <input type="hidden" name="upfile_associate" 
1.257     albertel 4113:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4114: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4115: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4116: <hr />
                   4117: ENDPICK
1.597     wenzelju 4118:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4119:     return '';
1.26      albertel 4120: 
                   4121: }
                   4122: 
                   4123: sub csvupload_fields {
1.582     raeburn  4124:     my ($symb,$errorref) = @_;
                   4125:     my (@parts) = &getpartlist($symb,$errorref);
                   4126:     if (ref($errorref)) {
                   4127:         if ($$errorref) {
                   4128:             return;
                   4129:         }
                   4130:     }
                   4131: 
1.556     weissno  4132:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4133: 		['username','Student Username'],
                   4134: 		['domain','Student Domain']);
1.324     albertel 4135:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4136:     foreach my $part (sort(@parts)) {
                   4137: 	my @datum;
                   4138: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4139: 	my $name=$part;
                   4140: 	if  (!$display) { $display = $name; }
                   4141: 	@datum=($name,$display);
1.244     albertel 4142: 	if ($name=~/^stores_(.*)_awarded/) {
                   4143: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4144: 	}
1.41      ng       4145: 	push(@fields,\@datum);
                   4146:     }
                   4147:     return (@fields);
1.26      albertel 4148: }
                   4149: 
                   4150: sub csvuploadmap_footer {
1.41      ng       4151:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4152:     my $buttontext = &mt('Assign Grades');
1.41      ng       4153:     $request->print(<<ENDPICK);
1.26      albertel 4154: </table>
                   4155: <input type="hidden" name="nfields" value="$i" />
                   4156: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4157: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4158: </form>
                   4159: ENDPICK
                   4160: }
                   4161: 
1.283     albertel 4162: sub checkforfile_js {
1.638     www      4163:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4164:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4165:     function checkUpload(formname) {
                   4166: 	if (formname.upfile.value == "") {
1.539     riegler  4167: 	    alert("$alertmsg");
1.86      ng       4168: 	    return false;
                   4169: 	}
                   4170: 	formname.submit();
                   4171:     }
                   4172: CSVFORMJS
1.283     albertel 4173:     return $result;
                   4174: }
                   4175: 
                   4176: sub upcsvScores_form {
1.608     www      4177:     my ($request,$symb) = @_;
1.283     albertel 4178:     if (!$symb) {return '';}
                   4179:     my $result=&checkforfile_js();
1.632     www      4180:     $result.=&Apache::loncommon::start_data_table().
                   4181:              &Apache::loncommon::start_data_table_header_row().
                   4182:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4183:              &Apache::loncommon::end_data_table_header_row().
                   4184:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4185:     my $upload=&mt("Upload Scores");
1.86      ng       4186:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4187:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4188:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4189:     $result.=<<ENDUPFORM;
1.106     albertel 4190: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4191: <input type="hidden" name="symb" value="$symb" />
                   4192: <input type="hidden" name="command" value="csvuploadmap" />
                   4193: $upfile_select
1.589     bisitz   4194: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4195: </form>
                   4196: ENDUPFORM
1.370     www      4197:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4198:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4199:              '</td>'.
                   4200:             &Apache::loncommon::end_data_table_row().
                   4201:             &Apache::loncommon::end_data_table();
1.86      ng       4202:     return $result;
                   4203: }
                   4204: 
                   4205: 
1.26      albertel 4206: sub csvuploadmap {
1.608     www      4207:     my ($request,$symb)= @_;
1.41      ng       4208:     if (!$symb) {return '';}
1.72      ng       4209: 
1.41      ng       4210:     my $datatoken;
1.257     albertel 4211:     if (!$env{'form.datatoken'}) {
1.41      ng       4212: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4213:     } else {
1.257     albertel 4214: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4215: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4216:     }
1.41      ng       4217:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4218:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4219:     my ($i,$keyfields);
                   4220:     if (@records) {
1.582     raeburn  4221:         my $fieldserror;
                   4222: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4223:         if ($fieldserror) {
                   4224:             $request->print(&navmap_errormsg());
                   4225:             return;
                   4226:         }
1.257     albertel 4227: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4228: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4229: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4230: 							  \@fields);
                   4231: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4232: 	    chop($keyfields);
                   4233: 	} else {
                   4234: 	    unshift(@fields,['none','']);
                   4235: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4236: 							    \@fields);
1.311     banghart 4237:             foreach my $rec (@records) {
                   4238:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4239:                 if (%temp) {
                   4240:                     $keyfields=join(',',sort(keys(%temp)));
                   4241:                     last;
                   4242:                 }
                   4243:             }
1.41      ng       4244: 	}
                   4245:     }
                   4246:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4247: 
1.41      ng       4248:     return '';
1.27      albertel 4249: }
                   4250: 
1.246     albertel 4251: sub csvuploadoptions {
1.608     www      4252:     my ($request,$symb)= @_;
1.632     www      4253:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4254:     $request->print(<<ENDPICK);
                   4255: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4256: <input type="hidden" name="command"    value="csvuploadassign" />
                   4257: <p>
                   4258: <label>
                   4259:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4260:    $overwrite
1.246     albertel 4261: </label>
                   4262: </p>
                   4263: ENDPICK
                   4264:     my %fields=&get_fields();
                   4265:     if (!defined($fields{'domain'})) {
1.257     albertel 4266: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4267: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4268:     }
1.257     albertel 4269:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4270: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4271: 	my $cleankey=$1;
                   4272: 	if ($cleankey eq 'command') { next; }
                   4273: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4274: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4275:     }
                   4276:     # FIXME do a check for any duplicated user ids...
                   4277:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4278:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4279: <hr /></form>'."\n");
1.246     albertel 4280:     return '';
                   4281: }
                   4282: 
                   4283: sub get_fields {
                   4284:     my %fields;
1.257     albertel 4285:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4286:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4287: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4288: 	    if ($env{'form.f'.$i} ne 'none') {
                   4289: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4290: 	    }
                   4291: 	} else {
1.257     albertel 4292: 	    if ($env{'form.f'.$i} ne 'none') {
                   4293: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4294: 	    }
                   4295: 	}
1.27      albertel 4296:     }
1.246     albertel 4297:     return %fields;
                   4298: }
                   4299: 
                   4300: sub csvuploadassign {
1.608     www      4301:     my ($request,$symb)= @_;
1.246     albertel 4302:     if (!$symb) {return '';}
1.345     bowersj2 4303:     my $error_msg = '';
1.246     albertel 4304:     &Apache::loncommon::load_tmp_file($request);
                   4305:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4306:     my %fields=&get_fields();
1.257     albertel 4307:     my $courseid=$env{'request.course.id'};
1.97      albertel 4308:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4309:     my @notallowed;
1.41      ng       4310:     my @skipped;
1.657     raeburn  4311:     my @warnings;
1.41      ng       4312:     my $countdone=0;
                   4313:     foreach my $grade (@gradedata) {
                   4314: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4315: 	my $domain;
                   4316: 	if ($entries{$fields{'domain'}}) {
                   4317: 	    $domain=$entries{$fields{'domain'}};
                   4318: 	} else {
1.257     albertel 4319: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4320: 	}
1.243     albertel 4321: 	$domain=~s/\s//g;
1.41      ng       4322: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4323: 	$username=~s/\s//g;
1.243     albertel 4324: 	if (!$username) {
                   4325: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4326: 	    $id=~s/\s//g;
1.243     albertel 4327: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4328: 	    $username=$ids{$id};
                   4329: 	}
1.41      ng       4330: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4331: 	    my $id=$entries{$fields{'ID'}};
                   4332: 	    $id=~s/\s//g;
                   4333: 	    if ($id) {
                   4334: 		push(@skipped,"$id:$domain");
                   4335: 	    } else {
                   4336: 		push(@skipped,"$username:$domain");
                   4337: 	    }
1.41      ng       4338: 	    next;
                   4339: 	}
1.108     albertel 4340: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4341: 	if (!&canmodify($usec)) {
                   4342: 	    push(@notallowed,"$username:$domain");
                   4343: 	    next;
                   4344: 	}
1.244     albertel 4345: 	my %points;
1.41      ng       4346: 	my %grades;
                   4347: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4348: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4349: 		$dest eq 'domain') { next; }
                   4350: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4351: 	    if ($dest=~/stores_(.*)_points/) {
                   4352: 		my $part=$1;
                   4353: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4354: 					      $symb,$domain,$username);
1.345     bowersj2 4355:                 if ($wgt) {
                   4356:                     $entries{$fields{$dest}}=~s/\s//g;
                   4357:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4358:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4359:                                           : 'correct_by_override';
1.638     www      4360:                     if ($pcr>1) {
1.657     raeburn  4361:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4362:                     }
1.345     bowersj2 4363:                     $grades{"resource.$part.awarded"}=$pcr;
                   4364:                     $grades{"resource.$part.solved"}=$award;
                   4365:                     $points{$part}=1;
                   4366:                 } else {
                   4367:                     $error_msg = "<br />" .
                   4368:                         &mt("Some point values were assigned"
                   4369:                             ." for problems with a weight "
                   4370:                             ."of zero. These values were "
                   4371:                             ."ignored.");
                   4372:                 }
1.244     albertel 4373: 	    } else {
                   4374: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4375: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4376: 		my $store_key=$dest;
                   4377: 		$store_key=~s/^stores/resource/;
                   4378: 		$store_key=~s/_/\./g;
                   4379: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4380: 	    }
1.41      ng       4381: 	}
1.508     www      4382: 	if (! %grades) { 
                   4383:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4384:         } else {
                   4385: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4386: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4387: 					   $env{'request.course.id'},
                   4388: 					   $domain,$username);
1.508     www      4389: 	   if ($result eq 'ok') {
1.627     www      4390: # Successfully stored
1.508     www      4391: 	      $request->print('.');
1.627     www      4392: # Remove from grading queue
                   4393:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4394:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4395:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4396:                                              $domain,$username);
                   4397:               $countdone++;
                   4398:            } else {
1.508     www      4399: 	      $request->print("<p><span class=\"LC_error\">".
                   4400:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4401:                                   "$username:$domain",$result)."</span></p>");
                   4402: 	   }
                   4403: 	   $request->rflush();
                   4404:         }
1.41      ng       4405:     }
1.570     www      4406:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4407:     if (@warnings) {
                   4408:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4409:         $request->print(join(', ',@warnings));
                   4410:     }
1.41      ng       4411:     if (@skipped) {
1.571     www      4412: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4413:         $request->print(join(', ',@skipped));
1.106     albertel 4414:     }
                   4415:     if (@notallowed) {
1.571     www      4416: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4417: 	$request->print(join(', ',@notallowed));
1.41      ng       4418:     }
1.106     albertel 4419:     $request->print("<br />\n");
1.345     bowersj2 4420:     return $error_msg;
1.26      albertel 4421: }
1.44      ng       4422: #------------- end of section for handling csv file upload ---------
                   4423: #
                   4424: #-------------------------------------------------------------------
                   4425: #
1.122     ng       4426: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4427: #
                   4428: #--- Select a page/sequence and a student to grade
1.68      ng       4429: sub pickStudentPage {
1.608     www      4430:     my ($request,$symb) = @_;
1.68      ng       4431: 
1.539     riegler  4432:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4433:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4434: 
                   4435: function checkPickOne(formname) {
1.76      ng       4436:     if (radioSelection(formname.student) == null) {
1.539     riegler  4437: 	alert("$alertmsg");
1.68      ng       4438: 	return;
                   4439:     }
1.125     ng       4440:     ptr = pullDownSelection(formname.selectpage);
                   4441:     formname.page.value = formname["page"+ptr].value;
                   4442:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4443:     formname.submit();
                   4444: }
                   4445: 
                   4446: LISTJAVASCRIPT
1.118     ng       4447:     &commonJSfunctions($request);
1.608     www      4448: 
1.257     albertel 4449:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4450:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4451:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4452: 
1.398     albertel 4453:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4454: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4455: 
1.80      ng       4456:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4457:     my $map_error;
                   4458:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4459:     if ($map_error) {
                   4460:         $request->print(&navmap_errormsg());
                   4461:         return; 
                   4462:     }
1.137     albertel 4463:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4464: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4465: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4466: 
                   4467:     # Collection of hidden fields
1.70      ng       4468:     my $ctr=0;
1.68      ng       4469:     foreach (@$titles) {
1.700     bisitz   4470:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4471:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4472:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4473:         $ctr++;
1.68      ng       4474:     }
1.700     bisitz   4475:     $result.='<input type="hidden" name="page" />'."\n".
                   4476:         '<input type="hidden" name="title" />'."\n";
                   4477: 
                   4478:     $result.=&build_section_inputs();
                   4479:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4480:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4481: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4482: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4483: 
1.700     bisitz   4484:     # Show grading options
                   4485:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4486:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4487:     $ctr=0;
                   4488:     foreach (@$titles) {
                   4489: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4490: 	$select.='<option value="'.$ctr.'"'.
                   4491: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4492: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4493: 	$ctr++;
                   4494:     }
1.700     bisitz   4495:     $select.= '</select>';
1.68      ng       4496: 
1.700     bisitz   4497:     $result.=
                   4498:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4499:        .$select
                   4500:        .&Apache::lonhtmlcommon::row_closure();
                   4501: 
                   4502:     $result.=
                   4503:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4504:        .'<label><input type="radio" name="vProb" value="no"'
                   4505:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4506:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4507:            .&mt('yes').'</label>'."\n"
                   4508:        .&Apache::lonhtmlcommon::row_closure();
                   4509: 
                   4510:     $result.=
                   4511:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4512:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4513:            .&mt('none').' </label>'."\n"
                   4514:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4515:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4516:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4517:            .&mt('all submissions with details').' </label>'
                   4518:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4519:     
1.700     bisitz   4520:     $result.=
                   4521:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4522:        .'<input type="text" name="CODE" value="" />'
                   4523:        .&Apache::lonhtmlcommon::row_closure(1)
                   4524:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4525: 
1.700     bisitz   4526:     # Show list of students to select for grading
                   4527:     $result.='<br /><input type="button" '.
1.589     bisitz   4528:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4529: 
1.68      ng       4530:     $request->print($result);
                   4531: 
1.485     albertel 4532:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4533: 	&Apache::loncommon::start_data_table().
                   4534: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4535: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4536: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4537: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4538: 	'<th>'.&nameUserString('header').'</th>'.
                   4539: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4540:  
1.76      ng       4541:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4542:     my $ptr = 1;
1.294     albertel 4543:     foreach my $student (sort 
                   4544: 			 {
                   4545: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4546: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4547: 			     }
                   4548: 			     return $a cmp $b;
                   4549: 			 } (keys(%$fullname))) {
1.68      ng       4550: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4551: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4552:                                   : '</td>');
1.126     ng       4553: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4554: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4555: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4556: 	$studentTable.=
                   4557: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4558:                          : '');
1.68      ng       4559: 	$ptr++;
                   4560:     }
1.484     albertel 4561:     if ($ptr%2 == 0) {
                   4562: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4563: 	    &Apache::loncommon::end_data_table_row();
                   4564:     }
                   4565:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4566:     $studentTable.='<input type="button" '.
1.589     bisitz   4567:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4568: 
                   4569:     $request->print($studentTable);
                   4570: 
                   4571:     return '';
                   4572: }
                   4573: 
                   4574: sub getSymbMap {
1.582     raeburn  4575:     my ($map_error) = @_;
1.132     bowersj2 4576:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4577:     unless (ref($navmap)) {
                   4578:         if (ref($map_error)) {
                   4579:             $$map_error = 'navmap';
                   4580:         }
                   4581:         return;
                   4582:     }
1.68      ng       4583:     my %symbx = ();
                   4584:     my @titles = ();
1.117     bowersj2 4585:     my $minder = 0;
                   4586: 
                   4587:     # Gather every sequence that has problems.
1.240     albertel 4588:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4589: 					       1,0,1);
1.117     bowersj2 4590:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4591: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4592: 	    my $title = $minder.'.'.
                   4593: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4594: 	    push(@titles, $title); # minder in case two titles are identical
                   4595: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4596: 	    $minder++;
1.241     albertel 4597: 	}
1.68      ng       4598:     }
                   4599:     return \@titles,\%symbx;
                   4600: }
                   4601: 
1.72      ng       4602: #
                   4603: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4604: sub displayPage {
1.608     www      4605:     my ($request,$symb) = @_;
1.257     albertel 4606:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4607:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4608:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4609:     my $pageTitle = $env{'form.page'};
1.103     albertel 4610:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4611:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4612:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4613: 
                   4614:     #need to make sure we have the correct data for later EXT calls, 
                   4615:     #thus invalidate the cache
                   4616:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4617:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4618:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4619:     &Apache::lonnet::clear_EXT_cache_status();
                   4620: 
1.103     albertel 4621:     if (!&canview($usec)) {
1.712     bisitz   4622:         $request->print(
                   4623:             '<span class="LC_warning">'.
                   4624:             &mt('Unable to view requested student. ([_1])',
                   4625:                     $env{'form.student'}).
                   4626:             '</span>');
                   4627:         return;
1.103     albertel 4628:     }
1.398     albertel 4629:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4630:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4631: 	'</h3>'."\n";
1.500     albertel 4632:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4633:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4634: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4635:     } else {
                   4636: 	delete($env{'form.CODE'});
                   4637:     }
1.71      ng       4638:     &sub_page_js($request);
                   4639:     $request->print($result);
                   4640: 
1.132     bowersj2 4641:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4642:     unless (ref($navmap)) {
                   4643:         $request->print(&navmap_errormsg());
                   4644:         return;
                   4645:     }
1.257     albertel 4646:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4647:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4648:     if (!$map) {
1.485     albertel 4649: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4650: 	return; 
                   4651:     }
1.68      ng       4652:     my $iterator = $navmap->getIterator($map->map_start(),
                   4653: 					$map->map_finish());
                   4654: 
1.71      ng       4655:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4656: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4657: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4658: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4659: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4660: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4661: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4662: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4663: 
1.382     albertel 4664:     if (defined($env{'form.CODE'})) {
                   4665: 	$studentTable.=
                   4666: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4667:     }
1.381     albertel 4668:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4669: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4670: 
1.594     bisitz   4671:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4672:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4673:         '</span>'."\n".
1.484     albertel 4674: 	&Apache::loncommon::start_data_table().
                   4675: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4676: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4677: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4678: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4679: 
1.329     albertel 4680:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4681:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4682:     $iterator->next(); # skip the first BEGIN_MAP
                   4683:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4684:     while ($depth > 0) {
1.68      ng       4685:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4686:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4687: 
1.385     albertel 4688:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4689: 	    my $parts = $curRes->parts();
1.68      ng       4690:             my $title = $curRes->compTitle();
1.71      ng       4691: 	    my $symbx = $curRes->symb();
1.484     albertel 4692: 	    $studentTable.=
                   4693: 		&Apache::loncommon::start_data_table_row().
                   4694: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4695: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4696: 		                        : '<br />('.&mt('[_1]parts',
                   4697: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4698: 		 ).
                   4699: 		 '</td>';
1.71      ng       4700: 	    $studentTable.='<td valign="top">';
1.382     albertel 4701: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4702: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4703: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4704: 					     undef,'both',\%form);
1.71      ng       4705: 	    } else {
1.382     albertel 4706: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4707: 		$companswer =~ s|<form(.*?)>||g;
                   4708: 		$companswer =~ s|</form>||g;
1.71      ng       4709: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4710: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4711: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4712: #		}
1.116     ng       4713: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4714: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4715: 	    }
                   4716: 
1.257     albertel 4717: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4718: 
1.257     albertel 4719: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4720: 		if ($record{'version'} eq '') {
1.485     albertel 4721: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4722: 		} else {
1.116     ng       4723: 		    my %responseType = ();
                   4724: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4725: 			my @responseIds =$curRes->responseIds($partid);
                   4726: 			my @responseType =$curRes->responseType($partid);
                   4727: 			my %responseIds;
                   4728: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4729: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4730: 			}
                   4731: 			$responseType{$partid} = \%responseIds;
1.116     ng       4732: 		    }
1.148     albertel 4733: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4734: 
1.71      ng       4735: 		}
1.257     albertel 4736: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4737: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4738: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4739: 									$env{'request.course.id'},
1.71      ng       4740: 									'','.submission');
                   4741:  
                   4742: 	    }
1.103     albertel 4743: 	    if (&canmodify($usec)) {
1.585     bisitz   4744:             $studentTable.=&gradeBox_start();
1.103     albertel 4745: 		foreach my $partid (@{$parts}) {
                   4746: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4747: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4748: 		    $question++;
                   4749: 		}
1.585     bisitz   4750:             $studentTable.=&gradeBox_end();
1.196     albertel 4751: 		$prob++;
1.71      ng       4752: 	    }
                   4753: 	    $studentTable.='</td></tr>';
1.68      ng       4754: 
1.103     albertel 4755: 	}
1.68      ng       4756:         $curRes = $iterator->next();
                   4757:     }
                   4758: 
1.589     bisitz   4759:     $studentTable.=
                   4760:         '</table>'."\n".
                   4761:         '<input type="button" value="'.&mt('Save').'" '.
                   4762:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4763:         '</form>'."\n";
1.71      ng       4764:     $request->print($studentTable);
                   4765: 
                   4766:     return '';
1.119     ng       4767: }
                   4768: 
                   4769: sub displaySubByDates {
1.148     albertel 4770:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4771:     my $isCODE=0;
1.335     albertel 4772:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4773:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4774:     my $studentTable=&Apache::loncommon::start_data_table().
                   4775: 	&Apache::loncommon::start_data_table_header_row().
                   4776: 	'<th>'.&mt('Date/Time').'</th>'.
                   4777: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4778:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4779: 	'<th>'.&mt('Submission').'</th>'.
                   4780: 	'<th>'.&mt('Status').'</th>'.
                   4781: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4782:     my ($version);
                   4783:     my %mark;
1.148     albertel 4784:     my %orders;
1.119     ng       4785:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4786:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4787: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4788:     }
1.335     albertel 4789: 
                   4790:     my $interaction;
1.525     raeburn  4791:     my $no_increment = 1;
1.640     raeburn  4792:     my %lastrndseed;
1.119     ng       4793:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4794: 	my $timestamp = 
                   4795: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4796: 	if (exists($$record{$version.':resource.0.version'})) {
                   4797: 	    $interaction = $$record{$version.':resource.0.version'};
                   4798: 	}
1.671     raeburn  4799:         if ($isTask && $env{'form.previousversion'}) {
                   4800:             next unless ($interaction == $env{'form.previousversion'});
                   4801:         }
1.335     albertel 4802: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4803: 		             : "$version:resource");
1.467     albertel 4804: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4805: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4806: 	if ($isCODE) {
                   4807: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4808: 	}
1.671     raeburn  4809:         if ($isTask) {
                   4810:             $studentTable.='<td>'.$interaction.'</td>';
                   4811:         }
1.119     ng       4812: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4813: 	my @displaySub = ();
                   4814: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4815:             my ($hidden,$type);
                   4816:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4817:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4818:                 $hidden = 1;
                   4819:             }
1.335     albertel 4820: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4821: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4822: 	    
1.122     ng       4823: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4824: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4825: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4826: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4827: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4828:                     
1.335     albertel 4829: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4830: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4831:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4832:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4833:                                    .' <span class="LC_internal_info">'
1.625     www      4834:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4835:                                    .'</span>'
                   4836:                                    .' <b>';
1.596     raeburn  4837:                     if ($hidden) {
                   4838:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4839:                     } else {
1.640     raeburn  4840:                         my ($trial,$rndseed,$newvariation);
                   4841:                         if ($type eq 'randomizetry') {
                   4842:                             $trial = $$record{"$where.$partid.tries"};
                   4843:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4844:                         }
1.596     raeburn  4845: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4846: 			    $displaySub[0].=&mt('Trial not counted');
                   4847: 		        } else {
                   4848: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4849: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4850:                             if ($rndseed || $lastrndseed{$partid}) {
                   4851:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4852:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4853:                                 }
                   4854:                             }
                   4855:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4856: 		        }
                   4857: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4858:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4859: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4860: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4861: 			    $orders{$partid}->{$responseId}=
                   4862: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4863:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4864: 		        }
1.640     raeburn  4865: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4866: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4867: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4868:                     }
1.147     albertel 4869: 		}
                   4870: 	    }
1.335     albertel 4871: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4872: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4873: 				    $$record{"$where.$partid.checkedin"},
                   4874: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4875: 					'<br />';
1.335     albertel 4876: 	    }
                   4877: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4878: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4879: 		    lc($$record{"$where.$partid.award"}).' '.
                   4880: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4881: 		    '<br />';
                   4882: 	    }
1.335     albertel 4883: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4884: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4885: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4886: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4887: 		$displaySub[2].=
                   4888: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4889: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4890: 	    }
                   4891: 	}
                   4892: 	# needed because old essay regrader has not parts info
                   4893: 	if (exists $$record{"$version:resource.regrader"}) {
                   4894: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4895: 	}
                   4896: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4897: 	if ($displaySub[2]) {
1.467     albertel 4898: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4899: 	}
1.467     albertel 4900: 	$studentTable.='&nbsp;</td>'.
                   4901: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4902:     }
1.467     albertel 4903:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4904:     return $studentTable;
1.71      ng       4905: }
                   4906: 
                   4907: sub updateGradeByPage {
1.608     www      4908:     my ($request,$symb) = @_;
1.71      ng       4909: 
1.257     albertel 4910:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4911:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4912:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4913:     my $pageTitle = $env{'form.page'};
1.103     albertel 4914:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4915:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4916:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4917:     if (!&canmodify($usec)) {
1.526     raeburn  4918: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4919: 	return;
                   4920:     }
1.398     albertel 4921:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4922:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4923: 	'</h3>'."\n";
1.70      ng       4924: 
1.68      ng       4925:     $request->print($result);
                   4926: 
1.582     raeburn  4927: 
1.132     bowersj2 4928:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4929:     unless (ref($navmap)) {
                   4930:         $request->print(&navmap_errormsg());
                   4931:         return;
                   4932:     }
1.257     albertel 4933:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4934:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4935:     if (!$map) {
1.527     raeburn  4936: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4937: 	return; 
                   4938:     }
1.71      ng       4939:     my $iterator = $navmap->getIterator($map->map_start(),
                   4940: 					$map->map_finish());
1.70      ng       4941: 
1.484     albertel 4942:     my $studentTable=
                   4943: 	&Apache::loncommon::start_data_table().
                   4944: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4945: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4946: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4947: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4948: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4949: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4950: 
                   4951:     $iterator->next(); # skip the first BEGIN_MAP
                   4952:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4953:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4954:     while ($depth > 0) {
1.71      ng       4955:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4956:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4957: 
1.385     albertel 4958:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4959: 	    my $parts = $curRes->parts();
1.71      ng       4960:             my $title = $curRes->compTitle();
                   4961: 	    my $symbx = $curRes->symb();
1.484     albertel 4962: 	    $studentTable.=
                   4963: 		&Apache::loncommon::start_data_table_row().
                   4964: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4965: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4966:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4967: 		.')').'</td>';
1.71      ng       4968: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4969: 
                   4970: 	    my %newrecord=();
                   4971: 	    my @displayPts=();
1.269     raeburn  4972:             my %aggregate = ();
                   4973:             my $aggregateflag = 0;
1.71      ng       4974: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4975: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4976: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4977: 
1.257     albertel 4978: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4979: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4980: 		my $partial = $newpts/$wgt;
                   4981: 		my $score;
                   4982: 		if ($partial > 0) {
                   4983: 		    $score = 'correct_by_override';
1.125     ng       4984: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4985: 		    $score = 'incorrect_by_override';
                   4986: 		}
1.257     albertel 4987: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4988: 		if ($dropMenu eq 'excused') {
1.71      ng       4989: 		    $partial = '';
                   4990: 		    $score = 'excused';
1.125     ng       4991: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4992: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4993: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4994: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4995: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4996: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4997: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4998: 		    $changeflag++;
                   4999: 		    $newpts = '';
1.269     raeburn  5000:                     
                   5001:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5002:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5003:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5004:                     if ($aggtries > 0) {
                   5005:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5006:                         $aggregateflag = 1;
                   5007:                     }
1.71      ng       5008: 		}
1.324     albertel 5009: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5010: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5011: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5012: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5013: 		    '&nbsp;<br />';
1.526     raeburn  5014: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5015: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5016: 		    '&nbsp;<br />';
1.71      ng       5017: 		$question++;
1.380     albertel 5018: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5019: 
1.71      ng       5020: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5021: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5022: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5023: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5024: 
                   5025: 		$changeflag++;
                   5026: 	    }
                   5027: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5028: 		my %record = 
                   5029: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5030: 					     $udom,$uname);
                   5031: 
                   5032: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5033: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5034: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5035: 		    $newrecord{'resource.CODE'} = '';
                   5036: 		}
1.257     albertel 5037: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5038: 					$udom,$uname);
1.382     albertel 5039: 		%record = &Apache::lonnet::restore($symbx,
                   5040: 						   $env{'request.course.id'},
                   5041: 						   $udom,$uname);
1.380     albertel 5042: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5043: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5044: 	    }
1.380     albertel 5045: 	    
1.269     raeburn  5046:             if ($aggregateflag) {
                   5047:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5048:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5049:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5050:             }
1.125     ng       5051: 
1.71      ng       5052: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5053: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5054: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5055: 
1.196     albertel 5056: 	    $prob++;
1.68      ng       5057: 	}
1.71      ng       5058:         $curRes = $iterator->next();
1.68      ng       5059:     }
1.98      albertel 5060: 
1.484     albertel 5061:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5062:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5063: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5064: 		  $changeflag));
1.76      ng       5065:     $request->print($grademsg.$studentTable);
1.68      ng       5066: 
1.70      ng       5067:     return '';
                   5068: }
                   5069: 
1.72      ng       5070: #-------- end of section for handling grading by page/sequence ---------
                   5071: #
                   5072: #-------------------------------------------------------------------
                   5073: 
1.581     www      5074: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5075: #
                   5076: #------ start of section for handling grading by page/sequence ---------
                   5077: 
1.423     albertel 5078: =pod
                   5079: 
                   5080: =head1 Bubble sheet grading routines
                   5081: 
1.424     albertel 5082:   For this documentation:
                   5083: 
                   5084:    'scanline' refers to the full line of characters
                   5085:    from the file that we are parsing that represents one entire sheet
                   5086: 
                   5087:    'bubble line' refers to the data
1.659     raeburn  5088:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5089: 
                   5090: 
1.659     raeburn  5091: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5092: into a course. When a user wants to grade, they select a
1.659     raeburn  5093: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5094: one of the predefined configurations for what each scanline looks
                   5095: like.
                   5096: 
                   5097: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5098: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5099: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5100: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5101: invalid student/employee ID
1.424     albertel 5102: 
                   5103: If the CODE option is used that determines the randomization of the
1.556     weissno  5104: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5105: username:domain.
                   5106: 
                   5107: During the validation phase the instructor can choose to skip scanlines. 
                   5108: 
1.659     raeburn  5109: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5110: 
                   5111:   scantron_original_filename (unmodified original file)
                   5112:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5113:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5114: 
                   5115: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5116: correction information that isn't representable in the bubblesheet
1.424     albertel 5117: file (see &scantron_getfile() for more information)
                   5118: 
                   5119: After all scanlines are either valid, marked as valid or skipped, then
                   5120: foreach line foreach problem in the picked sequence, an ssi request is
                   5121: made that simulates a user submitting their selected letter(s) against
                   5122: the homework problem.
1.423     albertel 5123: 
                   5124: =over 4
                   5125: 
                   5126: 
                   5127: 
                   5128: =item defaultFormData
                   5129: 
                   5130:   Returns html hidden inputs used to hold context/default values.
                   5131: 
                   5132:  Arguments:
                   5133:   $symb - $symb of the current resource 
                   5134: 
                   5135: =cut
1.422     foxr     5136: 
1.81      albertel 5137: sub defaultFormData {
1.324     albertel 5138:     my ($symb)=@_;
1.613     www      5139:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5140: }
                   5141: 
1.447     foxr     5142: 
1.423     albertel 5143: =pod 
                   5144: 
                   5145: =item getSequenceDropDown
                   5146: 
                   5147:    Return html dropdown of possible sequences to grade
                   5148:  
                   5149:  Arguments:
1.582     raeburn  5150:    $symb - $symb of the current resource
                   5151:    $map_error - ref to scalar which will container error if
                   5152:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5153: 
                   5154: =cut
1.422     foxr     5155: 
1.75      albertel 5156: sub getSequenceDropDown {
1.582     raeburn  5157:     my ($symb,$map_error)=@_;
1.75      albertel 5158:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5159:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5160:     if (ref($map_error)) {
                   5161:         return if ($$map_error);
                   5162:     }
1.137     albertel 5163:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5164:     my $ctr=0;
                   5165:     foreach (@$titles) {
                   5166: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5167: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5168: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5169: 	    '>'.$showtitle.'</option>'."\n";
                   5170: 	$ctr++;
                   5171:     }
                   5172:     $result.= '</select>';
                   5173:     return $result;
                   5174: }
                   5175: 
1.495     albertel 5176: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5177:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5178: 
                   5179: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5180: 
1.509     raeburn  5181: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5182:                                    # matchresponse or rankresponse, where 
                   5183:                                    # an individual response can have multiple 
                   5184:                                    # lines
1.503     raeburn  5185: 
                   5186: my %responsetype_per_response;     # responsetype for each response
                   5187: 
1.691     raeburn  5188: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5189:                                    # numbered response. Needed when randomorder
                   5190:                                    # or randompick are in use. Key is ID, value 
                   5191:                                    # is response number.
                   5192: 
1.495     albertel 5193: # Save and restore the bubble lines array to the form env.
                   5194: 
                   5195: 
                   5196: sub save_bubble_lines {
                   5197:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5198: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5199: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5200: 	    $first_bubble_line{$line};
1.503     raeburn  5201:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5202:             $subdivided_bubble_lines{$line};
                   5203:         $env{"form.scantron.responsetype.$line"} =
                   5204:             $responsetype_per_response{$line};
1.495     albertel 5205:     }
1.691     raeburn  5206:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5207:         my $line = $masterseq_id_responsenum{$resid};
                   5208:         $env{"form.scantron.residpart.$line"} = $resid;
                   5209:     }
1.495     albertel 5210: }
                   5211: 
                   5212: 
                   5213: sub restore_bubble_lines {
                   5214:     my $line = 0;
                   5215:     %bubble_lines_per_response = ();
1.691     raeburn  5216:     %masterseq_id_responsenum = ();
1.495     albertel 5217:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5218: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5219: 	$bubble_lines_per_response{$line} = $value;
                   5220: 	$first_bubble_line{$line}  =
                   5221: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5222:         $subdivided_bubble_lines{$line} =
                   5223:             $env{"form.scantron.sub_bubblelines.$line"};
                   5224:         $responsetype_per_response{$line} =
                   5225:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5226:         my $id = $env{"form.scantron.residpart.$line"};
                   5227:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5228: 	$line++;
                   5229:     }
                   5230: }
                   5231: 
1.423     albertel 5232: =pod 
                   5233: 
                   5234: =item scantron_filenames
                   5235: 
                   5236:    Returns a list of the scantron files in the current course 
                   5237: 
                   5238: =cut
1.422     foxr     5239: 
1.202     albertel 5240: sub scantron_filenames {
1.257     albertel 5241:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5242:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5243:     my $getpropath = 1;
1.662     raeburn  5244:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5245:                                                         $cname,$getpropath);
1.202     albertel 5246:     my @possiblenames;
1.662     raeburn  5247:     if (ref($dirlist) eq 'ARRAY') {
                   5248:         foreach my $filename (sort(@{$dirlist})) {
                   5249: 	    ($filename)=split(/&/,$filename);
                   5250: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5251: 	    $filename=~s/^scantron_orig_//;
                   5252: 	    push(@possiblenames,$filename);
                   5253:         }
1.202     albertel 5254:     }
                   5255:     return @possiblenames;
                   5256: }
                   5257: 
1.423     albertel 5258: =pod 
                   5259: 
                   5260: =item scantron_uploads
                   5261: 
                   5262:    Returns  html drop-down list of scantron files in current course.
                   5263: 
                   5264:  Arguments:
                   5265:    $file2grade - filename to set as selected in the dropdown
                   5266: 
                   5267: =cut
1.422     foxr     5268: 
1.202     albertel 5269: sub scantron_uploads {
1.209     ng       5270:     my ($file2grade) = @_;
1.202     albertel 5271:     my $result=	'<select name="scantron_selectfile">';
                   5272:     $result.="<option></option>";
                   5273:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5274: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5275:     }
                   5276:     $result.="</select>";
                   5277:     return $result;
                   5278: }
                   5279: 
1.423     albertel 5280: =pod 
                   5281: 
                   5282: =item scantron_scantab
                   5283: 
                   5284:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5285:   file.
                   5286: 
                   5287: =cut
1.422     foxr     5288: 
1.82      albertel 5289: sub scantron_scantab {
                   5290:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5291:     $result.='<option></option>'."\n";
1.518     raeburn  5292:     my @lines = &get_scantronformat_file();
                   5293:     if (@lines > 0) {
                   5294:         foreach my $line (@lines) {
                   5295:             next if (($line =~ /^\#/) || ($line eq ''));
                   5296: 	    my ($name,$descrip)=split(/:/,$line);
                   5297: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5298:         }
1.82      albertel 5299:     }
                   5300:     $result.='</select>'."\n";
1.518     raeburn  5301:     return $result;
                   5302: }
                   5303: 
                   5304: =pod
                   5305: 
                   5306: =item get_scantronformat_file
                   5307: 
                   5308:   Returns an array containing lines from the scantron format file for
                   5309:   the domain of the course.
                   5310: 
                   5311:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5312:   lines are from this file.
                   5313: 
                   5314:   Otherwise, if a default.tab has been published in RES space by the 
                   5315:   domainconfig user, lines are from this file.
                   5316: 
                   5317:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5318:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5319: 
1.518     raeburn  5320: =cut
                   5321: 
                   5322: sub get_scantronformat_file {
                   5323:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5324:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5325:     my $gottab = 0;
                   5326:     my @lines;
                   5327:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5328:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5329:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5330:             if ($formatfile ne '-1') {
                   5331:                 @lines = split("\n",$formatfile,-1);
                   5332:                 $gottab = 1;
                   5333:             }
                   5334:         }
                   5335:     }
                   5336:     if (!$gottab) {
                   5337:         my $confname = $cdom.'-domainconfig';
                   5338:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5339:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5340:         if ($formatfile ne '-1') {
                   5341:             @lines = split("\n",$formatfile,-1);
                   5342:             $gottab = 1;
                   5343:         }
                   5344:     }
                   5345:     if (!$gottab) {
1.519     raeburn  5346:         my @domains = &Apache::lonnet::current_machine_domains();
                   5347:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5348:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5349:             @lines = <$fh>;
                   5350:             close($fh);
                   5351:         } else {
                   5352:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5353:             @lines = <$fh>;
                   5354:             close($fh);
                   5355:         }
1.518     raeburn  5356:     }
                   5357:     return @lines;
1.82      albertel 5358: }
                   5359: 
1.423     albertel 5360: =pod 
                   5361: 
                   5362: =item scantron_CODElist
                   5363: 
                   5364:   Returns html drop down of the saved CODE lists from current course,
                   5365:   generated from earlier printings.
                   5366: 
                   5367: =cut
1.422     foxr     5368: 
1.186     albertel 5369: sub scantron_CODElist {
1.257     albertel 5370:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5371:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5372:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5373:     my $namechoice='<option></option>';
1.225     albertel 5374:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5375: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5376: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5377: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5378:     }
                   5379:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5380:     return $namechoice;
                   5381: }
                   5382: 
1.423     albertel 5383: =pod 
                   5384: 
                   5385: =item scantron_CODEunique
                   5386: 
                   5387:   Returns the html for "Each CODE to be used once" radio.
                   5388: 
                   5389: =cut
1.422     foxr     5390: 
1.186     albertel 5391: sub scantron_CODEunique {
1.532     bisitz   5392:     my $result='<span class="LC_nobreak">
1.272     albertel 5393:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5394:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5395:                 </span>
1.532     bisitz   5396:                 <span class="LC_nobreak">
1.272     albertel 5397:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5398:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5399:                 </span>';
1.186     albertel 5400:     return $result;
                   5401: }
1.423     albertel 5402: 
                   5403: =pod 
                   5404: 
                   5405: =item scantron_selectphase
                   5406: 
1.659     raeburn  5407:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5408:   Allows for - starting a grading run.
1.424     albertel 5409:              - downloading existing scan data (original, corrected
1.423     albertel 5410:                                                 or skipped info)
                   5411: 
                   5412:              - uploading new scan data
                   5413: 
                   5414:  Arguments:
                   5415:   $r          - The Apache request object
                   5416:   $file2grade - name of the file that contain the scanned data to score
                   5417: 
                   5418: =cut
1.186     albertel 5419: 
1.75      albertel 5420: sub scantron_selectphase {
1.608     www      5421:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5422:     if (!$symb) {return '';}
1.582     raeburn  5423:     my $map_error;
                   5424:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5425:     if ($map_error) {
                   5426:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5427:         return;
                   5428:     }
1.324     albertel 5429:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5430:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5431:     my $format_selector=&scantron_scantab();
1.186     albertel 5432:     my $CODE_selector=&scantron_CODElist();
                   5433:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5434:     my $result;
1.422     foxr     5435: 
1.513     foxr     5436:     $ssi_error = 0;
                   5437: 
1.606     wenzelju 5438:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5439:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5440: 
                   5441: 	# Chunk of form to prompt for a scantron file upload.
                   5442: 
                   5443:         $r->print('
                   5444:     <br />
                   5445:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5446:        '.&Apache::loncommon::start_data_table_header_row().'
                   5447:             <th>
                   5448:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5449:             </th>
                   5450:        '.&Apache::loncommon::end_data_table_header_row().'
                   5451:        '.&Apache::loncommon::start_data_table_row().'
                   5452:             <td>
                   5453: ');
1.608     www      5454:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5455:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5456:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5457:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5458:     function checkUpload(formname) {
                   5459: 	if (formname.upfile.value == "") {
                   5460: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5461: 	    return false;
                   5462: 	}
                   5463: 	formname.submit();
                   5464:     }'));
                   5465:     $r->print('
                   5466:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5467:                 '.$default_form_data.'
                   5468:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5469:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5470:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5471:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5472:                 <br />
                   5473:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5474:               </form>
                   5475: ');
                   5476: 
                   5477:         $r->print('
                   5478:             </td>
                   5479:        '.&Apache::loncommon::end_data_table_row().'
                   5480:        '.&Apache::loncommon::end_data_table().'
                   5481: ');
                   5482:     }
                   5483: 
1.422     foxr     5484:     # Chunk of form to prompt for a file to grade and how:
                   5485: 
1.489     albertel 5486:     $result.= '
                   5487:     <br />
                   5488:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5489:     <input type="hidden" name="command" value="scantron_warning" />
                   5490:     '.$default_form_data.'
                   5491:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5492:        '.&Apache::loncommon::start_data_table_header_row().'
                   5493:             <th colspan="2">
1.492     albertel 5494:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5495:             </th>
                   5496:        '.&Apache::loncommon::end_data_table_header_row().'
                   5497:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5498:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5499:        '.&Apache::loncommon::end_data_table_row().'
                   5500:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5501:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5502:        '.&Apache::loncommon::end_data_table_row().'
                   5503:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5504:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5505:        '.&Apache::loncommon::end_data_table_row().'
                   5506:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5507:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5508:        '.&Apache::loncommon::end_data_table_row().'
                   5509:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5510:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5511:        '.&Apache::loncommon::end_data_table_row().'
                   5512:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5513: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5514:             <td>
1.492     albertel 5515: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5516:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5517:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5518: 	    </td>
1.489     albertel 5519:        '.&Apache::loncommon::end_data_table_row().'
                   5520:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5521:             <td colspan="2">
1.572     www      5522:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5523:             </td>
1.489     albertel 5524:        '.&Apache::loncommon::end_data_table_row().'
                   5525:     '.&Apache::loncommon::end_data_table().'
                   5526:     </form>
                   5527: ';
1.162     albertel 5528:    
                   5529:     $r->print($result);
                   5530: 
1.422     foxr     5531: 
                   5532: 
                   5533:     # Chunk of the form that prompts to view a scoring office file,
                   5534:     # corrected file, skipped records in a file.
                   5535: 
1.489     albertel 5536:     $r->print('
                   5537:    <br />
                   5538:    <form action="/adm/grades" name="scantron_download">
                   5539:      '.$default_form_data.'
                   5540:      <input type="hidden" name="command" value="scantron_download" />
                   5541:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5542:        '.&Apache::loncommon::start_data_table_header_row().'
                   5543:               <th>
1.492     albertel 5544:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5545:               </th>
                   5546:        '.&Apache::loncommon::end_data_table_header_row().'
                   5547:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5548:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5549:                 <br />
1.492     albertel 5550:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5551:        '.&Apache::loncommon::end_data_table_row().'
                   5552:      '.&Apache::loncommon::end_data_table().'
                   5553:    </form>
                   5554:    <br />
                   5555: ');
1.162     albertel 5556: 
1.457     banghart 5557:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5558: 
1.694     bisitz   5559:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5560:              $default_form_data."\n".
                   5561:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5562:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5563:              '<th colspan="2">
1.572     www      5564:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5565:              '</th>'."\n".
                   5566:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5567:               &Apache::loncommon::start_data_table_row()."\n".
                   5568:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5569:               '<td> '.$sequence_selector.' </td>'.
                   5570:               &Apache::loncommon::end_data_table_row()."\n".
                   5571:               &Apache::loncommon::start_data_table_row()."\n".
                   5572:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5573:               '<td> '.$file_selector.' </td>'."\n".
                   5574:               &Apache::loncommon::end_data_table_row()."\n".
                   5575:               &Apache::loncommon::start_data_table_row()."\n".
                   5576:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5577:               '<td> '.$format_selector.' </td>'."\n".
                   5578:               &Apache::loncommon::end_data_table_row()."\n".
                   5579:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5580:               '<td> '.&mt('Options').' </td>'."\n".
                   5581:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5582:               &Apache::loncommon::end_data_table_row()."\n".
                   5583:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5584:               '<td colspan="2">'."\n".
                   5585:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5586:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5587:               '</td>'."\n".
                   5588:               &Apache::loncommon::end_data_table_row()."\n".
                   5589:               &Apache::loncommon::end_data_table()."\n".
                   5590:               '</form><br />');
                   5591:     return;
1.75      albertel 5592: }
                   5593: 
1.423     albertel 5594: =pod
                   5595: 
                   5596: =item get_scantron_config
                   5597: 
1.711     bisitz   5598:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5599:    hash of configuration file fields.
                   5600: 
                   5601:  Arguments:
                   5602:     which - the name of the configuration to parse from the file.
                   5603: 
                   5604: 
                   5605:  Returns:
                   5606:             If the named configuration is not in the file, an empty
                   5607:             hash is returned.
                   5608:     a hash with the fields
                   5609:       name         - internal name for the this configuration setup
                   5610:       description  - text to display to operator that describes this config
                   5611:       CODElocation - if 0 or the string 'none'
                   5612:                           - no CODE exists for this config
                   5613:                      if -1 || the string 'letter'
                   5614:                           - a CODE exists for this config and is
                   5615:                             a string of letters
                   5616:                      Unsupported value (but planned for future support)
                   5617:                           if a positive integer
                   5618:                                - The CODE exists as the first n items from
                   5619:                                  the question section of the form
                   5620:                           if the string 'number'
                   5621:                                - The CODE exists for this config and is
                   5622:                                  a string of numbers
                   5623:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5624:                      the CODE starts
                   5625:       CODElength  - length of the CODE
1.573     bisitz   5626:       IDstart     - column where the student/employee ID starts
1.556     weissno  5627:       IDlength    - length of the student/employee ID info
1.423     albertel 5628:       Qstart      - column where the information from the bubbled
                   5629:                     'questions' start
                   5630:       Qlength     - number of columns comprising a single bubble line from
                   5631:                     the sheet. (usually either 1 or 10)
1.424     albertel 5632:       Qon         - either a single character representing the character used
1.423     albertel 5633:                     to signal a bubble was chosen in the positional setup, or
                   5634:                     the string 'letter' if the letter of the chosen bubble is
                   5635:                     in the final, or 'number' if a number representing the
                   5636:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5637:       Qoff        - the character used to represent that a bubble was
                   5638:                     left blank
1.423     albertel 5639:       PaperID     - if the scanning process generates a unique number for each
                   5640:                     sheet scanned the column that this ID number starts in
                   5641:       PaperIDlength - number of columns that comprise the unique ID number
                   5642:                       for the sheet of paper
1.424     albertel 5643:       FirstName   - column that the first name starts in
1.423     albertel 5644:       FirstNameLength - number of columns that the first name spans
                   5645:  
                   5646:       LastName    - column that the last name starts in
                   5647:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5648:       BubblesPerRow - number of bubbles available in each row used to 
                   5649:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5650: 
1.423     albertel 5651: =cut
1.422     foxr     5652: 
1.82      albertel 5653: sub get_scantron_config {
                   5654:     my ($which) = @_;
1.518     raeburn  5655:     my @lines = &get_scantronformat_file();
1.82      albertel 5656:     my %config;
1.157     albertel 5657:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5658:     foreach my $line (@lines) {
1.82      albertel 5659: 	my ($name,$descrip)=split(/:/,$line);
                   5660: 	if ($name ne $which ) { next; }
                   5661: 	chomp($line);
                   5662: 	my @config=split(/:/,$line);
                   5663: 	$config{'name'}=$config[0];
                   5664: 	$config{'description'}=$config[1];
                   5665: 	$config{'CODElocation'}=$config[2];
                   5666: 	$config{'CODEstart'}=$config[3];
                   5667: 	$config{'CODElength'}=$config[4];
                   5668: 	$config{'IDstart'}=$config[5];
                   5669: 	$config{'IDlength'}=$config[6];
                   5670: 	$config{'Qstart'}=$config[7];
1.497     foxr     5671:  	$config{'Qlength'}=$config[8];
1.82      albertel 5672: 	$config{'Qoff'}=$config[9];
                   5673: 	$config{'Qon'}=$config[10];
1.157     albertel 5674: 	$config{'PaperID'}=$config[11];
                   5675: 	$config{'PaperIDlength'}=$config[12];
                   5676: 	$config{'FirstName'}=$config[13];
                   5677: 	$config{'FirstNamelength'}=$config[14];
                   5678: 	$config{'LastName'}=$config[15];
                   5679: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5680:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5681: 	last;
                   5682:     }
                   5683:     return %config;
                   5684: }
                   5685: 
1.423     albertel 5686: =pod 
                   5687: 
                   5688: =item username_to_idmap
                   5689: 
1.556     weissno  5690:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5691:     student username:domain.
                   5692: 
                   5693:   Arguments:
                   5694: 
                   5695:     $classlist - reference to the class list hash. This is a hash
                   5696:                  keyed by student name:domain  whose elements are references
1.424     albertel 5697:                  to arrays containing various chunks of information
1.423     albertel 5698:                  about the student. (See loncoursedata for more info).
                   5699: 
                   5700:   Returns
                   5701:     %idmap - the constructed hash
                   5702: 
                   5703: =cut
                   5704: 
1.82      albertel 5705: sub username_to_idmap {
                   5706:     my ($classlist)= @_;
                   5707:     my %idmap;
                   5708:     foreach my $student (keys(%$classlist)) {
                   5709: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5710: 	    $student;
                   5711:     }
                   5712:     return %idmap;
                   5713: }
1.423     albertel 5714: 
                   5715: =pod
                   5716: 
1.424     albertel 5717: =item scantron_fixup_scanline
1.423     albertel 5718: 
                   5719:    Process a requested correction to a scanline.
                   5720: 
                   5721:   Arguments:
                   5722:     $scantron_config   - hash from &get_scantron_config()
                   5723:     $scan_data         - hash of correction information 
                   5724:                           (see &scantron_getfile())
                   5725:     $line              - existing scanline
                   5726:     $whichline         - line number of the passed in scanline
                   5727:     $field             - type of change to process 
                   5728:                          (either 
1.573     bisitz   5729:                           'ID'     -> correct the student/employee ID
1.423     albertel 5730:                           'CODE'   -> correct the CODE
                   5731:                           'answer' -> fixup the submitted answers)
                   5732:     
                   5733:    $args               - hash of additional info,
                   5734:                           - 'ID' 
                   5735:                                'newid' -> studentID to use in replacement
1.424     albertel 5736:                                           of existing one
1.423     albertel 5737:                           - 'CODE' 
                   5738:                                'CODE_ignore_dup' - set to true if duplicates
                   5739:                                                    should be ignored.
                   5740: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5741:                                         if the existing unfound code should
1.423     albertel 5742:                                         be used as is
                   5743:                           - 'answer'
                   5744:                                'response' - new answer or 'none' if blank
                   5745:                                'question' - the bubble line to change
1.503     raeburn  5746:                                'questionnum' - the question identifier,
                   5747:                                                may include subquestion. 
1.423     albertel 5748: 
                   5749:   Returns:
                   5750:     $line - the modified scanline
                   5751: 
                   5752:   Side effects: 
                   5753:     $scan_data - may be updated
                   5754: 
                   5755: =cut
                   5756: 
1.82      albertel 5757: 
1.157     albertel 5758: sub scantron_fixup_scanline {
                   5759:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5760:     if ($field eq 'ID') {
                   5761: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5762: 	    return ($line,1,'New value too large');
1.157     albertel 5763: 	}
                   5764: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5765: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5766: 				     $args->{'newid'});
                   5767: 	}
                   5768: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5769: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5770: 	if ($args->{'newid'}=~/^\s*$/) {
                   5771: 	    &scan_data($scan_data,"$whichline.user",
                   5772: 		       $args->{'username'}.':'.$args->{'domain'});
                   5773: 	}
1.186     albertel 5774:     } elsif ($field eq 'CODE') {
1.192     albertel 5775: 	if ($args->{'CODE_ignore_dup'}) {
                   5776: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5777: 	}
                   5778: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5779: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5780: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5781: 		return ($line,1,'New CODE value too large');
                   5782: 	    }
                   5783: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5784: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5785: 	    }
                   5786: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5787: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5788: 	}
1.157     albertel 5789:     } elsif ($field eq 'answer') {
1.497     foxr     5790: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5791: 	my $off=$scantron_config->{'Qoff'};
                   5792: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5793: 	my $answer=${off}x$length;
                   5794: 	if ($args->{'response'} eq 'none') {
                   5795: 	    &scan_data($scan_data,
1.503     raeburn  5796: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5797: 	} else {
                   5798: 	    if ($on eq 'letter') {
                   5799: 		my @alphabet=('A'..'Z');
                   5800: 		$answer=$alphabet[$args->{'response'}];
                   5801: 	    } elsif ($on eq 'number') {
                   5802: 		$answer=$args->{'response'}+1;
                   5803: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5804: 	    } else {
1.497     foxr     5805: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5806: 	    }
1.497     foxr     5807: 	    &scan_data($scan_data,
1.503     raeburn  5808: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5809: 	}
1.497     foxr     5810: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5811: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5812:     }
                   5813:     return $line;
                   5814: }
1.423     albertel 5815: 
                   5816: =pod
                   5817: 
                   5818: =item scan_data
                   5819: 
                   5820:     Edit or look up  an item in the scan_data hash.
                   5821: 
                   5822:   Arguments:
                   5823:     $scan_data  - The hash (see scantron_getfile)
                   5824:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5825:                   scantronfilename_key).
1.423     albertel 5826:     $data        - New value of the hash entry.
                   5827:     $delete      - If true, the entry is removed from the hash.
                   5828: 
                   5829:   Returns:
                   5830:     The new value of the hash table field (undefined if deleted).
                   5831: 
                   5832: =cut
                   5833: 
                   5834: 
1.157     albertel 5835: sub scan_data {
                   5836:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5837:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5838:     if (defined($value)) {
                   5839: 	$scan_data->{$filename.'_'.$key} = $value;
                   5840:     }
                   5841:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5842:     return $scan_data->{$filename.'_'.$key};
                   5843: }
1.423     albertel 5844: 
1.495     albertel 5845: # ----- These first few routines are general use routines.----
                   5846: 
                   5847: # Return the number of occurences of a pattern in a string.
                   5848: 
                   5849: sub occurence_count {
                   5850:     my ($string, $pattern) = @_;
                   5851: 
                   5852:     my @matches = ($string =~ /$pattern/g);
                   5853: 
                   5854:     return scalar(@matches);
                   5855: }
                   5856: 
                   5857: 
                   5858: # Take a string known to have digits and convert all the
                   5859: # digits into letters in the range J,A..I.
                   5860: 
                   5861: sub digits_to_letters {
                   5862:     my ($input) = @_;
                   5863: 
                   5864:     my @alphabet = ('J', 'A'..'I');
                   5865: 
                   5866:     my @input    = split(//, $input);
                   5867:     my $output ='';
                   5868:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5869: 	if ($input[$i] =~ /\d/) {
                   5870: 	    $output .= $alphabet[$input[$i]];
                   5871: 	} else {
                   5872: 	    $output .= $input[$i];
                   5873: 	}
                   5874:     }
                   5875:     return $output;
                   5876: }
                   5877: 
1.423     albertel 5878: =pod 
                   5879: 
                   5880: =item scantron_parse_scanline
                   5881: 
1.711     bisitz   5882:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5883: 
                   5884:  Arguments:
1.711     bisitz   5885:     line             - The text of the bubblesheet file line to process
1.423     albertel 5886:     whichline        - Line number
1.711     bisitz   5887:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5888:     scan_data        - Hash of extra information about the scanline
                   5889:                        (see scantron_getfile for more information)
                   5890:     just_header      - True if should not process question answers but only
                   5891:                        the stuff to the left of the answers.
1.691     raeburn  5892:     randomorder      - True if randomorder in use
                   5893:     randompick       - True if randompick in use
                   5894:     sequence         - Exam folder URL
                   5895:     master_seq       - Ref to array containing symbs in exam folder
                   5896:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5897:                        (corresponding values are resource objects)
                   5898:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5899:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5900:                        are refs to an array of resource objects, ordered
                   5901:                        according to order used for CODE, when randomorder
                   5902:                        and or randompick are in use.
                   5903:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5904:                        for current line to question number used for same question
                   5905:                         in "Master Sequence" (as seen by Course Coordinator).
                   5906:     startline        - Ref to hash where key is question number (0 is first)
                   5907:                        and value is number of first bubble line for current 
                   5908:                        student or code-based randompick and/or randomorder.
                   5909:     totalref         - Ref of scalar used to score total number of bubble
                   5910:                        lines needed for responses in a scan line (used when
                   5911:                        randompick in use. 
                   5912:     
1.423     albertel 5913:  Returns:
                   5914:    Hash containing the result of parsing the scanline
                   5915: 
                   5916:    Keys are all proceeded by the string 'scantron.'
                   5917: 
                   5918:        CODE    - the CODE in use for this scanline
                   5919:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5920:                  by the operator
                   5921:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5922:                             CODEs were selected, but the usage has been
                   5923:                             forced by the operator
1.556     weissno  5924:        ID  - student/employee ID
1.423     albertel 5925:        PaperID - if used, the ID number printed on the sheet when the 
                   5926:                  paper was scanned
                   5927:        FirstName - first name from the sheet
                   5928:        LastName  - last name from the sheet
                   5929: 
                   5930:      if just_header was not true these key may also exist
                   5931: 
1.447     foxr     5932:        missingerror - a list of bubble ranges that are considered to be answers
                   5933:                       to a single question that don't have any bubbles filled in.
                   5934:                       Of the form questionnumber:firstbubblenumber:count.
                   5935:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5936:                       to a single question that have more than one bubble filled in.
                   5937:                       Of the form questionnumber::firstbubblenumber:count
                   5938:    
                   5939:                 In the above, count is the number of bubble responses in the
                   5940:                 input line needed to represent the possible answers to the question.
                   5941:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5942:                 per line would have count = 2.
                   5943: 
1.423     albertel 5944:        maxquest     - the number of the last bubble line that was parsed
                   5945: 
                   5946:        (<number> starts at 1)
                   5947:        <number>.answer - zero or more letters representing the selected
                   5948:                          letters from the scanline for the bubble line 
                   5949:                          <number>.
                   5950:                          if blank there was either no bubble or there where
                   5951:                          multiple bubbles, (consult the keys missingerror and
                   5952:                          doubleerror if this is an error condition)
                   5953: 
                   5954: =cut
                   5955: 
1.82      albertel 5956: sub scantron_parse_scanline {
1.691     raeburn  5957:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5958:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5959:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5960: 
1.82      albertel 5961:     my %record;
1.691     raeburn  5962:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 5963:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5964: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5965: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5966: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5967: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5968: 	    $record{'scantron.CODE'}=substr($data,
                   5969: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5970: 					    $$scantron_config{'CODElength'});
1.191     albertel 5971: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5972: 		$record{'scantron.useCODE'}=1;
                   5973: 	    }
1.192     albertel 5974: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5975: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5976: 	    }
1.82      albertel 5977: 	} else {
                   5978: 	    #FIXME interpret first N questions
                   5979: 	}
                   5980:     }
1.83      albertel 5981:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5982: 				  $$scantron_config{'IDlength'});
1.157     albertel 5983:     $record{'scantron.PaperID'}=
                   5984: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5985: 	       $$scantron_config{'PaperIDlength'});
                   5986:     $record{'scantron.FirstName'}=
                   5987: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5988: 	       $$scantron_config{'FirstNamelength'});
                   5989:     $record{'scantron.LastName'}=
                   5990: 	substr($data,$$scantron_config{'LastName'}-1,
                   5991: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5992:     if ($just_header) { return \%record; }
1.194     albertel 5993: 
1.82      albertel 5994:     my @alphabet=('A'..'Z');
                   5995:     my $questnum=0;
1.447     foxr     5996:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5997: 
1.691     raeburn  5998:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5999:     if ($randompick || $randomorder) {
                   6000:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6001:                                          $master_seq,$symb_to_resource,
                   6002:                                          $partids_by_symb,$orderedforcode,
                   6003:                                          $respnumlookup,$startline);
                   6004:         if ($total) {
                   6005:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6006:         }
                   6007:         if (ref($totalref)) {
                   6008:             $$totalref = $total;
                   6009:         }
                   6010:     }
                   6011:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6012:     chomp($questions);		# Get rid of any trailing \n.
                   6013:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6014:     while (length($questions)) {
1.691     raeburn  6015:         my $answers_needed;
                   6016:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6017:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6018:         } else {
                   6019: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6020:         }
1.503     raeburn  6021:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6022:                              || 1;
                   6023:         $questnum++;
                   6024:         my $quest_id = $questnum;
                   6025:         my $currentquest = substr($questions,0,$answer_length);
                   6026:         $questions       = substr($questions,$answer_length);
                   6027:         if (length($currentquest) < $answer_length) { next; }
                   6028: 
1.691     raeburn  6029:         my $subdivided;
                   6030:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6031:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6032:         } else {
                   6033:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6034:         }
                   6035:         if ($subdivided =~ /,/) {
1.503     raeburn  6036:             my $subquestnum = 1;
                   6037:             my $subquestions = $currentquest;
1.691     raeburn  6038:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6039:             foreach my $subans (@subanswers_needed) {
                   6040:                 my $subans_length =
                   6041:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6042:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6043:                 $subquestions   = substr($subquestions,$subans_length);
                   6044:                 $quest_id = "$questnum.$subquestnum";
                   6045:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6046:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6047:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6048:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6049:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6050:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6051:                 } else {
                   6052:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6053:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6054:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6055:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6056:                 }
                   6057:                 $subquestnum ++;
                   6058:             }
                   6059:         } else {
                   6060:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6061:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6062:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6063:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6064:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6065:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6066:             } else {
                   6067:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6068:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6069:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6070:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6071:             }
                   6072:         }
                   6073:     }
                   6074:     $record{'scantron.maxquest'}=$questnum;
                   6075:     return \%record;
                   6076: }
1.447     foxr     6077: 
1.691     raeburn  6078: sub get_master_seq {
                   6079:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6080:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6081:                    (ref($symb_to_resource) eq 'HASH'));
                   6082:     my $resource_error;
                   6083:     foreach my $resource (@{$resources}) {
                   6084:         my $ressymb;
                   6085:         if (ref($resource)) {
                   6086:             $ressymb = $resource->symb();
                   6087:             push(@{$master_seq},$ressymb);
                   6088:             $symb_to_resource->{$ressymb} = $resource;
                   6089:         } else {
                   6090:             $resource_error = 1;
                   6091:             last;
                   6092:         }
                   6093:     }
                   6094:     return $resource_error;
                   6095: }
                   6096: 
                   6097: sub get_respnum_lookups {
                   6098:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6099:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6100:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6101:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6102:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6103:                    (ref($startline) eq 'HASH'));
                   6104:     my ($user,$scancode);
                   6105:     if ((exists($record->{'scantron.CODE'})) &&
                   6106:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6107:         $scancode = $record->{'scantron.CODE'};
                   6108:     } else {
                   6109:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6110:     }
                   6111:     my @mapresources =
                   6112:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6113:                      $orderedforcode);
                   6114:     my $total = 0;
                   6115:     my $count = 0;
                   6116:     foreach my $resource (@mapresources) {
                   6117:         my $id = $resource->id();
                   6118:         my $symb = $resource->symb();
                   6119:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6120:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6121:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6122:                 if ($respnum ne '') {
                   6123:                     $respnumlookup->{$count} = $respnum;
                   6124:                     $startline->{$count} = $total;
                   6125:                     $total += $bubble_lines_per_response{$respnum};
                   6126:                     $count ++;
                   6127:                 }
                   6128:             }
                   6129:         }
                   6130:     }
                   6131:     return $total;
                   6132: }
                   6133: 
1.503     raeburn  6134: sub scantron_validator_lettnum {
                   6135:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6136:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6137:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6138: 
                   6139:     # Qon 'letter' implies for each slot in currquest we have:
                   6140:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6141:     #    about anything else (esp. a value of Qoff) for missing
                   6142:     #    bubbles.
                   6143:     #
                   6144:     # Qon 'number' implies each slot gives a digit that indexes the
                   6145:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6146:     #    and * or ? for double bubbles on a single line.
                   6147:     #
1.447     foxr     6148: 
1.503     raeburn  6149:     my $matchon;
                   6150:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6151:         $matchon = '[A-Z]';
                   6152:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6153:         $matchon = '\d';
                   6154:     }
                   6155:     my $occurrences = 0;
1.691     raeburn  6156:     my $responsenum = $questnum-1;
                   6157:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6158:        $responsenum = $respnumlookup->{$questnum-1} 
                   6159:     }
                   6160:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6161:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6162:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6163:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6164:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6165:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6166:         my @singlelines = split('',$currquest);
                   6167:         foreach my $entry (@singlelines) {
                   6168:             $occurrences = &occurence_count($entry,$matchon);
                   6169:             if ($occurrences > 1) {
                   6170:                 last;
                   6171:             }
1.691     raeburn  6172:         }
1.503     raeburn  6173:     } else {
                   6174:         $occurrences = &occurence_count($currquest,$matchon); 
                   6175:     }
                   6176:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6177:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6178:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6179:             my $bubble = substr($currquest,$ans,1);
                   6180:             if ($bubble =~ /$matchon/ ) {
                   6181:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6182:                     if ($bubble == 0) {
                   6183:                         $bubble = 10; 
                   6184:                     }
                   6185:                     $record->{"scantron.$ansnum.answer"} = 
                   6186:                         $alphabet->[$bubble-1];
                   6187:                 } else {
                   6188:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6189:                 }
                   6190:             } else {
                   6191:                 $record->{"scantron.$ansnum.answer"}='';
                   6192:             }
                   6193:             $ansnum++;
                   6194:         }
                   6195:     } elsif (!defined($currquest)
                   6196:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6197:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6198:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6199:             $record->{"scantron.$ansnum.answer"}='';
                   6200:             $ansnum++;
                   6201:         }
                   6202:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6203:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6204:         }
                   6205:     } else {
                   6206:         if ($$scantron_config{'Qon'} eq 'number') {
                   6207:             $currquest = &digits_to_letters($currquest);            
                   6208:         }
                   6209:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6210:             my $bubble = substr($currquest,$ans,1);
                   6211:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6212:             $ansnum++;
                   6213:         }
                   6214:     }
                   6215:     return $ansnum;
                   6216: }
1.447     foxr     6217: 
1.503     raeburn  6218: sub scantron_validator_positional {
                   6219:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6220:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6221:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6222: 
1.503     raeburn  6223:     # Otherwise there's a positional notation;
                   6224:     # each bubble line requires Qlength items, and there are filled in
                   6225:     # bubbles for each case where there 'Qon' characters.
                   6226:     #
1.447     foxr     6227: 
1.503     raeburn  6228:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6229: 
1.503     raeburn  6230:     # If the split only gives us one element.. the full length of the
                   6231:     # answer string, no bubbles are filled in:
1.447     foxr     6232: 
1.507     raeburn  6233:     if ($answers_needed eq '') {
                   6234:         return;
                   6235:     }
                   6236: 
1.503     raeburn  6237:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6238:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6239:             $record->{"scantron.$ansnum.answer"}='';
                   6240:             $ansnum++;
                   6241:         }
                   6242:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6243:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6244:         }
                   6245:     } elsif (scalar(@array) == 2) {
                   6246:         my $location = length($array[0]);
                   6247:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6248:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6249:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6250:             if ($ans eq $line_num) {
                   6251:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6252:             } else {
                   6253:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6254:             }
                   6255:             $ansnum++;
                   6256:          }
                   6257:     } else {
                   6258:         #  If there's more than one instance of a bubble character
                   6259:         #  That's a double bubble; with positional notation we can
                   6260:         #  record all the bubbles filled in as well as the
                   6261:         #  fact this response consists of multiple bubbles.
                   6262:         #
1.691     raeburn  6263:         my $responsenum = $questnum-1;
                   6264:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6265:             $responsenum = $respnumlookup->{$questnum-1}
                   6266:         }
                   6267:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6268:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6269:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6270:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6271:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6272:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6273:             my $doubleerror = 0;
                   6274:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6275:                    (!$doubleerror)) {
                   6276:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6277:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6278:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6279:                if (length(@currarray) > 2) {
                   6280:                    $doubleerror = 1;
                   6281:                } 
                   6282:             }
                   6283:             if ($doubleerror) {
                   6284:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6285:             }
                   6286:         } else {
                   6287:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6288:         }
                   6289:         my $item = $ansnum;
                   6290:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6291:             $record->{"scantron.$item.answer"} = '';
                   6292:             $item ++;
                   6293:         }
1.447     foxr     6294: 
1.503     raeburn  6295:         my @ans=@array;
                   6296:         my $i=0;
                   6297:         my $increment = 0;
                   6298:         while ($#ans) {
                   6299:             $i+=length($ans[0]) + $increment;
                   6300:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6301:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6302:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6303:             shift(@ans);
                   6304:             $increment = 1;
                   6305:         }
                   6306:         $ansnum += $answers_needed;
1.82      albertel 6307:     }
1.503     raeburn  6308:     return $ansnum;
1.82      albertel 6309: }
                   6310: 
1.423     albertel 6311: =pod
                   6312: 
                   6313: =item scantron_add_delay
                   6314: 
                   6315:    Adds an error message that occurred during the grading phase to a
                   6316:    queue of messages to be shown after grading pass is complete
                   6317: 
                   6318:  Arguments:
1.424     albertel 6319:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6320:    $scanline    - the scanline that caused the error
                   6321:    $errormesage - the error message
                   6322:    $errorcode   - a numeric code for the error
                   6323: 
                   6324:  Side Effects:
1.424     albertel 6325:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6326: 
                   6327: =cut
                   6328: 
1.82      albertel 6329: sub scantron_add_delay {
1.140     albertel 6330:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6331:     push(@$delayqueue,
                   6332: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6333: 	  'ecode' => $errorcode }
                   6334: 	 );
1.82      albertel 6335: }
                   6336: 
1.423     albertel 6337: =pod
                   6338: 
                   6339: =item scantron_find_student
                   6340: 
1.424     albertel 6341:    Finds the username for the current scanline
                   6342: 
                   6343:   Arguments:
                   6344:    $scantron_record - hash result from scantron_parse_scanline
                   6345:    $scan_data       - hash of correction information 
                   6346:                       (see &scantron_getfile() form more information)
                   6347:    $idmap           - hash from &username_to_idmap()
                   6348:    $line            - number of current scanline
                   6349:  
                   6350:   Returns:
                   6351:    Either 'username:domain' or undef if unknown
                   6352: 
1.423     albertel 6353: =cut
                   6354: 
1.82      albertel 6355: sub scantron_find_student {
1.157     albertel 6356:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6357:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6358:     if ($scanID =~ /^\s*$/) {
                   6359:  	return &scan_data($scan_data,"$line.user");
                   6360:     }
1.83      albertel 6361:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6362:  	if (lc($id) eq lc($scanID)) {
                   6363:  	    return $$idmap{$id};
                   6364:  	}
1.83      albertel 6365:     }
                   6366:     return undef;
                   6367: }
                   6368: 
1.423     albertel 6369: =pod
                   6370: 
                   6371: =item scantron_filter
                   6372: 
1.424     albertel 6373:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6374:    hidden resources was selected
                   6375: 
1.423     albertel 6376: =cut
                   6377: 
1.83      albertel 6378: sub scantron_filter {
                   6379:     my ($curres)=@_;
1.331     albertel 6380: 
                   6381:     if (ref($curres) && $curres->is_problem()) {
                   6382: 	# if the user has asked to not have either hidden
                   6383: 	# or 'randomout' controlled resources to be graded
                   6384: 	# don't include them
                   6385: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6386: 	    && $curres->randomout) {
                   6387: 	    return 0;
                   6388: 	}
1.83      albertel 6389: 	return 1;
                   6390:     }
                   6391:     return 0;
1.82      albertel 6392: }
                   6393: 
1.423     albertel 6394: =pod
                   6395: 
                   6396: =item scantron_process_corrections
                   6397: 
1.424     albertel 6398:    Gets correction information out of submitted form data and corrects
                   6399:    the scanline
                   6400: 
1.423     albertel 6401: =cut
                   6402: 
1.157     albertel 6403: sub scantron_process_corrections {
                   6404:     my ($r) = @_;
1.257     albertel 6405:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6406:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6407:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6408:     my $which=$env{'form.scantron_line'};
1.200     albertel 6409:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6410:     my ($skip,$err,$errmsg);
1.257     albertel 6411:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6412: 	$skip=1;
1.257     albertel 6413:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6414: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6415: 	    $env{'form.scantron_domain'};
1.157     albertel 6416: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6417: 	($line,$err,$errmsg)=
                   6418: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6419: 				     'ID',{'newid'=>$newid,
1.257     albertel 6420: 				    'username'=>$env{'form.scantron_username'},
                   6421: 				    'domain'=>$env{'form.scantron_domain'}});
                   6422:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6423: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6424: 	my $newCODE;
1.192     albertel 6425: 	my %args;
1.190     albertel 6426: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6427: 	    $newCODE='use_unfound';
1.190     albertel 6428: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6429: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6430: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6431: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6432: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6433: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6434: 	}
1.257     albertel 6435: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6436: 	    $args{'CODE_ignore_dup'}=1;
                   6437: 	}
                   6438: 	$args{'CODE'}=$newCODE;
1.186     albertel 6439: 	($line,$err,$errmsg)=
                   6440: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6441: 				     'CODE',\%args);
1.257     albertel 6442:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6443: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6444: 	    ($line,$err,$errmsg)=
                   6445: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6446: 					 $which,'answer',
                   6447: 					 { 'question'=>$question,
1.503     raeburn  6448: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6449:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6450: 	    if ($err) { last; }
                   6451: 	}
                   6452:     }
                   6453:     if ($err) {
1.703     bisitz   6454:         $r->print(
                   6455:             '<p class="LC_error">'
                   6456:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6457:                 $errmsg)
1.704     raeburn  6458:            .'</p>');
1.157     albertel 6459:     } else {
1.200     albertel 6460: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6461: 	&scantron_putfile($scanlines,$scan_data);
                   6462:     }
                   6463: }
                   6464: 
1.423     albertel 6465: =pod
                   6466: 
                   6467: =item reset_skipping_status
                   6468: 
1.424     albertel 6469:    Forgets the current set of remember skipped scanlines (and thus
                   6470:    reverts back to considering all lines in the
                   6471:    scantron_skipped_<filename> file)
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.200     albertel 6475: sub reset_skipping_status {
                   6476:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6477:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6478:     &scantron_putfile(undef,$scan_data);
                   6479: }
                   6480: 
1.423     albertel 6481: =pod
                   6482: 
                   6483: =item start_skipping
                   6484: 
1.424     albertel 6485:    Marks a scanline to be skipped. 
                   6486: 
1.423     albertel 6487: =cut
                   6488: 
1.376     albertel 6489: sub start_skipping {
1.200     albertel 6490:     my ($scan_data,$i)=@_;
                   6491:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6492:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6493: 	$remembered{$i}=2;
                   6494:     } else {
                   6495: 	$remembered{$i}=1;
                   6496:     }
1.200     albertel 6497:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6498: }
                   6499: 
1.423     albertel 6500: =pod
                   6501: 
                   6502: =item should_be_skipped
                   6503: 
1.424     albertel 6504:    Checks whether a scanline should be skipped.
                   6505: 
1.423     albertel 6506: =cut
                   6507: 
1.200     albertel 6508: sub should_be_skipped {
1.376     albertel 6509:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6510:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6511: 	# not redoing old skips
1.376     albertel 6512: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6513: 	return 0;
                   6514:     }
                   6515:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6516: 
                   6517:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6518: 	return 0;
                   6519:     }
1.200     albertel 6520:     return 1;
                   6521: }
                   6522: 
1.423     albertel 6523: =pod
                   6524: 
                   6525: =item remember_current_skipped
                   6526: 
1.424     albertel 6527:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6528:    file and remembers them into scan_data for later use.
                   6529: 
1.423     albertel 6530: =cut
                   6531: 
1.200     albertel 6532: sub remember_current_skipped {
                   6533:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6534:     my %to_remember;
                   6535:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6536: 	if ($scanlines->{'skipped'}[$i]) {
                   6537: 	    $to_remember{$i}=1;
                   6538: 	}
                   6539:     }
1.376     albertel 6540: 
1.200     albertel 6541:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6542:     &scantron_putfile(undef,$scan_data);
                   6543: }
                   6544: 
1.423     albertel 6545: =pod
                   6546: 
                   6547: =item check_for_error
                   6548: 
1.424     albertel 6549:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6550:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6551:     something went wrong.
                   6552: 
1.423     albertel 6553: =cut
                   6554: 
1.200     albertel 6555: sub check_for_error {
                   6556:     my ($r,$result)=@_;
                   6557:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6558: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6559:     }
                   6560: }
1.157     albertel 6561: 
1.423     albertel 6562: =pod
                   6563: 
                   6564: =item scantron_warning_screen
                   6565: 
1.424     albertel 6566:    Interstitial screen to make sure the operator has selected the
                   6567:    correct options before we start the validation phase.
                   6568: 
1.423     albertel 6569: =cut
                   6570: 
1.203     albertel 6571: sub scantron_warning_screen {
1.650     raeburn  6572:     my ($button_text,$symb)=@_;
1.257     albertel 6573:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6574:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6575:     my $CODElist;
1.284     albertel 6576:     if ($scantron_config{'CODElocation'} &&
                   6577: 	$scantron_config{'CODEstart'} &&
                   6578: 	$scantron_config{'CODElength'}) {
                   6579: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6580: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6581: 	$CODElist=
1.492     albertel 6582: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6583: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6584:     }
1.663     raeburn  6585:     my $lastbubblepoints;
                   6586:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6587:         $lastbubblepoints =
                   6588:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6589:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6590:     }
1.492     albertel 6591:     return ('
1.203     albertel 6592: <p>
1.492     albertel 6593: <span class="LC_warning">
1.705     raeburn  6594: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6595: </p>
                   6596: <table>
1.492     albertel 6597: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6598: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6599: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6600: </table>
1.680     raeburn  6601: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6602: '.&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 6603: 
                   6604: <br />
1.492     albertel 6605: ');
1.203     albertel 6606: }
                   6607: 
1.423     albertel 6608: =pod
                   6609: 
                   6610: =item scantron_do_warning
                   6611: 
1.424     albertel 6612:    Check if the operator has picked something for all required
                   6613:    fields. Error out if something is missing.
                   6614: 
1.423     albertel 6615: =cut
                   6616: 
1.203     albertel 6617: sub scantron_do_warning {
1.608     www      6618:     my ($r,$symb)=@_;
1.203     albertel 6619:     if (!$symb) {return '';}
1.324     albertel 6620:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6621:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6622:     if ( $env{'form.selectpage'} eq '' ||
                   6623: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6624: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6625: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6626: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6627: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6628: 	} 
1.257     albertel 6629: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6630: 	    $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 6631: 	} 
1.257     albertel 6632: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6633: 	    $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 6634: 	} 
                   6635:     } else {
1.650     raeburn  6636: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6637:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6638: 	$r->print('
1.663     raeburn  6639: '.$warning.$bubbledbyhand.'
1.492     albertel 6640: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6641: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6642: ');
1.237     albertel 6643:     }
1.614     www      6644:     $r->print("</form><br />");
1.203     albertel 6645:     return '';
                   6646: }
                   6647: 
1.423     albertel 6648: =pod
                   6649: 
                   6650: =item scantron_form_start
                   6651: 
1.424     albertel 6652:     html hidden input for remembering all selected grading options
                   6653: 
1.423     albertel 6654: =cut
                   6655: 
1.203     albertel 6656: sub scantron_form_start {
                   6657:     my ($max_bubble)=@_;
                   6658:     my $result= <<SCANTRONFORM;
                   6659: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6660:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6661:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6662:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6663:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6664:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6665:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6666:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6667:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6668:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6669: SCANTRONFORM
1.447     foxr     6670: 
                   6671:   my $line = 0;
                   6672:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6673:        my $chunk =
                   6674: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6675:        $chunk .=
                   6676: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6677:        $chunk .= 
                   6678:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6679:        $chunk .=
                   6680:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6681:        $chunk .=
                   6682:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6683:        $result .= $chunk;
                   6684:        $line++;
1.691     raeburn  6685:     }
1.203     albertel 6686:     return $result;
                   6687: }
                   6688: 
1.423     albertel 6689: =pod
                   6690: 
                   6691: =item scantron_validate_file
                   6692: 
1.659     raeburn  6693:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6694: 
                   6695:     Also processes any necessary information resets that need to
                   6696:     occur before validation begins (ignore previous corrections,
                   6697:     restarting the skipped records processing)
                   6698: 
1.423     albertel 6699: =cut
                   6700: 
1.157     albertel 6701: sub scantron_validate_file {
1.608     www      6702:     my ($r,$symb) = @_;
1.157     albertel 6703:     if (!$symb) {return '';}
1.324     albertel 6704:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6705:     
1.703     bisitz   6706:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6707:     # them when doing the corrections reset
1.257     albertel 6708:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6709: 	&reset_skipping_status();
                   6710:     }
1.257     albertel 6711:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6712: 	&remember_current_skipped();
1.257     albertel 6713: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6714:     }
                   6715: 
1.257     albertel 6716:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6717: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6718: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6719: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6720: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6721:     }
1.200     albertel 6722: 
1.257     albertel 6723:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6724: 	&scantron_process_corrections($r);
                   6725:     }
1.503     raeburn  6726:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6727:     #get the student pick code ready
                   6728:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6729:     my $nav_error;
1.649     raeburn  6730:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6731:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6732:     if ($nav_error) {
                   6733:         $r->print(&navmap_errormsg());
                   6734:         return '';
                   6735:     }
1.203     albertel 6736:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6737:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6738:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6739:     }
1.157     albertel 6740:     $r->print($result);
                   6741:     
1.334     albertel 6742:     my @validate_phases=( 'sequence',
                   6743: 			  'ID',
1.157     albertel 6744: 			  'CODE',
                   6745: 			  'doublebubble',
                   6746: 			  'missingbubbles');
1.257     albertel 6747:     if (!$env{'form.validatepass'}) {
                   6748: 	$env{'form.validatepass'} = 0;
1.157     albertel 6749:     }
1.257     albertel 6750:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6751: 
1.448     foxr     6752: 
1.157     albertel 6753:     my $stop=0;
                   6754:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6755: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6756: 	$r->rflush();
1.691     raeburn  6757:      
1.157     albertel 6758: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6759: 	{
                   6760: 	    no strict 'refs';
                   6761: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6762: 	}
                   6763:     }
                   6764:     if (!$stop) {
1.650     raeburn  6765: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6766: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6767:                   $warning.
                   6768:                   &mt('Perform verification for each student after storage of submissions?').
                   6769:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6770:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6771:                   ('&nbsp;'x3).'<label>'.
                   6772:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6773:                   '</label></span><br />'.
                   6774:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6775:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6776:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6777:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6778:     } else {
                   6779: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6780: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6781:     }
                   6782:     if ($stop) {
1.334     albertel 6783: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6784: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6785: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6786: 
1.650     raeburn  6787: 	    $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 6788: 	} else {
1.503     raeburn  6789:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6790: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6791:             } else {
1.539     riegler  6792:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6793:             }
1.492     albertel 6794: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6795: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6796: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6797: 	}
1.157     albertel 6798:     }
1.614     www      6799:     $r->print(" </form><br />");
1.157     albertel 6800:     return '';
                   6801: }
                   6802: 
1.423     albertel 6803: 
                   6804: =pod
                   6805: 
                   6806: =item scantron_remove_file
                   6807: 
1.659     raeburn  6808:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6809:    scantron_original_<filename> is never removed
                   6810: 
                   6811: 
1.423     albertel 6812: =cut
                   6813: 
1.200     albertel 6814: sub scantron_remove_file {
1.192     albertel 6815:     my ($which)=@_;
1.257     albertel 6816:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6817:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6818:     my $file='scantron_';
1.200     albertel 6819:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6820: 	$file.=$which.'_';
1.192     albertel 6821:     } else {
                   6822: 	return 'refused';
                   6823:     }
1.257     albertel 6824:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6825:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6826: }
                   6827: 
1.423     albertel 6828: 
                   6829: =pod
                   6830: 
                   6831: =item scantron_remove_scan_data
                   6832: 
1.659     raeburn  6833:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6834:    data file.  (In the case that both the are doing skipped records we need
                   6835:    to remember the old skipped lines for the time being so that element
                   6836:    persists for a while.)
                   6837: 
1.423     albertel 6838: =cut
                   6839: 
1.200     albertel 6840: sub scantron_remove_scan_data {
1.257     albertel 6841:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6842:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6843:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6844:     my @todelete;
1.257     albertel 6845:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6846:     foreach my $key (@keys) {
                   6847: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6848: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6849: 		$key=~/remember_skipping/) {
                   6850: 		next;
                   6851: 	    }
1.192     albertel 6852: 	    push(@todelete,$key);
                   6853: 	}
                   6854:     }
1.200     albertel 6855:     my $result;
1.192     albertel 6856:     if (@todelete) {
1.491     albertel 6857: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6858: 				       \@todelete,$cdom,$cname);
                   6859:     } else {
                   6860: 	$result = 'ok';
1.192     albertel 6861:     }
                   6862:     return $result;
                   6863: }
                   6864: 
1.423     albertel 6865: 
                   6866: =pod
                   6867: 
                   6868: =item scantron_getfile
                   6869: 
1.659     raeburn  6870:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6871:     the scan_data hash
                   6872:   
                   6873:   Arguments:
                   6874:     None
                   6875: 
                   6876:   Returns:
                   6877:     2 hash references
                   6878: 
                   6879:      - first one has 
                   6880:          orig      -
                   6881:          corrected -
                   6882:          skipped   -  each of which points to an array ref of the specified
                   6883:                       file broken up into individual lines
                   6884:          count     - number of scanlines
                   6885:  
                   6886:      - second is the scan_data hash possible keys are
1.425     albertel 6887:        ($number refers to scanline numbered $number and thus the key affects
                   6888:         only that scanline
                   6889:         $bubline refers to the specific bubble line element and the aspects
                   6890:         refers to that specific bubble line element)
                   6891: 
                   6892:        $number.user - username:domain to use
                   6893:        $number.CODE_ignore_dup 
                   6894:                     - ignore the duplicate CODE error 
                   6895:        $number.useCODE
                   6896:                     - use the CODE in the scanline as is
                   6897:        $number.no_bubble.$bubline
                   6898:                     - it is valid that there is no bubbled in bubble
                   6899:                       at $number $bubline
                   6900:        remember_skipping
                   6901:                     - a frozen hash containing keys of $number and values
                   6902:                       of either 
                   6903:                         1 - we are on a 'do skipped records pass' and plan
                   6904:                             on processing this line
                   6905:                         2 - we are on a 'do skipped records pass' and this
                   6906:                             scanline has been marked to skip yet again
1.424     albertel 6907: 
1.423     albertel 6908: =cut
                   6909: 
1.157     albertel 6910: sub scantron_getfile {
1.200     albertel 6911:     #FIXME really would prefer a scantron directory
1.257     albertel 6912:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6913:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6914:     my $lines;
                   6915:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6916: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6917:     my %scanlines;
                   6918:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6919:     my $temp=$scanlines{'orig'};
                   6920:     $scanlines{'count'}=$#$temp;
                   6921: 
                   6922:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6923: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6924:     if ($lines eq '-1') {
                   6925: 	$scanlines{'corrected'}=[];
                   6926:     } else {
                   6927: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6928:     }
                   6929:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6930: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6931:     if ($lines eq '-1') {
                   6932: 	$scanlines{'skipped'}=[];
                   6933:     } else {
                   6934: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6935:     }
1.175     albertel 6936:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6937:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6938:     my %scan_data = @tmp;
                   6939:     return (\%scanlines,\%scan_data);
                   6940: }
                   6941: 
1.423     albertel 6942: =pod
                   6943: 
                   6944: =item lonnet_putfile
                   6945: 
1.424     albertel 6946:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6947: 
                   6948:  Arguments:
                   6949:    $contents - data to store
                   6950:    $filename - filename to store $contents into
                   6951: 
                   6952:  Returns:
                   6953:    result value from &Apache::lonnet::finishuserfileupload
                   6954: 
1.423     albertel 6955: =cut
                   6956: 
1.157     albertel 6957: sub lonnet_putfile {
                   6958:     my ($contents,$filename)=@_;
1.257     albertel 6959:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6960:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6961:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6962:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6963: 
                   6964: }
                   6965: 
1.423     albertel 6966: =pod
                   6967: 
                   6968: =item scantron_putfile
                   6969: 
1.659     raeburn  6970:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6971:     scan_data hash. (Does not modify the original version only the
                   6972:     corrected and skipped versions.
                   6973: 
                   6974:  Arguments:
                   6975:     $scanlines - hash ref that looks like the first return value from
                   6976:                  &scantron_getfile()
                   6977:     $scan_data - hash ref that looks like the second return value from
                   6978:                  &scantron_getfile()
                   6979: 
1.423     albertel 6980: =cut
                   6981: 
1.157     albertel 6982: sub scantron_putfile {
                   6983:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6984:     #FIXME really would prefer a scantron directory
1.257     albertel 6985:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6986:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6987:     if ($scanlines) {
                   6988: 	my $prefix='scantron_';
1.157     albertel 6989: # no need to update orig, shouldn't change
                   6990: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6991: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6992: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6993: 			$prefix.'corrected_'.
1.257     albertel 6994: 			$env{'form.scantron_selectfile'});
1.200     albertel 6995: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6996: 			$prefix.'skipped_'.
1.257     albertel 6997: 			$env{'form.scantron_selectfile'});
1.200     albertel 6998:     }
1.175     albertel 6999:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7000: }
                   7001: 
1.423     albertel 7002: =pod
                   7003: 
                   7004: =item scantron_get_line
                   7005: 
1.424     albertel 7006:    Returns the correct version of the scanline
                   7007: 
                   7008:  Arguments:
                   7009:     $scanlines - hash ref that looks like the first return value from
                   7010:                  &scantron_getfile()
                   7011:     $scan_data - hash ref that looks like the second return value from
                   7012:                  &scantron_getfile()
                   7013:     $i         - number of the requested line (starts at 0)
                   7014: 
                   7015:  Returns:
                   7016:    A scanline, (either the original or the corrected one if it
                   7017:    exists), or undef if the requested scanline should be
                   7018:    skipped. (Either because it's an skipped scanline, or it's an
                   7019:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7020:    pass.
                   7021: 
1.423     albertel 7022: =cut
                   7023: 
1.157     albertel 7024: sub scantron_get_line {
1.200     albertel 7025:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7026:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7027:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7028:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7029:     return $scanlines->{'orig'}[$i]; 
                   7030: }
                   7031: 
1.423     albertel 7032: =pod
                   7033: 
                   7034: =item scantron_todo_count
                   7035: 
1.424     albertel 7036:     Counts the number of scanlines that need processing.
                   7037: 
                   7038:  Arguments:
                   7039:     $scanlines - hash ref that looks like the first return value from
                   7040:                  &scantron_getfile()
                   7041:     $scan_data - hash ref that looks like the second return value from
                   7042:                  &scantron_getfile()
                   7043: 
                   7044:  Returns:
                   7045:     $count - number of scanlines to process
                   7046: 
1.423     albertel 7047: =cut
                   7048: 
1.200     albertel 7049: sub get_todo_count {
                   7050:     my ($scanlines,$scan_data)=@_;
                   7051:     my $count=0;
                   7052:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7053: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7054: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7055: 	$count++;
                   7056:     }
                   7057:     return $count;
                   7058: }
                   7059: 
1.423     albertel 7060: =pod
                   7061: 
                   7062: =item scantron_put_line
                   7063: 
1.659     raeburn  7064:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7065:     data file.
                   7066: 
                   7067:  Arguments:
                   7068:     $scanlines - hash ref that looks like the first return value from
                   7069:                  &scantron_getfile()
                   7070:     $scan_data - hash ref that looks like the second return value from
                   7071:                  &scantron_getfile()
                   7072:     $i         - line number to update
                   7073:     $newline   - contents of the updated scanline
                   7074:     $skip      - if true make the line for skipping and update the
                   7075:                  'skipped' file
                   7076: 
1.423     albertel 7077: =cut
                   7078: 
1.157     albertel 7079: sub scantron_put_line {
1.200     albertel 7080:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7081:     if ($skip) {
                   7082: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7083: 	&start_skipping($scan_data,$i);
1.157     albertel 7084: 	return;
                   7085:     }
                   7086:     $scanlines->{'corrected'}[$i]=$newline;
                   7087: }
                   7088: 
1.423     albertel 7089: =pod
                   7090: 
                   7091: =item scantron_clear_skip
                   7092: 
1.424     albertel 7093:    Remove a line from the 'skipped' 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: 
1.423     albertel 7102: =cut
                   7103: 
1.376     albertel 7104: sub scantron_clear_skip {
                   7105:     my ($scanlines,$scan_data,$i)=@_;
                   7106:     if (exists($scanlines->{'skipped'}[$i])) {
                   7107: 	undef($scanlines->{'skipped'}[$i]);
                   7108: 	return 1;
                   7109:     }
                   7110:     return 0;
                   7111: }
                   7112: 
1.423     albertel 7113: =pod
                   7114: 
                   7115: =item scantron_filter_not_exam
                   7116: 
1.424     albertel 7117:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7118:    filter out resources that are not marked as 'exam' mode
                   7119: 
1.423     albertel 7120: =cut
                   7121: 
1.334     albertel 7122: sub scantron_filter_not_exam {
                   7123:     my ($curres)=@_;
                   7124:     
                   7125:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7126: 	# if the user has asked to not have either hidden
                   7127: 	# or 'randomout' controlled resources to be graded
                   7128: 	# don't include them
                   7129: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7130: 	    && $curres->randomout) {
                   7131: 	    return 0;
                   7132: 	}
                   7133: 	return 1;
                   7134:     }
                   7135:     return 0;
                   7136: }
                   7137: 
1.423     albertel 7138: =pod
                   7139: 
                   7140: =item scantron_validate_sequence
                   7141: 
1.424     albertel 7142:     Validates the selected sequence, checking for resource that are
                   7143:     not set to exam mode.
                   7144: 
1.423     albertel 7145: =cut
                   7146: 
1.334     albertel 7147: sub scantron_validate_sequence {
                   7148:     my ($r,$currentphase) = @_;
                   7149: 
                   7150:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7151:     unless (ref($navmap)) {
                   7152:         $r->print(&navmap_errormsg());
                   7153:         return (1,$currentphase);
                   7154:     }
1.334     albertel 7155:     my (undef,undef,$sequence)=
                   7156: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7157: 
                   7158:     my $map=$navmap->getResourceByUrl($sequence);
                   7159: 
                   7160:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7161:                                     value="ignore" />');
                   7162:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7163: 	my @resources=
                   7164: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7165: 	if (@resources) {
1.675     bisitz   7166: 	    $r->print(
                   7167:                 '<p class="LC_warning">'
                   7168:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7169:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7170:                    .' work correctly.')
                   7171:                .'</p>'
                   7172:             );
1.334     albertel 7173: 	    return (1,$currentphase);
                   7174: 	}
                   7175:     }
                   7176: 
                   7177:     return (0,$currentphase+1);
                   7178: }
                   7179: 
1.423     albertel 7180: 
                   7181: 
1.157     albertel 7182: sub scantron_validate_ID {
                   7183:     my ($r,$currentphase) = @_;
                   7184:     
                   7185:     #get student info
                   7186:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7187:     my %idmap=&username_to_idmap($classlist);
                   7188: 
                   7189:     #get scantron line setup
1.257     albertel 7190:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7191:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7192: 
                   7193:     my $nav_error;
1.649     raeburn  7194:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7195:     if ($nav_error) {
                   7196:         $r->print(&navmap_errormsg());
                   7197:         return(1,$currentphase);
                   7198:     }
1.157     albertel 7199: 
                   7200:     my %found=('ids'=>{},'usernames'=>{});
                   7201:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7202: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7203: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7204: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7205: 						 $scan_data);
                   7206: 	my $id=$$scan_record{'scantron.ID'};
                   7207: 	my $found;
                   7208: 	foreach my $checkid (keys(%idmap)) {
                   7209: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7210: 	}
                   7211: 	if ($found) {
                   7212: 	    my $username=$idmap{$found};
                   7213: 	    if ($found{'ids'}{$found}) {
                   7214: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7215: 					 $line,'duplicateID',$found);
1.194     albertel 7216: 		return(1,$currentphase);
1.157     albertel 7217: 	    } elsif ($found{'usernames'}{$username}) {
                   7218: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7219: 					 $line,'duplicateID',$username);
1.194     albertel 7220: 		return(1,$currentphase);
1.157     albertel 7221: 	    }
1.186     albertel 7222: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7223: 	    $found{'ids'}{$found}++;
                   7224: 	    $found{'usernames'}{$username}++;
                   7225: 	} else {
                   7226: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7227: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7228: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7229: 		    &scantron_get_correction($r,$i,$scan_record,
                   7230: 					     \%scantron_config,
                   7231: 					     $line,'duplicateID',$username);
1.194     albertel 7232: 		    return(1,$currentphase);
1.157     albertel 7233: 		} elsif (!defined($username)) {
                   7234: 		    &scantron_get_correction($r,$i,$scan_record,
                   7235: 					     \%scantron_config,
                   7236: 					     $line,'incorrectID');
1.194     albertel 7237: 		    return(1,$currentphase);
1.157     albertel 7238: 		}
                   7239: 		$found{'usernames'}{$username}++;
                   7240: 	    } else {
                   7241: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7242: 					 $line,'incorrectID');
1.194     albertel 7243: 		return(1,$currentphase);
1.157     albertel 7244: 	    }
                   7245: 	}
                   7246:     }
                   7247: 
                   7248:     return (0,$currentphase+1);
                   7249: }
                   7250: 
1.423     albertel 7251: 
1.157     albertel 7252: sub scantron_get_correction {
1.691     raeburn  7253:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7254:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7255: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7256: #to show both the current line and the previous one and allow skipping
                   7257: #the previous one or the current one
                   7258: 
1.333     albertel 7259:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7260:         $r->print(
                   7261:             '<p class="LC_warning">'
                   7262:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7263:                 "<b>$error</b>",
                   7264:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7265:            ."</p> \n");
1.157     albertel 7266:     } else {
1.658     bisitz   7267:         $r->print(
                   7268:             '<p class="LC_warning">'
                   7269:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7270:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7271:            ."</p> \n");
                   7272:     }
                   7273:     my $message =
                   7274:         '<p>'
                   7275:        .&mt('The ID on the form is [_1]',
                   7276:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7277:        .'<br />'
1.665     raeburn  7278:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7279:             $$scan_record{'scantron.LastName'},
                   7280:             $$scan_record{'scantron.FirstName'})
                   7281:        .'</p>';
1.242     albertel 7282: 
1.157     albertel 7283:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7284:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7285:                            # Array populated for doublebubble or
                   7286:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7287:                            # to validate radio button checking   
                   7288: 
1.157     albertel 7289:     if ($error =~ /ID$/) {
1.186     albertel 7290: 	if ($error eq 'incorrectID') {
1.658     bisitz   7291:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7292: 		      "</p>\n");
1.157     albertel 7293: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7294:             $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 7295: 	}
1.242     albertel 7296: 	$r->print($message);
1.492     albertel 7297: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7298: 	$r->print("\n<ul><li> ");
                   7299: 	#FIXME it would be nice if this sent back the user ID and
                   7300: 	#could do partial userID matches
                   7301: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7302: 				       'scantron_username','scantron_domain'));
                   7303: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7304: 	$r->print("\n:\n".
1.257     albertel 7305: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7306: 
                   7307: 	$r->print('</li>');
1.186     albertel 7308:     } elsif ($error =~ /CODE$/) {
                   7309: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7310: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7311: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7312: 	    $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 7313: 	}
1.658     bisitz   7314: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7315: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7316:                  ."</p>\n");
1.242     albertel 7317: 	$r->print($message);
1.658     bisitz   7318: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7319: 	$r->print("\n<br /> ");
1.194     albertel 7320: 	my $i=0;
1.273     albertel 7321: 	if ($error eq 'incorrectCODE' 
                   7322: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7323: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7324: 	    if ($closest > 0) {
                   7325: 		foreach my $testcode (@{$closest}) {
                   7326: 		    my $checked='';
1.569     bisitz   7327: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7328: 		    $r->print("
                   7329:    <label>
1.569     bisitz   7330:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7331:        ".&mt("Use the similar CODE [_1] instead.",
                   7332: 	    "<b><tt>".$testcode."</tt></b>")."
                   7333:     </label>
                   7334:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7335: 		    $r->print("\n<br />");
                   7336: 		    $i++;
                   7337: 		}
1.194     albertel 7338: 	    }
                   7339: 	}
1.273     albertel 7340: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7341: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7342: 	    $r->print("
                   7343:     <label>
1.569     bisitz   7344:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7345:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7346: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7347:     </label>");
1.273     albertel 7348: 	    $r->print("\n<br />");
                   7349: 	}
1.194     albertel 7350: 
1.597     wenzelju 7351: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7352: function change_radio(field) {
1.190     albertel 7353:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7354:     var i;
                   7355:     for (i=0;i<slct.length;i++) {
                   7356:         if (slct[i].value==field) { slct[i].checked=true; }
                   7357:     }
                   7358: }
                   7359: ENDSCRIPT
1.187     albertel 7360: 	my $href="/adm/pickcode?".
1.359     www      7361: 	   "form=".&escape("scantronupload").
                   7362: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7363: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7364: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7365: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7366: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7367: 	    $r->print("
                   7368:     <label>
                   7369:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7370:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7371: 	     "<a target='_blank' href='$href'>","</a>")."
                   7372:     </label> 
1.558     bisitz   7373:     ".&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 7374: 	    $r->print("\n<br />");
                   7375: 	}
1.492     albertel 7376: 	$r->print("
                   7377:     <label>
                   7378:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7379:        ".&mt("Use [_1] as the CODE.",
                   7380: 	     "</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 7381: 	$r->print("\n<br /><br />");
1.157     albertel 7382:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7383: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7384: 
                   7385: 	# The form field scantron_questions is acutally a list of line numbers.
                   7386: 	# represented by this form so:
                   7387: 
1.691     raeburn  7388: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7389:                                                 $respnumlookup,$startline);
1.497     foxr     7390: 
1.157     albertel 7391: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7392: 		  $line_list.'" />');
1.242     albertel 7393: 	$r->print($message);
1.492     albertel 7394: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7395: 	foreach my $question (@{$arg}) {
1.503     raeburn  7396: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7397:                                                    $scan_record, $error,
                   7398:                                                    $randomorder,$randompick,
                   7399:                                                    $respnumlookup,$startline);
1.524     raeburn  7400:             push(@lines_to_correct,@linenums);
1.157     albertel 7401: 	}
1.503     raeburn  7402:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7403:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7404: 	$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 7405: 	$r->print($message);
1.492     albertel 7406: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7407: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7408: 
1.503     raeburn  7409: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7410: 	# a list of question numbers. Therefore:
                   7411: 	#
1.691     raeburn  7412: 
                   7413: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7414:                                                 $respnumlookup,$startline);
1.497     foxr     7415: 
1.157     albertel 7416: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7417: 		  $line_list.'" />');
1.157     albertel 7418: 	foreach my $question (@{$arg}) {
1.503     raeburn  7419: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7420:                                                    $scan_record, $error,
                   7421:                                                    $randomorder,$randompick,
                   7422:                                                    $respnumlookup,$startline);
1.524     raeburn  7423:             push(@lines_to_correct,@linenums);
1.157     albertel 7424: 	}
1.503     raeburn  7425:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7426:     } else {
                   7427: 	$r->print("\n<ul>");
                   7428:     }
                   7429:     $r->print("\n</li></ul>");
1.497     foxr     7430: }
                   7431: 
1.503     raeburn  7432: sub verify_bubbles_checked {
                   7433:     my (@ansnums) = @_;
                   7434:     my $ansnumstr = join('","',@ansnums);
                   7435:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7436:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7437: function verify_bubble_radio(form) {
                   7438:     var ansnumArray = new Array ("$ansnumstr");
                   7439:     var need_bubble_count = 0;
                   7440:     for (var i=0; i<ansnumArray.length; i++) {
                   7441:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7442:             var bubble_picked = 0; 
                   7443:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7444:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7445:                     bubble_picked = 1;
                   7446:                 }
                   7447:             }
                   7448:             if (bubble_picked == 0) {
                   7449:                 need_bubble_count ++;
                   7450:             }
                   7451:         }
                   7452:     }
                   7453:     if (need_bubble_count) {
                   7454:         alert("$warning");
                   7455:         return;
                   7456:     }
                   7457:     form.submit(); 
                   7458: }
                   7459: ENDSCRIPT
                   7460:     return $output;
                   7461: }
                   7462: 
1.497     foxr     7463: =pod
                   7464: 
                   7465: =item  questions_to_line_list
1.157     albertel 7466: 
1.497     foxr     7467: Converts a list of questions into a string of comma separated
                   7468: line numbers in the answer sheet used by the questions.  This is
                   7469: used to fill in the scantron_questions form field.
                   7470: 
                   7471:   Arguments:
                   7472:      questions    - Reference to an array of questions.
1.691     raeburn  7473:      randomorder  - True if randomorder in use.
                   7474:      randompick   - True if randompick in use.
                   7475:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7476:                      for current line to question number used for same question
                   7477:                      in "Master Seqence" (as seen by Course Coordinator).
                   7478:      startline    - Reference to hash where key is question number (0 is first)
                   7479:                     and key is number of first bubble line for current student
                   7480:                     or code-based randompick and/or randomorder.
1.693     raeburn  7481: 
1.497     foxr     7482: =cut
                   7483: 
                   7484: 
                   7485: sub questions_to_line_list {
1.691     raeburn  7486:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7487:     my @lines;
                   7488: 
1.503     raeburn  7489:     foreach my $item (@{$questions}) {
                   7490:         my $question = $item;
                   7491:         my ($first,$count,$last);
                   7492:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7493:             $question = $1;
                   7494:             my $subquestion = $2;
1.691     raeburn  7495:             my $responsenum = $question-1;
                   7496:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7497:                 $responsenum = $respnumlookup->{$question-1};
                   7498:                 if (ref($startline) eq 'HASH') {
                   7499:                     $first = $startline->{$question-1} + 1;
                   7500:                 }
                   7501:             } else {
                   7502:                 $first = $first_bubble_line{$responsenum} + 1;
                   7503:             }
                   7504:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7505:             my $subcount = 1;
                   7506:             while ($subcount<$subquestion) {
                   7507:                 $first += $subans[$subcount-1];
                   7508:                 $subcount ++;
                   7509:             }
                   7510:             $count = $subans[$subquestion-1];
                   7511:         } else {
1.691     raeburn  7512:             my $responsenum = $question-1;
                   7513:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7514:                 $responsenum = $respnumlookup->{$question-1};
                   7515:                 if (ref($startline) eq 'HASH') {
                   7516:                     $first = $startline->{$question-1} + 1;
                   7517:                 }
                   7518:             } else {
                   7519:                 $first = $first_bubble_line{$responsenum} + 1;
                   7520:             }
                   7521: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7522:         }
1.506     raeburn  7523:         $last = $first+$count-1;
1.503     raeburn  7524:         push(@lines, ($first..$last));
1.497     foxr     7525:     }
                   7526:     return join(',', @lines);
                   7527: }
                   7528: 
                   7529: =pod 
                   7530: 
                   7531: =item prompt_for_corrections
                   7532: 
                   7533: Prompts for a potentially multiline correction to the
                   7534: user's bubbling (factors out common code from scantron_get_correction
                   7535: for multi and missing bubble cases).
                   7536: 
                   7537:  Arguments:
                   7538:    $r           - Apache request object.
                   7539:    $question    - The question number to prompt for.
                   7540:    $scan_config - The scantron file configuration hash.
                   7541:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7542:    $error       - Type of error
1.691     raeburn  7543:    $randomorder - True if randomorder in use.
                   7544:    $randompick  - True if randompick in use.
                   7545:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7546:                     for current line to question number used for same question
                   7547:                     in "Master Seqence" (as seen by Course Coordinator).
                   7548:    $startline   - Reference to hash where key is question number (0 is first)
                   7549:                   and value is number of first bubble line for current student
                   7550:                   or code-based randompick and/or randomorder.
                   7551: 
1.497     foxr     7552: 
                   7553:  Implicit inputs:
                   7554:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7555:                                   Numbered from 0 (but question numbers are from
                   7556:                                   1.
                   7557:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7558:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7559:                                   type problems render as separate sub-questions, 
1.503     raeburn  7560:                                   in exam mode. This hash contains a 
                   7561:                                   comma-separated list of the lines per 
                   7562:                                   sub-question.
1.510     raeburn  7563:    %responsetype_per_response   - essayresponse, formularesponse,
                   7564:                                   stringresponse, imageresponse, reactionresponse,
                   7565:                                   and organicresponse type problem parts can have
1.503     raeburn  7566:                                   multiple lines per response if the weight
                   7567:                                   assigned exceeds 10.  In this case, only
                   7568:                                   one bubble per line is permitted, but more 
                   7569:                                   than one line might contain bubbles, e.g.
                   7570:                                   bubbling of: line 1 - J, line 2 - J, 
                   7571:                                   line 3 - B would assign 22 points.  
1.497     foxr     7572: 
                   7573: =cut
                   7574: 
                   7575: sub prompt_for_corrections {
1.691     raeburn  7576:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7577:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7578:     my ($current_line,$lines);
                   7579:     my @linenums;
                   7580:     my $questionnum = $question;
1.691     raeburn  7581:     my ($first,$responsenum);
1.503     raeburn  7582:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7583:         $question = $1;
                   7584:         my $subquestion = $2;
1.691     raeburn  7585:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7586:             $responsenum = $respnumlookup->{$question-1};
                   7587:             if (ref($startline) eq 'HASH') {
                   7588:                 $first = $startline->{$question-1};
                   7589:             }
                   7590:         } else {
                   7591:             $responsenum = $question-1;
1.714     raeburn  7592:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7593:         }
                   7594:         $current_line = $first + 1 ;
                   7595:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7596:         my $subcount = 1;
                   7597:         while ($subcount<$subquestion) {
                   7598:             $current_line += $subans[$subcount-1];
                   7599:             $subcount ++;
                   7600:         }
                   7601:         $lines = $subans[$subquestion-1];
                   7602:     } else {
1.691     raeburn  7603:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7604:             $responsenum = $respnumlookup->{$question-1};
                   7605:             if (ref($startline) eq 'HASH') { 
                   7606:                 $first = $startline->{$question-1};
                   7607:             }
                   7608:         } else {
                   7609:             $responsenum = $question-1;
                   7610:             $first = $first_bubble_line{$responsenum};
                   7611:         }
                   7612:         $current_line = $first + 1;
                   7613:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7614:     }
1.497     foxr     7615:     if ($lines > 1) {
1.503     raeburn  7616:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7617:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7618:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7619:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7620:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7621:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7622:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7623:             $r->print(
                   7624:                 &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)
                   7625:                .'<br /><br />'
                   7626:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7627:                .'<br />'
                   7628:                .&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.')
                   7629:                .'<br />'
                   7630:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7631:                .'<br /><br />'
                   7632:             );
1.503     raeburn  7633:         } else {
                   7634:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7635:         }
1.497     foxr     7636:     }
                   7637:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7638:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7639: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7640: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7641:         push(@linenums,$current_line);
1.497     foxr     7642: 	$current_line++;
                   7643:     }
                   7644:     if ($lines > 1) {
                   7645: 	$r->print("<hr /><br />");
                   7646:     }
1.503     raeburn  7647:     return @linenums;
1.157     albertel 7648: }
1.423     albertel 7649: 
                   7650: =pod
                   7651: 
                   7652: =item scantron_bubble_selector
                   7653:   
                   7654:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7655:    possibly showing the existing the selected bubbles if known
1.423     albertel 7656: 
                   7657:  Arguments:
                   7658:     $r           - Apache request object
                   7659:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7660:     $line        - Number of the line being displayed.
1.503     raeburn  7661:     $questionnum - Question number (may include subquestion)
                   7662:     $error       - Type of error.
1.497     foxr     7663:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7664: 
                   7665: =cut
                   7666: 
1.157     albertel 7667: sub scantron_bubble_selector {
1.503     raeburn  7668:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7669:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7670: 
                   7671:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7672:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7673:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7674:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7675:             $max=$$scan_config{'BubblesPerRow'};
                   7676:             if (($scmode eq 'number') && ($max > 10)) {
                   7677:                 $max = 10;
                   7678:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7679:                 $max = 26;
                   7680:             }
                   7681:         } else {
                   7682:             $max = 10;
                   7683:         }
                   7684:     }
1.274     albertel 7685: 
1.157     albertel 7686:     my @alphabet=('A'..'Z');
1.503     raeburn  7687:     $r->print(&Apache::loncommon::start_data_table().
                   7688:               &Apache::loncommon::start_data_table_row());
                   7689:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7690:     for (my $i=0;$i<$max+1;$i++) {
                   7691: 	$r->print("\n".'<td align="center">');
                   7692: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7693: 	else { $r->print('&nbsp;'); }
                   7694: 	$r->print('</td>');
                   7695:     }
1.503     raeburn  7696:     $r->print(&Apache::loncommon::end_data_table_row().
                   7697:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7698:     for (my $i=0;$i<$max;$i++) {
                   7699: 	$r->print("\n".
                   7700: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7701: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7702:     }
1.503     raeburn  7703:     my $nobub_checked = ' ';
                   7704:     if ($error eq 'missingbubble') {
                   7705:         $nobub_checked = ' checked = "checked" ';
                   7706:     }
                   7707:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7708: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7709:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7710:               $line.'" value="'.$questionnum.'" /></td>');
                   7711:     $r->print(&Apache::loncommon::end_data_table_row().
                   7712:               &Apache::loncommon::end_data_table());
1.157     albertel 7713: }
                   7714: 
1.423     albertel 7715: =pod
                   7716: 
                   7717: =item num_matches
                   7718: 
1.424     albertel 7719:    Counts the number of characters that are the same between the two arguments.
                   7720: 
                   7721:  Arguments:
                   7722:    $orig - CODE from the scanline
                   7723:    $code - CODE to match against
                   7724: 
                   7725:  Returns:
                   7726:    $count - integer count of the number of same characters between the
                   7727:             two arguments
                   7728: 
1.423     albertel 7729: =cut
                   7730: 
1.194     albertel 7731: sub num_matches {
                   7732:     my ($orig,$code) = @_;
                   7733:     my @code=split(//,$code);
                   7734:     my @orig=split(//,$orig);
                   7735:     my $same=0;
                   7736:     for (my $i=0;$i<scalar(@code);$i++) {
                   7737: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7738:     }
                   7739:     return $same;
                   7740: }
                   7741: 
1.423     albertel 7742: =pod
                   7743: 
                   7744: =item scantron_get_closely_matching_CODEs
                   7745: 
1.424     albertel 7746:    Cycles through all CODEs and finds the set that has the greatest
                   7747:    number of same characters as the provided CODE
                   7748: 
                   7749:  Arguments:
                   7750:    $allcodes - hash ref returned by &get_codes()
                   7751:    $CODE     - CODE from the current scanline
                   7752: 
                   7753:  Returns:
                   7754:    2 element list
                   7755:     - first elements is number of how closely matching the best fit is 
                   7756:       (5 means best set has 5 matching characters)
                   7757:     - second element is an arrary ref containing the set of valid CODEs
                   7758:       that best fit the passed in CODE
                   7759: 
1.423     albertel 7760: =cut
                   7761: 
1.194     albertel 7762: sub scantron_get_closely_matching_CODEs {
                   7763:     my ($allcodes,$CODE)=@_;
                   7764:     my @CODEs;
                   7765:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7766: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7767:     }
                   7768: 
                   7769:     return ($#CODEs,$CODEs[-1]);
                   7770: }
                   7771: 
1.423     albertel 7772: =pod
                   7773: 
                   7774: =item get_codes
                   7775: 
1.424     albertel 7776:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7777:    set of remembered CODEs.
                   7778: 
                   7779:  Arguments:
                   7780:   $old_name - name of the set of remembered CODEs
                   7781:   $cdom     - domain of the course
                   7782:   $cnum     - internal course name
                   7783: 
                   7784:  Returns:
                   7785:   %allcodes - keys are the valid CODEs, values are all 1
                   7786: 
1.423     albertel 7787: =cut
                   7788: 
1.194     albertel 7789: sub get_codes {
1.280     foxr     7790:     my ($old_name, $cdom, $cnum) = @_;
                   7791:     if (!$old_name) {
                   7792: 	$old_name=$env{'form.scantron_CODElist'};
                   7793:     }
                   7794:     if (!$cdom) {
                   7795: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7796:     }
                   7797:     if (!$cnum) {
                   7798: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7799:     }
1.278     albertel 7800:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7801: 				    $cdom,$cnum);
                   7802:     my %allcodes;
                   7803:     if ($result{"type\0$old_name"} eq 'number') {
                   7804: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7805:     } else {
                   7806: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7807:     }
1.194     albertel 7808:     return %allcodes;
                   7809: }
                   7810: 
1.423     albertel 7811: =pod
                   7812: 
                   7813: =item scantron_validate_CODE
                   7814: 
1.424     albertel 7815:    Validates all scanlines in the selected file to not have any
                   7816:    invalid or underspecified CODEs and that none of the codes are
                   7817:    duplicated if this was requested.
                   7818: 
1.423     albertel 7819: =cut
                   7820: 
1.157     albertel 7821: sub scantron_validate_CODE {
                   7822:     my ($r,$currentphase) = @_;
1.257     albertel 7823:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7824:     if ($scantron_config{'CODElocation'} &&
                   7825: 	$scantron_config{'CODEstart'} &&
                   7826: 	$scantron_config{'CODElength'}) {
1.257     albertel 7827: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7828: 	    &FIXME_blow_up()
                   7829: 	}
                   7830:     } else {
                   7831: 	return (0,$currentphase+1);
                   7832:     }
                   7833:     
                   7834:     my %usedCODEs;
                   7835: 
1.194     albertel 7836:     my %allcodes=&get_codes();
1.186     albertel 7837: 
1.582     raeburn  7838:     my $nav_error;
1.649     raeburn  7839:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7840:     if ($nav_error) {
                   7841:         $r->print(&navmap_errormsg());
                   7842:         return(1,$currentphase);
                   7843:     }
1.447     foxr     7844: 
1.186     albertel 7845:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7846:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7847: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7848: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7849: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7850: 						 $scan_data);
                   7851: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7852: 	my $error=0;
1.224     albertel 7853: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7854: 	    &scantron_get_correction($r,$i,$scan_record,
                   7855: 				     \%scantron_config,
                   7856: 				     $line,'incorrectCODE',\%allcodes);
                   7857: 	    return(1,$currentphase);
                   7858: 	}
1.221     albertel 7859: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7860: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7861: 	    &scantron_get_correction($r,$i,$scan_record,
                   7862: 				     \%scantron_config,
1.194     albertel 7863: 				     $line,'incorrectCODE',\%allcodes);
                   7864: 	    return(1,$currentphase);
1.186     albertel 7865: 	}
1.214     albertel 7866: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7867: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7868: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7869: 	    &scantron_get_correction($r,$i,$scan_record,
                   7870: 				     \%scantron_config,
1.194     albertel 7871: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7872: 	    return(1,$currentphase);
1.186     albertel 7873: 	}
1.524     raeburn  7874: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7875:     }
1.157     albertel 7876:     return (0,$currentphase+1);
                   7877: }
                   7878: 
1.423     albertel 7879: =pod
                   7880: 
                   7881: =item scantron_validate_doublebubble
                   7882: 
1.424     albertel 7883:    Validates all scanlines in the selected file to not have any
                   7884:    bubble lines with multiple bubbles marked.
                   7885: 
1.423     albertel 7886: =cut
                   7887: 
1.157     albertel 7888: sub scantron_validate_doublebubble {
                   7889:     my ($r,$currentphase) = @_;
                   7890:     #get student info
                   7891:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7892:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7893:     my (undef,undef,$sequence)=
                   7894:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7895: 
                   7896:     #get scantron line setup
1.257     albertel 7897:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7898:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7899: 
                   7900:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7901:     unless (ref($navmap)) {
                   7902:         $r->print(&navmap_errormsg());
                   7903:         return(1,$currentphase);
                   7904:     }
                   7905:     my $map=$navmap->getResourceByUrl($sequence);
                   7906:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7907:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7908:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7909:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7910: 
1.583     raeburn  7911:     my $nav_error;
1.691     raeburn  7912:     if (ref($map)) {
                   7913:         $randomorder = $map->randomorder();
                   7914:         $randompick = $map->randompick();
                   7915:         if ($randomorder || $randompick) {
                   7916:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7917:             if ($nav_error) {
                   7918:                 $r->print(&navmap_errormsg());
                   7919:                 return(1,$currentphase);
                   7920:             }
                   7921:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7922:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7923:         }
                   7924:     } else {
                   7925:         $r->print(&navmap_errormsg());
                   7926:         return(1,$currentphase);
                   7927:     }
                   7928: 
1.649     raeburn  7929:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7930:     if ($nav_error) {
                   7931:         $r->print(&navmap_errormsg());
                   7932:         return(1,$currentphase);
                   7933:     }
1.447     foxr     7934: 
1.157     albertel 7935:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7936: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7937: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7938: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7939: 						 $scan_data,undef,\%idmap,$randomorder,
                   7940:                                                  $randompick,$sequence,\@master_seq,
                   7941:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7942:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7943: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7944: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7945: 				 'doublebubble',
1.691     raeburn  7946: 				 $$scan_record{'scantron.doubleerror'},
                   7947:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7948:     	return (1,$currentphase);
                   7949:     }
                   7950:     return (0,$currentphase+1);
                   7951: }
                   7952: 
1.423     albertel 7953: 
1.503     raeburn  7954: sub scantron_get_maxbubble {
1.649     raeburn  7955:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7956:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7957: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7958: 	&restore_bubble_lines();
1.257     albertel 7959: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7960:     }
1.330     albertel 7961: 
1.447     foxr     7962:     my (undef, undef, $sequence) =
1.257     albertel 7963: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7964: 
1.447     foxr     7965:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7966:     unless (ref($navmap)) {
                   7967:         if (ref($nav_error)) {
                   7968:             $$nav_error = 1;
                   7969:         }
1.591     raeburn  7970:         return;
1.582     raeburn  7971:     }
1.191     albertel 7972:     my $map=$navmap->getResourceByUrl($sequence);
                   7973:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7974:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7975: 
                   7976:     &Apache::lonxml::clear_problem_counter();
                   7977: 
1.557     raeburn  7978:     my $uname       = $env{'user.name'};
                   7979:     my $udom        = $env{'user.domain'};
1.435     foxr     7980:     my $cid         = $env{'request.course.id'};
                   7981:     my $total_lines = 0;
                   7982:     %bubble_lines_per_response = ();
1.447     foxr     7983:     %first_bubble_line         = ();
1.503     raeburn  7984:     %subdivided_bubble_lines   = ();
                   7985:     %responsetype_per_response = ();
1.691     raeburn  7986:     %masterseq_id_responsenum  = ();
1.554     raeburn  7987: 
1.447     foxr     7988:     my $response_number = 0;
                   7989:     my $bubble_line     = 0;
1.191     albertel 7990:     foreach my $resource (@resources) {
1.691     raeburn  7991:         my $resid = $resource->id(); 
1.672     raeburn  7992:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7993:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  7994:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7995: 	    foreach my $part_id (@{$parts}) {
                   7996:                 my $lines;
                   7997: 
                   7998: 	        # TODO - make this a persistent hash not an array.
                   7999: 
                   8000:                 # optionresponse, matchresponse and rankresponse type items 
                   8001:                 # render as separate sub-questions in exam mode.
                   8002:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8003:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8004:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8005:                     my ($numbub,$numshown);
                   8006:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8007:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8008:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8009:                         }
                   8010:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8011:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8012:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8013:                         }
                   8014:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8015:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8016:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8017:                         }
                   8018:                     }
                   8019:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8020:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8021:                     }
1.649     raeburn  8022:                     my $bubbles_per_row =
                   8023:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8024:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8025:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8026:                         $inner_bubble_lines++;
                   8027:                     }
                   8028:                     for (my $i=0; $i<$numshown; $i++) {
                   8029:                         $subdivided_bubble_lines{$response_number} .= 
                   8030:                             $inner_bubble_lines.',';
                   8031:                     }
                   8032:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8033:                     $lines = $numshown * $inner_bubble_lines;
                   8034:                 } else {
                   8035:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8036:                 }
1.542     raeburn  8037: 
                   8038:                 $first_bubble_line{$response_number} = $bubble_line;
                   8039: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8040:                 $responsetype_per_response{$response_number} = 
                   8041:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8042:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8043: 	        $response_number++;
                   8044: 
                   8045: 	        $bubble_line +=  $lines;
                   8046: 	        $total_lines +=  $lines;
                   8047: 	    }
                   8048:         }
                   8049:     }
1.552     raeburn  8050:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8051: 
                   8052:     &save_bubble_lines();
                   8053:     $env{'form.scantron_maxbubble'} =
                   8054: 	$total_lines;
                   8055:     return $env{'form.scantron_maxbubble'};
                   8056: }
1.523     raeburn  8057: 
1.649     raeburn  8058: sub bubblesheet_bubbles_per_row {
                   8059:     my ($scantron_config) = @_;
                   8060:     my $bubbles_per_row;
                   8061:     if (ref($scantron_config) eq 'HASH') {
                   8062:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8063:     }
                   8064:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8065:         $bubbles_per_row = 10;
                   8066:     }
                   8067:     return $bubbles_per_row;
                   8068: }
                   8069: 
1.157     albertel 8070: sub scantron_validate_missingbubbles {
                   8071:     my ($r,$currentphase) = @_;
                   8072:     #get student info
                   8073:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8074:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8075:     my (undef,undef,$sequence)=
                   8076:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8077: 
                   8078:     #get scantron line setup
1.257     albertel 8079:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8080:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8081: 
                   8082:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8083:     unless (ref($navmap)) {
                   8084:         $r->print(&navmap_errormsg());
                   8085:         return(1,$currentphase);
                   8086:     }
                   8087: 
                   8088:     my $map=$navmap->getResourceByUrl($sequence);
                   8089:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8090:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8091:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8092:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8093: 
1.582     raeburn  8094:     my $nav_error;
1.691     raeburn  8095:     if (ref($map)) {
                   8096:         $randomorder = $map->randomorder();
                   8097:         $randompick = $map->randompick();
                   8098:         if ($randomorder || $randompick) {
                   8099:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8100:             if ($nav_error) {
                   8101:                 $r->print(&navmap_errormsg());
                   8102:                 return(1,$currentphase);
                   8103:             }
                   8104:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8105:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8106:         }
                   8107:     } else {
                   8108:         $r->print(&navmap_errormsg());
                   8109:         return(1,$currentphase);
                   8110:     }
                   8111: 
                   8112: 
1.649     raeburn  8113:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8114:     if ($nav_error) {
1.691     raeburn  8115:         $r->print(&navmap_errormsg());
1.693     raeburn  8116:         return(1,$currentphase);
1.582     raeburn  8117:     }
1.691     raeburn  8118: 
1.157     albertel 8119:     if (!$max_bubble) { $max_bubble=2**31; }
                   8120:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8121: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8122: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8123: 	my $scan_record =
                   8124:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8125: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8126:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8127:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8128: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8129: 	my @to_correct;
1.470     foxr     8130: 	
                   8131: 	# Probably here's where the error is...
                   8132: 
1.157     albertel 8133: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8134:             my $lastbubble;
                   8135:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8136:                my $question = $1;
                   8137:                my $subquestion = $2;
1.691     raeburn  8138:                my ($first,$responsenum);
                   8139:                if ($randomorder || $randompick) {
                   8140:                    $responsenum = $respnumlookup{$question-1};
                   8141:                    $first = $startline{$question-1};
                   8142:                } else {
                   8143:                    $responsenum = $question-1; 
                   8144:                    $first = $first_bubble_line{$responsenum};
                   8145:                }
                   8146:                if (!defined($first)) { next; }
                   8147:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8148:                my $subcount = 1;
                   8149:                while ($subcount<$subquestion) {
                   8150:                    $first += $subans[$subcount-1];
                   8151:                    $subcount ++;
                   8152:                }
                   8153:                my $count = $subans[$subquestion-1];
                   8154:                $lastbubble = $first + $count;
                   8155:             } else {
1.691     raeburn  8156:                my ($first,$responsenum);
                   8157:                if ($randomorder || $randompick) {
                   8158:                    $responsenum = $respnumlookup{$missing-1};
                   8159:                    $first = $startline{$missing-1};
                   8160:                } else {
                   8161:                    $responsenum = $missing-1;
                   8162:                    $first = $first_bubble_line{$responsenum};
                   8163:                }
                   8164:                if (!defined($first)) { next; }
                   8165:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8166:             }
                   8167:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8168: 	    push(@to_correct,$missing);
                   8169: 	}
                   8170: 	if (@to_correct) {
                   8171: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8172: 				     $line,'missingbubble',\@to_correct,
                   8173:                                      $randomorder,$randompick,\%respnumlookup,
                   8174:                                      \%startline);
1.157     albertel 8175: 	    return (1,$currentphase);
                   8176: 	}
                   8177: 
                   8178:     }
                   8179:     return (0,$currentphase+1);
                   8180: }
                   8181: 
1.663     raeburn  8182: sub hand_bubble_option {
                   8183:     my (undef, undef, $sequence) =
                   8184:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8185:     return if ($sequence eq '');
                   8186:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8187:     unless (ref($navmap)) {
                   8188:         return;
                   8189:     }
                   8190:     my $needs_hand_bubbles;
                   8191:     my $map=$navmap->getResourceByUrl($sequence);
                   8192:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8193:     foreach my $res (@resources) {
                   8194:         if (ref($res)) {
                   8195:             if ($res->is_problem()) {
                   8196:                 my $partlist = $res->parts();
                   8197:                 foreach my $part (@{ $partlist }) {
                   8198:                     my @types = $res->responseType($part);
                   8199:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8200:                         $needs_hand_bubbles = 1;
                   8201:                         last;
                   8202:                     }
                   8203:                 }
                   8204:             }
                   8205:         }
                   8206:     }
                   8207:     if ($needs_hand_bubbles) {
                   8208:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8209:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8210:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8211:                &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 />').
                   8212:                '<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;'.
                   8213:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8214:     }
                   8215:     return;
                   8216: }
1.423     albertel 8217: 
1.82      albertel 8218: sub scantron_process_students {
1.608     www      8219:     my ($r,$symb) = @_;
1.513     foxr     8220: 
1.257     albertel 8221:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8222:     if (!$symb) {
                   8223: 	return '';
                   8224:     }
1.324     albertel 8225:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8226: 
1.257     albertel 8227:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8228:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8229:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8230:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8231:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8232:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8233:     unless (ref($navmap)) {
                   8234:         $r->print(&navmap_errormsg());
                   8235:         return '';
1.691     raeburn  8236:     }
1.83      albertel 8237:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8238:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8239:         %grader_randomlists_by_symb);
1.677     raeburn  8240:     if (ref($map)) {
                   8241:         $randomorder = $map->randomorder();
1.689     raeburn  8242:         $randompick = $map->randompick();
1.691     raeburn  8243:     } else {
                   8244:         $r->print(&navmap_errormsg());
                   8245:         return '';
1.677     raeburn  8246:     }
1.691     raeburn  8247:     my $nav_error;
1.83      albertel 8248:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8249:     if ($randomorder || $randompick) {
                   8250:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8251:         if ($nav_error) {
                   8252:             $r->print(&navmap_errormsg());
                   8253:             return '';
                   8254:         }
                   8255:     }
1.557     raeburn  8256:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8257:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8258: 
1.554     raeburn  8259:     my ($uname,$udom);
1.82      albertel 8260:     my $result= <<SCANTRONFORM;
1.81      albertel 8261: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8262:   <input type="hidden" name="command" value="scantron_configphase" />
                   8263:   $default_form_data
                   8264: SCANTRONFORM
1.82      albertel 8265:     $r->print($result);
                   8266: 
                   8267:     my @delayqueue;
1.542     raeburn  8268:     my (%completedstudents,%scandata);
1.140     albertel 8269:     
1.520     www      8270:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8271:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8272:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8273:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8274:     $r->print('<br />');
1.140     albertel 8275:     my $start=&Time::HiRes::time();
1.158     albertel 8276:     my $i=-1;
1.542     raeburn  8277:     my $started;
1.447     foxr     8278: 
1.649     raeburn  8279:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8280:     if ($nav_error) {
                   8281:         $r->print(&navmap_errormsg());
                   8282:         return '';
                   8283:     }
                   8284: 
1.513     foxr     8285:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8286:     # the user and return.
                   8287: 
                   8288:     if ($ssi_error) {
                   8289: 	$r->print("</form>");
                   8290: 	&ssi_print_error($r);
1.520     www      8291:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8292: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8293:     }
1.447     foxr     8294: 
1.542     raeburn  8295:     my %lettdig = &letter_to_digits();
                   8296:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8297:     my %orderedforcode;
1.542     raeburn  8298: 
1.157     albertel 8299:     while ($i<$scanlines->{'count'}) {
                   8300:  	($uname,$udom)=('','');
                   8301:  	$i++;
1.200     albertel 8302:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8303:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8304: 	if ($started) {
1.667     www      8305: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8306: 	}
                   8307: 	$started=1;
1.691     raeburn  8308:         my %respnumlookup = ();
                   8309:         my %startline = ();
                   8310:         my $total;
1.157     albertel 8311:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8312:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8313:                                                  $randompick,$sequence,\@master_seq,
                   8314:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8315:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8316:                                                  \$total);
1.157     albertel 8317:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8318:  					      \%idmap,$i)) {
                   8319:   	    &scantron_add_delay(\@delayqueue,$line,
                   8320:  				'Unable to find a student that matches',1);
                   8321:  	    next;
                   8322:   	}
                   8323:  	if (exists $completedstudents{$uname}) {
                   8324:  	    &scantron_add_delay(\@delayqueue,$line,
                   8325:  				'Student '.$uname.' has multiple sheets',2);
                   8326:  	    next;
                   8327:  	}
1.677     raeburn  8328:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8329:         my $user = $uname.':'.$usec;
1.157     albertel 8330:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8331: 
1.677     raeburn  8332:         my $scancode;
                   8333:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8334:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8335:             $scancode = $scan_record->{'scantron.CODE'};
                   8336:         } else {
                   8337:             $scancode = '';
                   8338:         }
                   8339: 
                   8340:         my @mapresources = @resources;
1.689     raeburn  8341:         if ($randomorder || $randompick) {
1.678     raeburn  8342:             @mapresources = 
1.691     raeburn  8343:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8344:                              \%orderedforcode);
1.677     raeburn  8345:         }
1.586     raeburn  8346:         my (%partids_by_symb,$res_error);
1.677     raeburn  8347:         foreach my $resource (@mapresources) {
1.586     raeburn  8348:             my $ressymb;
                   8349:             if (ref($resource)) {
                   8350:                 $ressymb = $resource->symb();
                   8351:             } else {
                   8352:                 $res_error = 1;
                   8353:                 last;
                   8354:             }
1.557     raeburn  8355:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8356:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8357:                 my ($analysis,$parts) =
1.672     raeburn  8358:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8359:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8360:                 $partids_by_symb{$ressymb} = $parts;
                   8361:             } else {
                   8362:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8363:             }
1.554     raeburn  8364:         }
                   8365: 
1.586     raeburn  8366:         if ($res_error) {
                   8367:             &scantron_add_delay(\@delayqueue,$line,
                   8368:                                 'An error occurred while grading student '.$uname,2);
                   8369:             next;
                   8370:         }
                   8371: 
1.330     albertel 8372: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8373:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8374: 
                   8375: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8376: 	    &scantron_putfile($scanlines,$scan_data);
                   8377: 	}
1.161     albertel 8378: 	
1.542     raeburn  8379:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8380:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8381:                                    $bubbles_per_row,$randomorder,$randompick,
                   8382:                                    \%respnumlookup,\%startline) 
                   8383:             eq 'ssi_error') {
1.542     raeburn  8384:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8385:             $r->print("</form>");
                   8386:             &ssi_print_error($r);
                   8387:             &Apache::lonnet::remove_lock($lock);
                   8388:             return '';      # Why return ''?  Beats me.
                   8389:         }
1.513     foxr     8390: 
1.692     raeburn  8391:         if (($scancode) && ($randomorder || $randompick)) {
                   8392:             my $parmresult =
                   8393:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8394:                                                        '0_examcode',2,$scancode,
                   8395:                                                        'string_examcode',$uname,
                   8396:                                                        $udom);
                   8397:         }
1.140     albertel 8398: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8399:         if ($env{'form.verifyrecord'}) {
                   8400:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8401:             if ($randompick) {
                   8402:                 if ($total) {
                   8403:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8404:                 }
                   8405:             }
                   8406: 
1.542     raeburn  8407:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8408:             chomp($studentdata);
                   8409:             $studentdata =~ s/\r$//;
                   8410:             my $studentrecord = '';
                   8411:             my $counter = -1;
1.677     raeburn  8412:             foreach my $resource (@mapresources) {
1.554     raeburn  8413:                 my $ressymb = $resource->symb();
1.542     raeburn  8414:                 ($counter,my $recording) =
                   8415:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8416:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8417:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8418:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8419:                 $studentrecord .= $recording;
                   8420:             }
                   8421:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8422:                 &Apache::lonxml::clear_problem_counter();
                   8423:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8424:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8425:                                            $bubbles_per_row,$randomorder,$randompick,
                   8426:                                            \%respnumlookup,\%startline) 
                   8427:                     eq 'ssi_error') {
1.554     raeburn  8428:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8429:                     $r->print("</form>");
                   8430:                     &ssi_print_error($r);
                   8431:                     &Apache::lonnet::remove_lock($lock);
                   8432:                     delete($completedstudents{$uname});
                   8433:                     return '';
                   8434:                 }
1.542     raeburn  8435:                 $counter = -1;
                   8436:                 $studentrecord = '';
1.677     raeburn  8437:                 foreach my $resource (@mapresources) {
1.554     raeburn  8438:                     my $ressymb = $resource->symb();
1.542     raeburn  8439:                     ($counter,my $recording) =
                   8440:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8441:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8442:                                                  \%scantron_config,\%lettdig,$numletts,
                   8443:                                                  $randomorder,$randompick,\%respnumlookup,
                   8444:                                                  \%startline);
1.542     raeburn  8445:                     $studentrecord .= $recording;
                   8446:                 }
                   8447:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8448:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8449:                     if ($scancode eq '') {
1.658     bisitz   8450:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8451:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8452:                     } else {
1.658     bisitz   8453:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8454:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8455:                     }
                   8456:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8457:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8458:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8459:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8460:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8461:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8462:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8463:                               &Apache::loncommon::end_data_table_row().
                   8464:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8465:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8466:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8467:                               &Apache::loncommon::end_data_table_row().
                   8468:                               &Apache::loncommon::end_data_table().'</p>');
                   8469:                 } else {
                   8470:                     $r->print('<br /><span class="LC_warning">'.
                   8471:                              &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 />'.
                   8472:                              &mt("As a consequence, this user's submission history records two tries.").
                   8473:                                  '</span><br />');
                   8474:                 }
                   8475:             }
                   8476:         }
1.543     raeburn  8477:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8478:     } continue {
1.330     albertel 8479: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8480: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8481:     }
1.140     albertel 8482:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8483:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8484: #    my $lasttime = &Time::HiRes::time()-$start;
                   8485: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8486: 
1.200     albertel 8487:     $r->print("</form>");
1.157     albertel 8488:     return '';
1.75      albertel 8489: }
1.157     albertel 8490: 
1.557     raeburn  8491: sub graders_resources_pass {
1.649     raeburn  8492:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8493:         $bubbles_per_row) = @_;
1.557     raeburn  8494:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8495:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8496:         foreach my $resource (@{$resources}) {
                   8497:             my $ressymb = $resource->symb();
                   8498:             my ($analysis,$parts) =
                   8499:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8500:                                           $env{'user.name'},$env{'user.domain'},
                   8501:                                           1,$bubbles_per_row);
1.557     raeburn  8502:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8503:             if (ref($analysis) eq 'HASH') {
                   8504:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8505:                     $grader_randomlists_by_symb->{$ressymb} =
                   8506:                         $analysis->{'parts_withrandomlist'};
                   8507:                 }
                   8508:             }
                   8509:         }
                   8510:     }
                   8511:     return;
                   8512: }
                   8513: 
1.678     raeburn  8514: =pod
                   8515: 
                   8516: =item users_order
                   8517: 
                   8518:   Returns array of resources in current map, ordered based on either CODE,
                   8519:   if this is a CODEd exam, or based on student's identity if this is a 
                   8520:   "NAMEd" exam.
                   8521: 
1.691     raeburn  8522:   Should be used when randomorder and/or randompick applied when the 
                   8523:   corresponding exam was printed, prior to students completing bubblesheets 
                   8524:   for the version of the exam the student received.
1.678     raeburn  8525: 
                   8526: =cut
                   8527: 
                   8528: sub users_order  {
1.691     raeburn  8529:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8530:     my @mapresources;
1.691     raeburn  8531:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8532:         return @mapresources;
1.691     raeburn  8533:     }
                   8534:     if ($scancode) {
                   8535:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8536:             @mapresources = @{$orderedforcode->{$scancode}};
                   8537:         } else {
                   8538:             $env{'form.CODE'} = $scancode;
                   8539:             my $actual_seq =
                   8540:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8541:                                                                $master_seq,
                   8542:                                                                $user,$scancode,1);
                   8543:             if (ref($actual_seq) eq 'ARRAY') {
                   8544:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8545:                 if (ref($orderedforcode) eq 'HASH') {
                   8546:                     if (@mapresources > 0) { 
                   8547:                         $orderedforcode->{$scancode} = \@mapresources;
                   8548:                     }
                   8549:                 }
                   8550:             }
                   8551:             delete($env{'form.CODE'});
1.678     raeburn  8552:         }
                   8553:     } else {
                   8554:         my $actual_seq =
                   8555:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8556:                                                            $master_seq,
1.688     raeburn  8557:                                                            $user,undef,1);
1.678     raeburn  8558:         if (ref($actual_seq) eq 'ARRAY') {
                   8559:             @mapresources = 
                   8560:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8561:         }
1.691     raeburn  8562:     }
                   8563:     return @mapresources;
1.678     raeburn  8564: }
                   8565: 
1.542     raeburn  8566: sub grade_student_bubbles {
1.691     raeburn  8567:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8568:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8569:     my $uselookup = 0;
                   8570:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8571:         (ref($startline) eq 'HASH')) {
                   8572:         $uselookup = 1;
                   8573:     }
                   8574: 
1.554     raeburn  8575:     if (ref($resources) eq 'ARRAY') {
                   8576:         my $count = 0;
                   8577:         foreach my $resource (@{$resources}) {
                   8578:             my $ressymb = $resource->symb();
                   8579:             my %form = ('submitted'      => 'scantron',
                   8580:                         'grade_target'   => 'grade',
                   8581:                         'grade_username' => $uname,
                   8582:                         'grade_domain'   => $udom,
                   8583:                         'grade_courseid' => $env{'request.course.id'},
                   8584:                         'grade_symb'     => $ressymb,
                   8585:                         'CODE'           => $scancode
                   8586:                        );
1.649     raeburn  8587:             if ($bubbles_per_row ne '') {
                   8588:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8589:             }
1.663     raeburn  8590:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8591:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8592:             }
1.554     raeburn  8593:             if (ref($parts) eq 'HASH') {
                   8594:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8595:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8596:                         if ($uselookup) {
                   8597:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8598:                         } else {
                   8599:                             $form{'scantron_questnum_start.'.$part} =
                   8600:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8601:                         }
1.554     raeburn  8602:                         $count++;
                   8603:                     }
                   8604:                 }
                   8605:             }
                   8606:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8607:             return 'ssi_error' if ($ssi_error);
                   8608:             last if (&Apache::loncommon::connection_aborted($r));
                   8609:         }
1.542     raeburn  8610:     }
                   8611:     return;
                   8612: }
                   8613: 
1.157     albertel 8614: sub scantron_upload_scantron_data {
1.608     www      8615:     my ($r,$symb)=@_;
1.565     raeburn  8616:     my $dom = $env{'request.role.domain'};
                   8617:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8618:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8619:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8620: 							  'domainid',
1.565     raeburn  8621: 							  'coursename',$dom);
                   8622:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8623:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8624:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8625:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8626:     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 8627:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8628:     function checkUpload(formname) {
                   8629: 	if (formname.upfile.value == "") {
1.579     raeburn  8630: 	    alert("'.$nofile_alert.'");
1.157     albertel 8631: 	    return false;
                   8632: 	}
1.565     raeburn  8633:         if (formname.courseid.value == "") {
1.579     raeburn  8634:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8635:             return false;
                   8636:         }
1.157     albertel 8637: 	formname.submit();
                   8638:     }
1.565     raeburn  8639: 
                   8640:     function ToSyllabus() {
                   8641:         var cdom = '."'$dom'".';
                   8642:         var cnum = document.rules.courseid.value;
                   8643:         if (cdom == "" || cdom == null) {
                   8644:             return;
                   8645:         }
                   8646:         if (cnum == "" || cnum == null) {
                   8647:            return;
                   8648:         }
                   8649:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8650:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8651:         return;
                   8652:     }
                   8653: 
1.597     wenzelju 8654: '));
                   8655:     $r->print('
1.648     bisitz   8656: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8657: 
1.492     albertel 8658: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8659: '.$default_form_data.
                   8660:   &Apache::lonhtmlcommon::start_pick_box().
                   8661:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8662:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8663:   &Apache::lonhtmlcommon::row_closure().
                   8664:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8665:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8666:   &Apache::lonhtmlcommon::row_closure().
                   8667:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8668:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8669:   &Apache::lonhtmlcommon::row_closure().
                   8670:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8671:   '<input type="file" name="upfile" size="50" />'.
                   8672:   &Apache::lonhtmlcommon::row_closure(1).
                   8673:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8674: 
1.492     albertel 8675: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8676: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8677: </form>
1.492     albertel 8678: ');
1.157     albertel 8679:     return '';
                   8680: }
                   8681: 
1.423     albertel 8682: 
1.157     albertel 8683: sub scantron_upload_scantron_data_save {
1.608     www      8684:     my($r,$symb)=@_;
1.182     albertel 8685:     my $doanotherupload=
                   8686: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8687: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8688: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8689: 	'</form>'."\n";
1.257     albertel 8690:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8691: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8692: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8693: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8694: 	unless ($symb) {
1.182     albertel 8695: 	    $r->print($doanotherupload);
                   8696: 	}
1.162     albertel 8697: 	return '';
                   8698:     }
1.257     albertel 8699:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8700:     my $uploadedfile;
1.710     bisitz   8701:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8702:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8703:         $r->print(
                   8704:             &Apache::lonhtmlcommon::confirm_success(
                   8705:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8706:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8707:     } else {
1.568     raeburn  8708:         my $result = 
                   8709:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8710:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8711:         if ($result =~ m{^/uploaded/}) {
                   8712:             $r->print(
                   8713:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8714:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8715:                         (length($env{'form.upfile'})-1),
                   8716:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8717:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8718:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8719:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8720:         } else {
                   8721:             $r->print(
                   8722:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8723:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8724:                           $result,
1.568     raeburn  8725: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8726: 	}
                   8727:     }
1.174     albertel 8728:     if ($symb) {
1.612     www      8729: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8730:     } else {
1.182     albertel 8731: 	$r->print($doanotherupload);
1.174     albertel 8732:     }
1.157     albertel 8733:     return '';
                   8734: }
                   8735: 
1.567     raeburn  8736: sub validate_uploaded_scantron_file {
                   8737:     my ($cdom,$cname,$fname) = @_;
                   8738:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8739:     my @lines;
                   8740:     if ($scanlines ne '-1') {
                   8741:         @lines=split("\n",$scanlines,-1);
                   8742:     }
                   8743:     my $output;
                   8744:     if (@lines) {
                   8745:         my (%counts,$max_match_format);
1.710     bisitz   8746:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8747:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8748:         my %idmap = &username_to_idmap($classlist);
                   8749:         foreach my $key (keys(%idmap)) {
                   8750:             my $lckey = lc($key);
                   8751:             $idmap{$lckey} = $idmap{$key};
                   8752:         }
                   8753:         my %unique_formats;
                   8754:         my @formatlines = &get_scantronformat_file();
                   8755:         foreach my $line (@formatlines) {
                   8756:             chomp($line);
                   8757:             my @config = split(/:/,$line);
                   8758:             my $idstart = $config[5];
                   8759:             my $idlength = $config[6];
                   8760:             if (($idstart ne '') && ($idlength > 0)) {
                   8761:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8762:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8763:                 } else {
                   8764:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8765:                 }
                   8766:             }
                   8767:         }
                   8768:         foreach my $key (keys(%unique_formats)) {
                   8769:             my ($idstart,$idlength) = split(':',$key);
                   8770:             %{$counts{$key}} = (
                   8771:                                'found'   => 0,
                   8772:                                'total'   => 0,
                   8773:                               );
                   8774:             foreach my $line (@lines) {
                   8775:                 next if ($line =~ /^#/);
                   8776:                 next if ($line =~ /^[\s\cz]*$/);
                   8777:                 my $id = substr($line,$idstart-1,$idlength);
                   8778:                 $id = lc($id);
                   8779:                 if (exists($idmap{$id})) {
                   8780:                     $counts{$key}{'found'} ++;
                   8781:                 }
                   8782:                 $counts{$key}{'total'} ++;
                   8783:             }
                   8784:             if ($counts{$key}{'total'}) {
                   8785:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8786:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8787:                     $max_match_pct = $percent_match;
                   8788:                     $max_match_format = $key;
1.710     bisitz   8789:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8790:                     $max_match_count = $counts{$key}{'total'};
                   8791:                 }
                   8792:             }
                   8793:         }
                   8794:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8795:             my $format_descs;
                   8796:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8797:             for (my $i=0; $i<$numwithformat; $i++) {
                   8798:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8799:                 if ($i<$numwithformat-2) {
                   8800:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8801:                 } elsif ($i==$numwithformat-2) {
                   8802:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8803:                 } elsif ($i==$numwithformat-1) {
                   8804:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8805:                 }
                   8806:             }
                   8807:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8808:             $output .= '<br />';
                   8809:             if ($found_match_count == $max_match_count) {
                   8810:                 # 100% matching entries
                   8811:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8812:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8813:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8814:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8815:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8816:                     ' in the file (for the format defined for [_3]).',
                   8817:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8818:             } else {
                   8819:                 # Not all entries matching? -> Show warning and additional info
                   8820:                 $output .=
                   8821:                     &Apache::lonhtmlcommon::confirm_success(
                   8822:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8823:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8824:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8825:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8826:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8827:                         ' in the file (for the format defined for [_3]).',
                   8828:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8829:                     '<p class="LC_info">'.
                   8830:                     &mt('A low percentage of matches results from one of the following:').
                   8831:                     '</p><ul>'.
                   8832:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8833:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8834:                                '<i>'.$cdom.'</i>').'</li>'.
                   8835:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8836:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8837:                     '</ul>';
                   8838:             }
1.567     raeburn  8839:         }
                   8840:     } else {
1.710     bisitz   8841:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8842:     }
                   8843:     return $output;
                   8844: }
                   8845: 
1.202     albertel 8846: sub valid_file {
                   8847:     my ($requested_file)=@_;
                   8848:     foreach my $filename (sort(&scantron_filenames())) {
                   8849: 	if ($requested_file eq $filename) { return 1; }
                   8850:     }
                   8851:     return 0;
                   8852: }
                   8853: 
                   8854: sub scantron_download_scantron_data {
1.608     www      8855:     my ($r,$symb)=@_;
                   8856:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8857:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8858:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8859:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8860:     if (! &valid_file($file)) {
1.492     albertel 8861: 	$r->print('
1.202     albertel 8862: 	<p>
1.686     bisitz   8863: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8864:         </p>
1.492     albertel 8865: ');
1.202     albertel 8866: 	return;
                   8867:     }
                   8868:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8869:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8870:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8871:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8872:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8873:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8874:     $r->print('
1.202     albertel 8875:     <p>
1.711     bisitz   8876: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
1.492     albertel 8877: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8878:     </p>
                   8879:     <p>
1.492     albertel 8880: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8881: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8882:     </p>
                   8883:     <p>
1.492     albertel 8884: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8885: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8886:     </p>
1.492     albertel 8887: ');
1.202     albertel 8888:     return '';
                   8889: }
1.157     albertel 8890: 
1.523     raeburn  8891: sub checkscantron_results {
1.608     www      8892:     my ($r,$symb) = @_;
1.523     raeburn  8893:     if (!$symb) {return '';}
                   8894:     my $cid = $env{'request.course.id'};
1.542     raeburn  8895:     my %lettdig = &letter_to_digits();
1.523     raeburn  8896:     my $numletts = scalar(keys(%lettdig));
                   8897:     my $cnum = $env{'course.'.$cid.'.num'};
                   8898:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8899:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8900:     my %record;
                   8901:     my %scantron_config =
                   8902:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8903:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8904:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8905:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8906:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8907:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8908:     unless (ref($navmap)) {
                   8909:         $r->print(&navmap_errormsg());
                   8910:         return '';
                   8911:     }
1.523     raeburn  8912:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8913:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8914:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8915:     if (ref($map)) { 
                   8916:         $randomorder=$map->randomorder();
1.689     raeburn  8917:         $randompick=$map->randompick();
1.677     raeburn  8918:     }
1.557     raeburn  8919:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8920:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8921:     if ($nav_error) {
                   8922:         $r->print(&navmap_errormsg());
                   8923:         return '';
1.678     raeburn  8924:     }
1.673     raeburn  8925:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8926:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8927:     my ($uname,$udom);
1.523     raeburn  8928:     my (%scandata,%lastname,%bylast);
                   8929:     $r->print('
                   8930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8931: 
                   8932:     my @delayqueue;
                   8933:     my %completedstudents;
                   8934: 
1.691     raeburn  8935:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8936:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8937:     my ($username,$domain,$started);
1.649     raeburn  8938:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8939:     if ($nav_error) {
                   8940:         $r->print(&navmap_errormsg());
                   8941:         return '';
                   8942:     }
1.523     raeburn  8943: 
1.667     www      8944:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8945:     my $start=&Time::HiRes::time();
                   8946:     my $i=-1;
                   8947: 
                   8948:     while ($i<$scanlines->{'count'}) {
                   8949:         ($username,$domain,$uname)=('','','');
                   8950:         $i++;
                   8951:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8952:         if ($line=~/^[\s\cz]*$/) { next; }
                   8953:         if ($started) {
1.667     www      8954:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8955:         }
                   8956:         $started=1;
                   8957:         my $scan_record=
                   8958:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8959:                                                      $scan_data);
1.693     raeburn  8960:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8961:                                               \%idmap,$i)) {
1.523     raeburn  8962:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8963:                                 'Unable to find a student that matches',1);
                   8964:             next;
                   8965:         }
                   8966:         if (exists $completedstudents{$uname}) {
                   8967:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8968:                                 'Student '.$uname.' has multiple sheets',2);
                   8969:             next;
                   8970:         }
                   8971:         my $pid = $scan_record->{'scantron.ID'};
                   8972:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8973:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  8974:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8975:         my $user = $uname.':'.$usec;
1.523     raeburn  8976:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  8977: 
1.678     raeburn  8978:         my $scancode;
1.677     raeburn  8979:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8980:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8981:             $scancode = $scan_record->{'scantron.CODE'};
                   8982:         } else {
                   8983:             $scancode = '';
                   8984:         }
                   8985: 
                   8986:         my @mapresources = @resources;
1.691     raeburn  8987:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8988:         my %respnumlookup=();
                   8989:         my %startline=();
1.689     raeburn  8990:         if ($randomorder || $randompick) {
1.678     raeburn  8991:             @mapresources =
1.691     raeburn  8992:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8993:                              \%orderedforcode);
                   8994:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   8995:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   8996:                                              \%grader_partids_by_symb,\%orderedforcode,
                   8997:                                              \%respnumlookup,\%startline);
                   8998:             if ($randompick && $total) {
                   8999:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9000:             }
1.677     raeburn  9001:         }
1.691     raeburn  9002:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9003:         chomp($scandata{$pid});
                   9004:         $scandata{$pid} =~ s/\r$//;
                   9005: 
1.523     raeburn  9006:         my $counter = -1;
1.677     raeburn  9007:         foreach my $resource (@mapresources) {
1.557     raeburn  9008:             my $parts;
1.554     raeburn  9009:             my $ressymb = $resource->symb();
1.557     raeburn  9010:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9011:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9012:                 (my $analysis,$parts) =
1.672     raeburn  9013:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9014:                                               $username,$domain,undef,
                   9015:                                               $bubbles_per_row);
1.557     raeburn  9016:             } else {
                   9017:                 $parts = $grader_partids_by_symb{$ressymb};
                   9018:             }
1.542     raeburn  9019:             ($counter,my $recording) =
                   9020:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9021:                                          $scandata{$pid},$parts,
1.691     raeburn  9022:                                          \%scantron_config,\%lettdig,$numletts,
                   9023:                                          $randomorder,$randompick,
                   9024:                                          \%respnumlookup,\%startline);
1.542     raeburn  9025:             $record{$pid} .= $recording;
1.523     raeburn  9026:         }
                   9027:     }
                   9028:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9029:     $r->print('<br />');
                   9030:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9031:     $passed = 0;
                   9032:     $failed = 0;
                   9033:     $numstudents = 0;
                   9034:     foreach my $last (sort(keys(%bylast))) {
                   9035:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9036:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9037:                 my $showscandata = $scandata{$pid};
                   9038:                 my $showrecord = $record{$pid};
                   9039:                 $showscandata =~ s/\s/&nbsp;/g;
                   9040:                 $showrecord =~ s/\s/&nbsp;/g;
                   9041:                 if ($scandata{$pid} eq $record{$pid}) {
                   9042:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9043:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9044: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9045: '</tr>'."\n".
                   9046: '<tr class="'.$css_class.'">'."\n".
                   9047: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   9048:                     $passed ++;
                   9049:                 } else {
                   9050:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9051:                     $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  9052: '</tr>'."\n".
                   9053: '<tr class="'.$css_class.'">'."\n".
                   9054: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   9055: '</tr>'."\n";
                   9056:                     $failed ++;
                   9057:                 }
                   9058:                 $numstudents ++;
                   9059:             }
                   9060:         }
                   9061:     }
1.648     bisitz   9062:     $r->print(
                   9063:         '<p>'
                   9064:        .&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).',
                   9065:             '<b>',
                   9066:             $numstudents,
                   9067:             '</b>',
                   9068:             $env{'form.scantron_maxbubble'})
                   9069:        .'</p>'
                   9070:     );
1.682     raeburn  9071:     $r->print('<p>'
1.683     raeburn  9072:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9073:              .'<br />'
                   9074:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9075:              .'</p>'
                   9076:     );
1.523     raeburn  9077:     if ($passed) {
1.572     www      9078:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9079:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9080:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9081:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9082:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9083:                  $okstudents."\n".
                   9084:                  &Apache::loncommon::end_data_table().'<br />');
                   9085:     }
                   9086:     if ($failed) {
1.572     www      9087:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9088:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9089:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9090:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9091:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9092:                  $badstudents."\n".
                   9093:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9094:                  &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  9095:     }
1.614     www      9096:     $r->print('</form><br />');
1.523     raeburn  9097:     return;
                   9098: }
                   9099: 
1.542     raeburn  9100: sub verify_scantron_grading {
1.554     raeburn  9101:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9102:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9103:         $respnumlookup,$startline) = @_;
1.542     raeburn  9104:     my ($record,%expected,%startpos);
                   9105:     return ($counter,$record) if (!ref($resource));
                   9106:     return ($counter,$record) if (!$resource->is_problem());
                   9107:     my $symb = $resource->symb();
1.554     raeburn  9108:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9109:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9110:         $counter ++;
                   9111:         $expected{$part_id} = 0;
1.691     raeburn  9112:         my $respnum = $counter;
                   9113:         if ($randomorder || $randompick) {
                   9114:             $respnum = $respnumlookup->{$counter};
                   9115:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9116:         } else {
                   9117:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9118:         }
                   9119:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9120:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9121:             foreach my $item (@sub_lines) {
                   9122:                 $expected{$part_id} += $item;
                   9123:             }
                   9124:         } else {
1.691     raeburn  9125:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9126:         }
                   9127:     }
                   9128:     if ($symb) {
                   9129:         my %recorded;
                   9130:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9131:         if ($returnhash{'version'}) {
                   9132:             my %lasthash=();
                   9133:             my $version;
                   9134:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9135:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9136:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9137:                 }
                   9138:             }
                   9139:             foreach my $key (keys(%lasthash)) {
                   9140:                 if ($key =~ /\.scantron$/) {
                   9141:                     my $value = &unescape($lasthash{$key});
                   9142:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9143:                     if ($value eq '') {
                   9144:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9145:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9146:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9147:                             }
                   9148:                         }
                   9149:                     } else {
                   9150:                         my @tocheck;
                   9151:                         my @items = split(//,$value);
                   9152:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9153:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9154:                             if (@items < $expected{$part_id}) {
                   9155:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9156:                                 my @singles = split(//,$fragment);
                   9157:                                 foreach my $pos (@singles) {
                   9158:                                     if ($pos eq ' ') {
                   9159:                                         push(@tocheck,$pos);
                   9160:                                     } else {
                   9161:                                         my $next = shift(@items);
                   9162:                                         push(@tocheck,$next);
                   9163:                                     }
                   9164:                                 }
                   9165:                             } else {
                   9166:                                 @tocheck = @items;
                   9167:                             }
                   9168:                             foreach my $letter (@tocheck) {
                   9169:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9170:                                     if ($letter !~ /^[A-J]$/) {
                   9171:                                         $letter = $scantron_config->{'Qoff'};
                   9172:                                     }
                   9173:                                     $recorded{$part_id} .= $letter;
                   9174:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9175:                                     my $digit;
                   9176:                                     if ($letter !~ /^[A-J]$/) {
                   9177:                                         $digit = $scantron_config->{'Qoff'};
                   9178:                                     } else {
                   9179:                                         $digit = $lettdig->{$letter};
                   9180:                                     }
                   9181:                                     $recorded{$part_id} .= $digit;
                   9182:                                 }
                   9183:                             }
                   9184:                         } else {
                   9185:                             @tocheck = @items;
                   9186:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9187:                                 my $curr_sub = shift(@tocheck);
                   9188:                                 my $digit;
                   9189:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9190:                                     $digit = $lettdig->{$curr_sub}-1;
                   9191:                                 }
                   9192:                                 if ($curr_sub eq 'J') {
                   9193:                                     $digit += scalar($numletts);
                   9194:                                 }
                   9195:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9196:                                     if ($j == $digit) {
                   9197:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9198:                                     } else {
                   9199:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9200:                                     }
                   9201:                                 }
                   9202:                             }
                   9203:                         }
                   9204:                     }
                   9205:                 }
                   9206:             }
                   9207:         }
1.554     raeburn  9208:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9209:             if ($recorded{$part_id} eq '') {
                   9210:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9211:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9212:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9213:                     }
                   9214:                 }
                   9215:             }
                   9216:             $record .= $recorded{$part_id};
                   9217:         }
                   9218:     }
                   9219:     return ($counter,$record);
                   9220: }
                   9221: 
1.691     raeburn  9222: sub letter_to_digits {
1.542     raeburn  9223:     my %lettdig = (
                   9224:                     A => 1,
                   9225:                     B => 2,
                   9226:                     C => 3,
                   9227:                     D => 4,
                   9228:                     E => 5,
                   9229:                     F => 6,
                   9230:                     G => 7,
                   9231:                     H => 8,
                   9232:                     I => 9,
                   9233:                     J => 0,
                   9234:                   );
                   9235:     return %lettdig;
                   9236: }
                   9237: 
1.423     albertel 9238: 
1.75      albertel 9239: #-------- end of section for handling grading scantron forms -------
                   9240: #
                   9241: #-------------------------------------------------------------------
                   9242: 
1.72      ng       9243: #-------------------------- Menu interface -------------------------
                   9244: #
1.614     www      9245: #--- Href with symb and command ---
                   9246: 
                   9247: sub href_symb_cmd {
                   9248:     my ($symb,$cmd)=@_;
1.669     raeburn  9249:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9250: }
                   9251: 
1.443     banghart 9252: sub grading_menu {
1.608     www      9253:     my ($request,$symb) = @_;
1.443     banghart 9254:     if (!$symb) {return '';}
                   9255: 
                   9256:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9257:                   'command'=>'individual');
1.538     schulted 9258:     
1.598     www      9259:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9260: 
                   9261:     $fields{'command'}='ungraded';
                   9262:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9263: 
                   9264:     $fields{'command'}='table';
                   9265:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9266: 
                   9267:     $fields{'command'}='all_for_one';
                   9268:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9269: 
1.621     www      9270:     $fields{'command'}='downloadfilesselect';
                   9271:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9272: 
1.443     banghart 9273:     $fields{'command'} = 'csvform';
1.538     schulted 9274:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9275:     
1.443     banghart 9276:     $fields{'command'} = 'processclicker';
1.538     schulted 9277:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9278:     
1.443     banghart 9279:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9280:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9281: 
                   9282:     $fields{'command'} = 'initialverifyreceipt';
                   9283:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9284:     
1.598     www      9285:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9286:             items =>[
1.598     www      9287:                         {	linktext => 'Select individual students to grade',
                   9288:                     		url => $url1a,
1.538     schulted 9289:                     		permission => 'F',
1.636     wenzelju 9290:                     		icon => 'grade_students.png',
1.598     www      9291:                     		linktitle => 'Grade current resource for a selection of students.'
                   9292:                         }, 
                   9293:                         {       linktext => 'Grade ungraded submissions.',
                   9294:                                 url => $url1b,
                   9295:                                 permission => 'F',
1.636     wenzelju 9296:                                 icon => 'ungrade_sub.png',
1.598     www      9297:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9298:                         },
1.598     www      9299: 
                   9300:                         {       linktext => 'Grading table',
                   9301:                                 url => $url1c,
                   9302:                                 permission => 'F',
1.636     wenzelju 9303:                                 icon => 'grading_table.png',
1.598     www      9304:                                 linktitle => 'Grade current resource for all students.'
                   9305:                         },
1.615     www      9306:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9307:                                 url => $url1d,
                   9308:                                 permission => 'F',
1.636     wenzelju 9309:                                 icon => 'grade_PageFolder.png',
1.598     www      9310:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9311:                         },
                   9312:                         {       linktext => 'Download submissions',
                   9313:                                 url => $url1e,
                   9314:                                 permission => 'F',
1.636     wenzelju 9315:                                 icon => 'download_sub.png',
1.621     www      9316:                                 linktitle => 'Download all students submissions.'
1.598     www      9317:                         }]},
                   9318:                          { categorytitle=>'Automated Grading',
                   9319:                items =>[
                   9320: 
1.538     schulted 9321:                 	    {	linktext => 'Upload Scores',
                   9322:                     		url => $url2,
                   9323:                     		permission => 'F',
                   9324:                     		icon => 'uploadscores.png',
                   9325:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9326:                 	    },
                   9327:                 	    {	linktext => 'Process Clicker',
                   9328:                     		url => $url3,
                   9329:                     		permission => 'F',
                   9330:                     		icon => 'addClickerInfoFile.png',
                   9331:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9332:                 	    },
1.587     raeburn  9333:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9334:                     		url => $url4,
                   9335:                     		permission => 'F',
1.636     wenzelju 9336:                     		icon => 'bubblesheet.png',
1.648     bisitz   9337:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9338:                 	    },
1.616     www      9339:                             {   linktext => 'Verify Receipt Number',
1.602     www      9340:                                 url => $url5,
                   9341:                                 permission => 'F',
1.636     wenzelju 9342:                                 icon => 'receipt_number.png',
1.602     www      9343:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9344:                             }
                   9345: 
1.538     schulted 9346:                     ]
                   9347:             });
                   9348: 
1.443     banghart 9349:     # Create the menu
                   9350:     my $Str;
1.445     banghart 9351:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9352:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9353:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9354: 
1.602     www      9355:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9356:     return $Str;    
                   9357: }
                   9358: 
1.598     www      9359: 
                   9360: sub ungraded {
                   9361:     my ($request)=@_;
                   9362:     &submit_options($request);
                   9363: }
                   9364: 
1.599     www      9365: sub submit_options_sequence {
1.608     www      9366:     my ($request,$symb) = @_;
1.599     www      9367:     if (!$symb) {return '';}
1.600     www      9368:     &commonJSfunctions($request);
                   9369:     my $result;
1.599     www      9370: 
1.600     www      9371:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9372:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9373:     $result.=&selectfield(0).
1.601     www      9374:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9375:             <div>
                   9376:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9377:             </div>
                   9378:         </div>
                   9379:   </form>';
                   9380:     return $result;
                   9381: }
                   9382: 
                   9383: sub submit_options_table {
1.608     www      9384:     my ($request,$symb) = @_;
1.600     www      9385:     if (!$symb) {return '';}
1.599     www      9386:     &commonJSfunctions($request);
                   9387:     my $result;
                   9388: 
                   9389:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9390:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9391: 
1.632     www      9392:     $result.=&selectfield(0).
1.601     www      9393:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9394:             <div>
                   9395:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9396:             </div>
                   9397:         </div>
                   9398:   </form>';
                   9399:     return $result;
                   9400: }
1.443     banghart 9401: 
1.621     www      9402: sub submit_options_download {
                   9403:     my ($request,$symb) = @_;
                   9404:     if (!$symb) {return '';}
                   9405: 
                   9406:     &commonJSfunctions($request);
                   9407: 
                   9408:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9409:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9410:     $result.='
                   9411: <h2>
                   9412:   '.&mt('Select Students for Which to Download Submissions').'
                   9413: </h2>'.&selectfield(1).'
                   9414:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9415:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9416:             </div>
                   9417:           </div>
1.600     www      9418: 
                   9419: 
1.621     www      9420:   </form>';
                   9421:     return $result;
                   9422: }
                   9423: 
1.443     banghart 9424: #--- Displays the submissions first page -------
                   9425: sub submit_options {
1.608     www      9426:     my ($request,$symb) = @_;
1.72      ng       9427:     if (!$symb) {return '';}
                   9428: 
1.118     ng       9429:     &commonJSfunctions($request);
1.473     albertel 9430:     my $result;
1.533     bisitz   9431: 
1.72      ng       9432:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9433: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9434:     $result.=&selectfield(1).'
1.601     www      9435:                 <input type="hidden" name="command" value="submission" /> 
                   9436: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9437:             </div>
                   9438:           </div>
                   9439: 
                   9440: 
                   9441:   </form>';
                   9442:     return $result;
                   9443: }
1.533     bisitz   9444: 
1.601     www      9445: sub selectfield {
                   9446:    my ($full)=@_;
1.635     raeburn  9447:    my %options = 
                   9448:           (&Apache::lonlocal::texthash(
                   9449:              'yes'       => 'with submissions',
                   9450:              'queued'    => 'in grading queue',
                   9451:              'graded'    => 'with ungraded submissions',
                   9452:              'incorrect' => 'with incorrect submissions',
                   9453:              'all'       => 'with any status'),
                   9454:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9455:    my $result='<div class="LC_columnSection">
1.537     harmsja  9456:   
1.533     bisitz   9457:     <fieldset>
                   9458:       <legend>
                   9459:        '.&mt('Sections').'
                   9460:       </legend>
1.601     www      9461:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9462:     </fieldset>
1.537     harmsja  9463:   
1.533     bisitz   9464:     <fieldset>
                   9465:       <legend>
                   9466:         '.&mt('Groups').'
                   9467:       </legend>
                   9468:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9469:     </fieldset>
1.537     harmsja  9470:   
1.533     bisitz   9471:     <fieldset>
                   9472:       <legend>
                   9473:         '.&mt('Access Status').'
                   9474:       </legend>
1.601     www      9475:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9476:     </fieldset>';
                   9477:     if ($full) {
                   9478:        $result.='
1.533     bisitz   9479:     <fieldset>
                   9480:       <legend>
                   9481:         '.&mt('Submission Status').'
1.601     www      9482:       </legend>'.
1.635     raeburn  9483:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9484:    '</fieldset>';
                   9485:     }
                   9486:     $result.='</div><br />';
1.44      ng       9487:     return $result;
1.2       albertel 9488: }
                   9489: 
1.285     albertel 9490: sub reset_perm {
                   9491:     undef(%perm);
                   9492: }
                   9493: 
                   9494: sub init_perm {
                   9495:     &reset_perm();
1.300     albertel 9496:     foreach my $test_perm ('vgr','mgr','opa') {
                   9497: 
                   9498: 	my $scope = $env{'request.course.id'};
                   9499: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9500: 
                   9501: 	    $scope .= '/'.$env{'request.course.sec'};
                   9502: 	    if ( $perm{$test_perm}=
                   9503: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9504: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9505: 	    } else {
                   9506: 		delete($perm{$test_perm});
                   9507: 	    }
1.285     albertel 9508: 	}
                   9509:     }
                   9510: }
                   9511: 
1.674     raeburn  9512: sub init_old_essays {
                   9513:     my ($symb,$apath,$adom,$aname) = @_;
                   9514:     if ($symb ne '') {
                   9515:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9516:         if (keys(%essays) > 0) {
                   9517:             $old_essays{$symb} = \%essays;
                   9518:         }
                   9519:     }
                   9520:     return;
                   9521: }
                   9522: 
                   9523: sub reset_old_essays {
                   9524:     undef(%old_essays);
                   9525: }
                   9526: 
1.400     www      9527: sub gather_clicker_ids {
1.408     albertel 9528:     my %clicker_ids;
1.400     www      9529: 
                   9530:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9531: 
                   9532:     # Set up a couple variables.
1.407     albertel 9533:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9534:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9535:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9536: 
1.407     albertel 9537:     foreach my $student (keys(%$classlist)) {
1.438     www      9538:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9539:         my $username = $classlist->{$student}->[$username_idx];
                   9540:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9541:         my $clickers =
1.408     albertel 9542: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9543:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9544:             $id=~s/^[\#0]+//;
1.421     www      9545:             $id=~s/[\-\:]//g;
1.407     albertel 9546:             if (exists($clicker_ids{$id})) {
1.408     albertel 9547: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9548:             } else {
1.408     albertel 9549: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9550:             }
                   9551:         }
                   9552:     }
1.407     albertel 9553:     return %clicker_ids;
1.400     www      9554: }
                   9555: 
1.402     www      9556: sub gather_adv_clicker_ids {
1.408     albertel 9557:     my %clicker_ids;
1.402     www      9558:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9559:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9560:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9561:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9562:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9563:             my ($puname,$pudom)=split(/\:/,$person);
                   9564:             my $clickers =
1.408     albertel 9565: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9566:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9567: 		$id=~s/^[\#0]+//;
1.421     www      9568:                 $id=~s/[\-\:]//g;
1.408     albertel 9569: 		if (exists($clicker_ids{$id})) {
                   9570: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9571: 		} else {
                   9572: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9573: 		}
1.405     www      9574:             }
1.402     www      9575:         }
                   9576:     }
1.407     albertel 9577:     return %clicker_ids;
1.402     www      9578: }
                   9579: 
1.413     www      9580: sub clicker_grading_parameters {
                   9581:     return ('gradingmechanism' => 'scalar',
                   9582:             'upfiletype' => 'scalar',
                   9583:             'specificid' => 'scalar',
                   9584:             'pcorrect' => 'scalar',
                   9585:             'pincorrect' => 'scalar');
                   9586: }
                   9587: 
1.400     www      9588: sub process_clicker {
1.608     www      9589:     my ($r,$symb)=@_;
1.400     www      9590:     if (!$symb) {return '';}
                   9591:     my $result=&checkforfile_js();
1.632     www      9592:     $result.=&Apache::loncommon::start_data_table().
                   9593:              &Apache::loncommon::start_data_table_header_row().
                   9594:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9595:              &Apache::loncommon::end_data_table_header_row().
                   9596:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9597: # Attempt to restore parameters from last session, set defaults if not present
                   9598:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9599:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9600:                                                  \%Saveable_Parameters);
                   9601:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9602:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9603:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9604:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9605: 
                   9606:     my %checked;
1.521     www      9607:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9608:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9609:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9610:        }
                   9611:     }
                   9612: 
1.632     www      9613:     my $upload=&mt("Evaluate File");
1.400     www      9614:     my $type=&mt("Type");
1.402     www      9615:     my $attendance=&mt("Award points just for participation");
                   9616:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9617:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9618:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9619:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9620:     my $pcorrect=&mt("Percentage points for correct solution");
                   9621:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9622:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9623: 						   {'iclicker' => 'i>clicker',
1.666     www      9624:                                                     'interwrite' => 'interwrite PRS',
                   9625:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9626:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9627:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9628: function sanitycheck() {
                   9629: // Accept only integer percentages
                   9630:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9631:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9632: // Find out grading choice
                   9633:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9634:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9635:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9636:       }
                   9637:    }
                   9638: // By default, new choice equals user selection
                   9639:    newgradingchoice=gradingchoice;
                   9640: // Not good to give more points for false answers than correct ones
                   9641:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9642:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9643:    }
                   9644: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9645:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9646:       document.forms.gradesupload.pcorrect.value=100;
                   9647:       document.forms.gradesupload.pincorrect.value=100;
                   9648:    }
                   9649: // If the values are different, cannot be attendance only
                   9650:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9651:        (gradingchoice=='attendance')) {
                   9652:        newgradingchoice='personnel';
                   9653:    }
                   9654: // Change grading choice to new one
                   9655:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9656:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9657:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9658:       } else {
                   9659:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9660:       }
                   9661:    }
                   9662: // Remember the old state
                   9663:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9664: }
1.597     wenzelju 9665: ENDUPFORM
                   9666:     $result.= <<ENDUPFORM;
1.400     www      9667: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9668: <input type="hidden" name="symb" value="$symb" />
                   9669: <input type="hidden" name="command" value="processclickerfile" />
                   9670: <input type="file" name="upfile" size="50" />
                   9671: <br /><label>$type: $selectform</label>
1.632     www      9672: ENDUPFORM
                   9673:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9674:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9675:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9676: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9677: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9678: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9679: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9680: <br />&nbsp;&nbsp;&nbsp;
                   9681: <input type="text" name="givenanswer" size="50" />
1.413     www      9682: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9683: ENDGRADINGFORM
                   9684:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9685:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9686:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9687: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9688: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9689: </form>'
1.632     www      9690: ENDPERCFORM
                   9691:     $result.='</td>'.
                   9692:              &Apache::loncommon::end_data_table_row().
                   9693:              &Apache::loncommon::end_data_table();
1.400     www      9694:     return $result;
                   9695: }
                   9696: 
                   9697: sub process_clicker_file {
1.608     www      9698:     my ($r,$symb)=@_;
1.400     www      9699:     if (!$symb) {return '';}
1.413     www      9700: 
                   9701:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9702:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9703:                                               \%Saveable_Parameters);
1.598     www      9704:     my $result='';
1.404     www      9705:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9706: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9707: 	return $result;
1.404     www      9708:     }
1.522     www      9709:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9710:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9711:         return $result;
1.521     www      9712:     }
1.522     www      9713:     my $foundgiven=0;
1.521     www      9714:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9715:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9716:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9717:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9718:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9719:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9720:         $foundgiven=$#answers+1;
1.521     www      9721:     }
1.407     albertel 9722:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9723:     my %correct_ids;
1.404     www      9724:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9725: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9726:     }
                   9727:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9728: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9729: 	   $correct_id=~tr/a-z/A-Z/;
                   9730: 	   $correct_id=~s/\s//gs;
                   9731: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9732:            $correct_id=~s/[\-\:]//g;
1.414     www      9733:            if ($correct_id) {
                   9734: 	      $correct_ids{$correct_id}='specified';
                   9735:            }
                   9736:         }
1.400     www      9737:     }
1.404     www      9738:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9739: 	$result.=&mt('Score based on attendance only');
1.521     www      9740:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9741:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9742:     } else {
1.408     albertel 9743: 	my $number=0;
1.411     www      9744: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9745: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9746: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9747: 	    if ($correct_ids{$id} eq 'specified') {
                   9748: 		$result.=&mt('specified');
                   9749: 	    } else {
                   9750: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9751: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9752: 	    }
                   9753: 	    $number++;
                   9754: 	}
1.411     www      9755:         $result.="</p>\n";
1.710     bisitz   9756:         if ($number==0) {
                   9757:             $result .=
                   9758:                  &Apache::lonhtmlcommon::confirm_success(
                   9759:                      &mt('No IDs found to determine correct answer'),1);
                   9760:             return $result;
                   9761:         }
1.404     www      9762:     }
1.405     www      9763:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9764:         $result .=
                   9765:             &Apache::lonhtmlcommon::confirm_success(
                   9766:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9767:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9768:         return $result;
1.405     www      9769:     }
1.410     www      9770: 
                   9771: # Were able to get all the info needed, now analyze the file
                   9772: 
1.411     www      9773:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9774:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9775:     $result.=&Apache::loncommon::start_data_table().
                   9776:              &Apache::loncommon::start_data_table_header_row().
                   9777:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9778:              &Apache::loncommon::end_data_table_header_row().
                   9779:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9780: <td>
1.410     www      9781: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9782: <input type="hidden" name="symb" value="$symb" />
                   9783: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9784: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9785: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9786: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9787: ENDHEADER
1.522     www      9788:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9789:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9790:     } 
1.408     albertel 9791:     my %responses;
                   9792:     my @questiontitles;
1.405     www      9793:     my $errormsg='';
                   9794:     my $number=0;
                   9795:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9796: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9797:     }
1.419     www      9798:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9799:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9800:     }
1.666     www      9801:     if ($env{'form.upfiletype'} eq 'turning') {
                   9802:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9803:     }
1.411     www      9804:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9805:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9806:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9807:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9808:              '<br />';
1.522     www      9809:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9810:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9811:        return $result;
1.522     www      9812:     } 
1.414     www      9813: # Remember Question Titles
                   9814: # FIXME: Possibly need delimiter other than ":"
                   9815:     for (my $i=0;$i<$number;$i++) {
                   9816:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9817:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9818:     }
1.411     www      9819:     my $correct_count=0;
                   9820:     my $student_count=0;
                   9821:     my $unknown_count=0;
1.414     www      9822: # Match answers with usernames
                   9823: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9824:     foreach my $id (keys(%responses)) {
1.410     www      9825:        if ($correct_ids{$id}) {
1.414     www      9826:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9827:           $correct_count++;
1.410     www      9828:        } elsif ($clicker_ids{$id}) {
1.437     www      9829:           if ($clicker_ids{$id}=~/\,/) {
                   9830: # More than one user with the same clicker!
1.632     www      9831:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9832:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9833:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9834:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9835:                            "<select name='multi".$id."'>";
                   9836:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9837:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9838:              }
                   9839:              $result.='</select>';
                   9840:              $unknown_count++;
                   9841:           } else {
                   9842: # Good: found one and only one user with the right clicker
                   9843:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9844:              $student_count++;
                   9845:           }
1.410     www      9846:        } else {
1.632     www      9847:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9848:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9849:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9850:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9851:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9852:                    "\n".&mt("Domain").": ".
                   9853:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9854:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9855:           $unknown_count++;
1.410     www      9856:        }
1.405     www      9857:     }
1.412     www      9858:     $result.='<hr />'.
                   9859:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9860:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9861:        if ($correct_count==0) {
1.696     bisitz   9862:           $errormsg.="Found no correct answers for grading!";
1.412     www      9863:        } elsif ($correct_count>1) {
1.414     www      9864:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9865:        }
                   9866:     }
1.428     www      9867:     if ($number<1) {
                   9868:        $errormsg.="Found no questions.";
                   9869:     }
1.412     www      9870:     if ($errormsg) {
                   9871:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9872:     } else {
                   9873:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9874:     }
1.632     www      9875:     $result.='</form></td>'.
                   9876:              &Apache::loncommon::end_data_table_row().
                   9877:              &Apache::loncommon::end_data_table();
1.614     www      9878:     return $result;
1.400     www      9879: }
                   9880: 
1.405     www      9881: sub iclicker_eval {
1.406     www      9882:     my ($questiontitles,$responses)=@_;
1.405     www      9883:     my $number=0;
                   9884:     my $errormsg='';
                   9885:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9886:         my %components=&Apache::loncommon::record_sep($line);
                   9887:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9888: 	if ($entries[0] eq 'Question') {
                   9889: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9890: 		$$questiontitles[$number]=$entries[$i];
                   9891: 		$number++;
                   9892: 	    }
                   9893: 	}
                   9894: 	if ($entries[0]=~/^\#/) {
                   9895: 	    my $id=$entries[0];
                   9896: 	    my @idresponses;
                   9897: 	    $id=~s/^[\#0]+//;
                   9898: 	    for (my $i=0;$i<$number;$i++) {
                   9899: 		my $idx=3+$i*6;
1.644     www      9900:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9901: 		push(@idresponses,$entries[$idx]);
                   9902: 	    }
                   9903: 	    $$responses{$id}=join(',',@idresponses);
                   9904: 	}
1.405     www      9905:     }
                   9906:     return ($errormsg,$number);
                   9907: }
                   9908: 
1.419     www      9909: sub interwrite_eval {
                   9910:     my ($questiontitles,$responses)=@_;
                   9911:     my $number=0;
                   9912:     my $errormsg='';
1.420     www      9913:     my $skipline=1;
                   9914:     my $questionnumber=0;
                   9915:     my %idresponses=();
1.419     www      9916:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9917:         my %components=&Apache::loncommon::record_sep($line);
                   9918:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9919:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9920:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9921:         next if $skipline;
                   9922:         if ($entries[0]!=$questionnumber) {
                   9923:            $questionnumber=$entries[0];
                   9924:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9925:            $number++;
1.419     www      9926:         }
1.420     www      9927:         my $id=$entries[4];
                   9928:         $id=~s/^[\#0]+//;
1.421     www      9929:         $id=~s/^v\d*\://i;
                   9930:         $id=~s/[\-\:]//g;
1.420     www      9931:         $idresponses{$id}[$number]=$entries[6];
                   9932:     }
1.524     raeburn  9933:     foreach my $id (keys(%idresponses)) {
1.420     www      9934:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9935:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9936:     }
                   9937:     return ($errormsg,$number);
                   9938: }
                   9939: 
1.666     www      9940: sub turning_eval {
                   9941:     my ($questiontitles,$responses)=@_;
                   9942:     my $number=0;
                   9943:     my $errormsg='';
                   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)));
                   9947:         if ($#entries>$number) { $number=$#entries; }
                   9948:         my $id=$entries[0];
                   9949:         my @idresponses;
                   9950:         $id=~s/^[\#0]+//;
                   9951:         unless ($id) { next; }
                   9952:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9953:             $entries[$idx]=~s/\,/\;/g;
                   9954:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9955:             push(@idresponses,$entries[$idx]);
                   9956:         }
                   9957:         $$responses{$id}=join(',',@idresponses);
                   9958:     }
                   9959:     for (my $i=1; $i<=$number; $i++) {
                   9960:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9961:     }
                   9962:     return ($errormsg,$number);
                   9963: }
                   9964: 
                   9965: 
1.414     www      9966: sub assign_clicker_grades {
1.608     www      9967:     my ($r,$symb)=@_;
1.414     www      9968:     if (!$symb) {return '';}
1.416     www      9969: # See which part we are saving to
1.582     raeburn  9970:     my $res_error;
                   9971:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9972:     if ($res_error) {
                   9973:         return &navmap_errormsg();
                   9974:     }
1.416     www      9975: # FIXME: This should probably look for the first handgradeable part
                   9976:     my $part=$$partlist[0];
                   9977: # Start screen output
1.632     www      9978:     my $result=&Apache::loncommon::start_data_table().
                   9979:              &Apache::loncommon::start_data_table_header_row().
                   9980:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9981:              &Apache::loncommon::end_data_table_header_row().
                   9982:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9983: # Get correct result
                   9984: # FIXME: Possibly need delimiter other than ":"
                   9985:     my @correct=();
1.415     www      9986:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9987:     my $number=$env{'form.number'};
                   9988:     if ($gradingmechanism ne 'attendance') {
1.414     www      9989:        foreach my $key (keys(%env)) {
                   9990:           if ($key=~/^form\.correct\:/) {
                   9991:              my @input=split(/\,/,$env{$key});
                   9992:              for (my $i=0;$i<=$#input;$i++) {
                   9993:                  if (($correct[$i]) && ($input[$i]) &&
                   9994:                      ($correct[$i] ne $input[$i])) {
                   9995:                     $result.='<br /><span class="LC_warning">'.
                   9996:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9997:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9998:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9999:                     $correct[$i]=$input[$i];
                   10000:                  }
                   10001:              }
                   10002:           }
                   10003:        }
1.415     www      10004:        for (my $i=0;$i<$number;$i++) {
1.644     www      10005:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10006:              $result.='<br /><span class="LC_error">'.
                   10007:                       &mt('No correct result given for question "[_1]"!',
                   10008:                           $env{'form.question:'.$i}).'</span>';
                   10009:           }
                   10010:        }
1.644     www      10011:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10012:     }
                   10013: # Start grading
1.415     www      10014:     my $pcorrect=$env{'form.pcorrect'};
                   10015:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10016:     my $storecount=0;
1.632     www      10017:     my %users=();
1.415     www      10018:     foreach my $key (keys(%env)) {
1.420     www      10019:        my $user='';
1.415     www      10020:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10021:           $user=$1;
                   10022:        }
                   10023:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10024:           my $id=$1;
                   10025:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10026:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10027:           } elsif ($env{'form.multi'.$id}) {
                   10028:              $user=$env{'form.multi'.$id};
1.420     www      10029:           }
                   10030:        }
1.632     www      10031:        if ($user) {
                   10032:           if ($users{$user}) {
                   10033:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10034:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10035:                       '</span><br />';
                   10036:           }
                   10037:           $users{$user}=1; 
1.415     www      10038:           my @answer=split(/\,/,$env{$key});
                   10039:           my $sum=0;
1.522     www      10040:           my $realnumber=$number;
1.415     www      10041:           for (my $i=0;$i<$number;$i++) {
1.576     www      10042:              if  ($correct[$i] eq '-') {
                   10043:                 $realnumber--;
1.644     www      10044:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10045:                 if ($gradingmechanism eq 'attendance') {
                   10046:                    $sum+=$pcorrect;
1.576     www      10047:                 } elsif ($correct[$i] eq '*') {
1.522     www      10048:                    $sum+=$pcorrect;
1.415     www      10049:                 } else {
1.644     www      10050: # We actually grade if correct or not
                   10051:                    my $increment=$pincorrect;
                   10052: # Special case: numerical answer "0"
                   10053:                    if ($correct[$i] eq '0') {
                   10054:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10055:                          $increment=$pcorrect;
                   10056:                       }
                   10057: # General numerical answer, both evaluate to something non-zero
                   10058:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10059:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10060:                          $increment=$pcorrect;
                   10061:                       }
                   10062: # Must be just alphanumeric
                   10063:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10064:                       $increment=$pcorrect;
1.415     www      10065:                    }
1.644     www      10066:                    $sum+=$increment;
1.415     www      10067:                 }
                   10068:              }
                   10069:           }
1.522     www      10070:           my $ave=$sum/(100*$realnumber);
1.416     www      10071: # Store
                   10072:           my ($username,$domain)=split(/\:/,$user);
                   10073:           my %grades=();
                   10074:           $grades{"resource.$part.solved"}='correct_by_override';
                   10075:           $grades{"resource.$part.awarded"}=$ave;
                   10076:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10077:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10078:                                                  $env{'request.course.id'},
                   10079:                                                  $domain,$username);
                   10080:           if ($returncode ne 'ok') {
                   10081:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10082:           } else {
                   10083:              $storecount++;
                   10084:           }
1.415     www      10085:        }
                   10086:     }
                   10087: # We are done
1.549     hauer    10088:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10089:              '</td>'.
                   10090:              &Apache::loncommon::end_data_table_row().
                   10091:              &Apache::loncommon::end_data_table();
1.614     www      10092:     return $result;
1.414     www      10093: }
                   10094: 
1.582     raeburn  10095: sub navmap_errormsg {
                   10096:     return '<div class="LC_error">'.
                   10097:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10098:            &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  10099:            '</div>';
                   10100: }
1.607     droeschl 10101: 
1.609     www      10102: sub startpage {
1.671     raeburn  10103:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10104:     if ($nomenu) {
                   10105:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10106:     } else {
                   10107:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10108:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10109:                                                  {'bread_crumbs' => $crumbs}));
                   10110:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10111:     }
1.613     www      10112:     unless ($nodisplayflag) {
1.671     raeburn  10113:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10114:     }
1.607     droeschl 10115: }
1.582     raeburn  10116: 
1.622     www      10117: sub select_problem {
                   10118:     my ($r)=@_;
1.632     www      10119:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10120:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10121:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10122:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10123: }
                   10124: 
1.1       albertel 10125: sub handler {
1.41      ng       10126:     my $request=$_[0];
1.434     albertel 10127:     &reset_caches();
1.646     raeburn  10128:     if ($request->header_only) {
                   10129:         &Apache::loncommon::content_type($request,'text/html');
                   10130:         $request->send_http_header;
                   10131:         return OK;
                   10132:     }
                   10133:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10134: 
1.664     raeburn  10135: # see what command we need to execute
                   10136: 
                   10137:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10138:     my $command=$commands[0];
                   10139: 
1.646     raeburn  10140:     &init_perm();
                   10141:     if (!$env{'request.course.id'}) {
1.664     raeburn  10142:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10143:                 ($command =~ /^scantronupload/)) {
                   10144:             # Not in a course.
                   10145:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10146:             return HTTP_NOT_ACCEPTABLE;
                   10147:         }
1.646     raeburn  10148:     } elsif (!%perm) {
                   10149:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10150:         return OK;
1.41      ng       10151:     }
1.646     raeburn  10152:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10153:     $request->send_http_header;
1.646     raeburn  10154: 
1.160     albertel 10155:     if ($#commands > 0) {
                   10156: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10157:     }
1.608     www      10158: 
                   10159: # see what the symb is
                   10160: 
                   10161:     my $symb=$env{'form.symb'};
                   10162:     unless ($symb) {
                   10163:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10164:        $symb=&Apache::lonnet::symbread($url);
                   10165:     }
1.646     raeburn  10166:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10167: 
1.513     foxr     10168:     $ssi_error = 0;
1.637     www      10169:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10170: #
1.637     www      10171: # Not called from a resource, but inside a course
1.601     www      10172: #    
1.622     www      10173:         &startpage($request,undef,[],1,1);
                   10174:         &select_problem($request);
1.41      ng       10175:     } else {
1.104     albertel 10176: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10177:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10178:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10179:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10180:                     &choose_task_version_form($symb,$env{'form.student'},
                   10181:                                               $env{'form.userdom'});
                   10182:             }
                   10183:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10184:             if ($versionform) {
                   10185:                 $request->print($versionform);
                   10186:             }
                   10187:             $request->print('<br clear="all" />');
1.611     www      10188: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10189:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10190:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10191:                 &choose_task_version_form($symb,$env{'form.student'},
                   10192:                                           $env{'form.userdom'},
                   10193:                                           $env{'form.inhibitmenu'});
                   10194:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10195:             if ($versionform) {
                   10196:                 $request->print($versionform);
                   10197:             }
                   10198:             $request->print('<br clear="all" />');
                   10199:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10200: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10201:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10202:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10203: 	    &pickStudentPage($request,$symb);
1.103     albertel 10204: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10205:             &startpage($request,$symb,
                   10206:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10207:                                        {href=>'',text=>'Select student'},
                   10208:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10209: 	    &displayPage($request,$symb);
1.104     albertel 10210: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10212:                                        {href=>'',text=>'Select student'},
                   10213:                                        {href=>'',text=>'Grade student'},
                   10214:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10215: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10216: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10217:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10218:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10219: 	    &processGroup($request,$symb);
1.104     albertel 10220: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10221:             &startpage($request,$symb);
                   10222: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10223: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10224:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10225: 	    $request->print(&submit_options($request,$symb));
1.598     www      10226:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10227:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10228:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10229:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10230:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10231:             $request->print(&submit_options_table($request,$symb));
1.598     www      10232:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10233:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10234:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10235: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10236:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10237: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10238: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10239:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10240:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10241: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10242: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10243:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10244:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10245:                                                                              text=>"Modify grades"},
                   10246:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10247: 	    $request->print(&editgrades($request,$symb));
1.602     www      10248:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10249:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10250:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10251: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10253:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10254: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10255:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10256:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10257:             $request->print(&process_clicker($request,$symb));
1.400     www      10258:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10260:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10261:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10262:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10263:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10264:                                        {href=>'', text=>'Process clicker file'},
                   10265:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10266:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10267: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10268:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10269: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10270: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10271:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10272: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10273: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10274:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10275: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10276: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10277: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10278:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10279: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10280: 	    } else {
1.257     albertel 10281: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10282: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10283: 		} else {
1.257     albertel 10284: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10285: 		}
1.627     www      10286:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10287: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10288: 	    }
1.246     albertel 10289: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10290:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10291: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10292: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10294: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10295:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10296:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10297:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10298: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10299:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10300: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10301: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10302:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10303: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10304:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10305:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10306: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10307:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10308:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10309:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10310:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10311: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10313:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10314:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10315: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10317:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10318:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10320:             $request->print(&checkscantron_results($request,$symb));
                   10321:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10322:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10323:             $request->print(&submit_options_download($request,$symb));
                   10324:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10325:             &startpage($request,$symb,
                   10326:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10327:     {href=>'', text=>'Download submissions'}]);
                   10328:             &submit_download_link($request,$symb);
1.106     albertel 10329: 	} elsif ($command) {
1.620     www      10330:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10331: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10332: 	}
1.2       albertel 10333:     }
1.513     foxr     10334:     if ($ssi_error) {
                   10335: 	&ssi_print_error($request);
                   10336:     }
1.671     raeburn  10337:     if ($env{'form.inhibitmenu'}) {
                   10338:         $request->print(&Apache::loncommon::end_page());
                   10339:     } else {
                   10340:         &Apache::lonquickgrades::endGradeScreen($request);
                   10341:     }
1.434     albertel 10342:     &reset_caches();
1.646     raeburn  10343:     return OK;
1.44      ng       10344: }
                   10345: 
1.1       albertel 10346: 1;
                   10347: 
1.13      albertel 10348: __END__;
1.531     jms      10349: 
                   10350: 
                   10351: =head1 NAME
                   10352: 
                   10353: Apache::grades
                   10354: 
                   10355: =head1 SYNOPSIS
                   10356: 
                   10357: Handles the viewing of grades.
                   10358: 
                   10359: This is part of the LearningOnline Network with CAPA project
                   10360: described at http://www.lon-capa.org.
                   10361: 
                   10362: =head1 OVERVIEW
                   10363: 
                   10364: Do an ssi with retries:
1.715   ! bisitz   10365: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10366: 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
                   10367: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10368: 
                   10369: At least the logic that drives this has been pulled out into loncommon.
                   10370: 
                   10371: 
                   10372: 
                   10373: ssi_with_retries - Does the server side include of a resource.
                   10374:                      if the ssi call returns an error we'll retry it up to
                   10375:                      the number of times requested by the caller.
1.715   ! bisitz   10376:                      If we still have a problem, no text is appended to the
1.531     jms      10377:                      output and we set some global variables.
                   10378:                      to indicate to the caller an SSI error occurred.  
                   10379:                      All of this is supposed to deal with the issues described
1.715   ! bisitz   10380:                      in LON-CAPA BZ 5631 see:
1.531     jms      10381:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10382:                      by informing the user that this happened.
                   10383: 
                   10384: Parameters:
                   10385:   resource   - The resource to include.  This is passed directly, without
                   10386:                interpretation to lonnet::ssi.
                   10387:   form       - The form hash parameters that guide the interpretation of the resource
                   10388:                
                   10389:   retries    - Number of retries allowed before giving up completely.
                   10390: Returns:
                   10391:   On success, returns the rendered resource identified by the resource parameter.
                   10392: Side Effects:
                   10393:   The following global variables can be set:
                   10394:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10395:                               It is up to the caller to initialize this to false
                   10396:                               if desired.
                   10397:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10398:                               of the resource that could not be rendered by the ssi
                   10399:                               call.
                   10400:    ssi_error_message   - The error string fetched from the ssi response
                   10401:                               in the event of an error.
                   10402: 
                   10403: 
                   10404: =head1 HANDLER SUBROUTINE
                   10405: 
                   10406: ssi_with_retries()
                   10407: 
                   10408: =head1 SUBROUTINES
                   10409: 
                   10410: =over
                   10411: 
1.671     raeburn  10412: =head1 Routines to display previous version of a Task for a specific student
                   10413: 
                   10414: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10415: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10416: requires a proctor to check-in the student, a new version of the Task will
                   10417: be created when the student is checked in to the new opportunity.
                   10418: 
                   10419: If a particular student has tried two or more versions of a particular task,
                   10420: the submission screen provides a user with vgr privileges (e.g., a Course
                   10421: Coordinator) the ability to display a previous version worked on by the
                   10422: student.  By default, the current version is displayed. If a previous version
                   10423: has been selected for display, submission data are only shown that pertain
                   10424: to that particular version, and the interface to submit grades is not shown.
                   10425: 
                   10426: =over 4
                   10427: 
                   10428: =item show_previous_task_version()
                   10429: 
                   10430: Displays a specified version of a student's Task, as the student sees it.
                   10431: 
                   10432: Inputs: 2
                   10433:         request - request object
                   10434:         symb    - unique symb for current instance of resource
                   10435: 
                   10436: Output: None.
                   10437: 
                   10438: Side Effects: calls &show_problem() to print version of Task, with
                   10439:               version contained in form item: $env{'form.previousversion'}
                   10440: 
                   10441: =item choose_task_version_form()
                   10442: 
                   10443: Displays a web form used to select which version of a student's view of a
                   10444: Task should be displayed.  Either launches a pop-up window, or replaces
                   10445: content in existing pop-up, or replaces page in main window.
                   10446: 
                   10447: Inputs: 4
                   10448:         symb    - unique symb for current instance of resource
                   10449:         uname   - username of student
                   10450:         udom    - domain of student
                   10451:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10452:                   breadcrumbs etc., are displayed
                   10453: 
                   10454: Output: 4
                   10455:         current   - student's current version
                   10456:         displayed - student's version being displayed
                   10457:         result    - scalar containing HTML for web form used to switch to
                   10458:                     a different version (or a link to close window, if pop-up).
                   10459:         js        - javascript for processing selection in versions web form
                   10460: 
                   10461: Side Effects: None.
                   10462: 
                   10463: =item previous_display_javascript()
                   10464: 
                   10465: Inputs: 2
                   10466:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10467:                   breadcrumbs etc., are displayed.
                   10468:         current - student's current version number.
                   10469: 
                   10470: Output: 1
                   10471:         js      - javascript for processing selection in versions web form.
                   10472: 
                   10473: Side Effects: None.
                   10474: 
                   10475: =back
                   10476: 
                   10477: =head1 Routines to process bubblesheet data.
                   10478: 
                   10479: =over 4
                   10480: 
1.531     jms      10481: =item scantron_get_correction() : 
                   10482: 
                   10483:    Builds the interface screen to interact with the operator to fix a
                   10484:    specific error condition in a specific scanline
                   10485: 
                   10486:  Arguments:
                   10487:     $r           - Apache request object
                   10488:     $i           - number of the current scanline
                   10489:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10490:     $scan_config - hash ref as returned from &get_scantron_config()
                   10491:     $line        - full contents of the current scanline
                   10492:     $error       - error condition, valid values are
                   10493:                    'incorrectCODE', 'duplicateCODE',
                   10494:                    'doublebubble', 'missingbubble',
                   10495:                    'duplicateID', 'incorrectID'
                   10496:     $arg         - extra information needed
                   10497:        For errors:
                   10498:          - duplicateID   - paper number that this studentID was seen before on
                   10499:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10500:                            seen on before
                   10501:          - incorrectCODE - current incorrect CODE 
                   10502:          - doublebubble  - array ref of the bubble lines that have double
                   10503:                            bubble errors
                   10504:          - missingbubble - array ref of the bubble lines that have missing
                   10505:                            bubble errors
                   10506: 
1.691     raeburn  10507:    $randomorder - True if exam folder has randomorder set
                   10508:    $randompick  - True if exam folder has randompick set
                   10509:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10510:                      for current line to question number used for same question
                   10511:                      in "Master Seqence" (as seen by Course Coordinator).
                   10512:    $startline   - Reference to hash where key is question number (0 is first)
                   10513:                   and value is number of first bubble line for current student
                   10514:                   or code-based randompick and/or randomorder.
                   10515: 
                   10516: 
                   10517: 
1.531     jms      10518: =item  scantron_get_maxbubble() : 
                   10519: 
1.582     raeburn  10520:    Arguments:
                   10521:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10522:                       failure to retrieve a navmap object.
                   10523:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10524:        calling routine should trap the error condition and display the warning
                   10525:        found in &navmap_errormsg().
                   10526: 
1.649     raeburn  10527:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10528: 
1.531     jms      10529:    Returns the maximum number of bubble lines that are expected to
                   10530:    occur. Does this by walking the selected sequence rendering the
                   10531:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10532:    for what the current value of the problem counter is.
                   10533: 
                   10534:    Caches the results to $env{'form.scantron_maxbubble'},
                   10535:    $env{'form.scantron.bubble_lines.n'}, 
                   10536:    $env{'form.scantron.first_bubble_line.n'} and
                   10537:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10538:    which are the total number of bubble lines, the number of bubble
1.531     jms      10539:    lines for response n and number of the first bubble line for response n,
                   10540:    and a comma separated list of numbers of bubble lines for sub-questions
                   10541:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10542: 
                   10543: 
                   10544: =item  scantron_validate_missingbubbles() : 
                   10545: 
                   10546:    Validates all scanlines in the selected file to not have any
                   10547:     answers that don't have bubbles that have not been verified
                   10548:     to be bubble free.
                   10549: 
                   10550: =item  scantron_process_students() : 
                   10551: 
1.659     raeburn  10552:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10553: 
                   10554:    The parsed scanline hash is added to %env 
                   10555: 
                   10556:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10557:    foreach resource , with the form data of
                   10558: 
                   10559: 	'submitted'     =>'scantron' 
                   10560: 	'grade_target'  =>'grade',
                   10561: 	'grade_username'=> username of student
                   10562: 	'grade_domain'  => domain of student
                   10563: 	'grade_courseid'=> of course
                   10564: 	'grade_symb'    => symb of resource to grade
                   10565: 
                   10566:     This triggers a grading pass. The problem grading code takes care
                   10567:     of converting the bubbled letter information (now in %env) into a
                   10568:     valid submission.
                   10569: 
                   10570: =item  scantron_upload_scantron_data() :
                   10571: 
1.659     raeburn  10572:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10573: 
                   10574: =item  scantron_upload_scantron_data_save() : 
                   10575: 
                   10576:    Adds a provided bubble information data file to the course if user
                   10577:    has the correct privileges to do so. 
                   10578: 
                   10579: =item  valid_file() :
                   10580: 
                   10581:    Validates that the requested bubble data file exists in the course.
                   10582: 
                   10583: =item  scantron_download_scantron_data() : 
                   10584: 
                   10585:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10586:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10587:    course.
                   10588: 
                   10589: =item  scantron_validate_ID() : 
                   10590: 
                   10591:    Validates all scanlines in the selected file to not have any
1.556     weissno  10592:    invalid or underspecified student/employee IDs
1.531     jms      10593: 
1.582     raeburn  10594: =item navmap_errormsg() :
                   10595: 
                   10596:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10597:    Should be called whenever the request to instantiate a navmap object fails.
                   10598: 
                   10599: =back
1.582     raeburn  10600: 
1.531     jms      10601: =back
                   10602: 
                   10603: =cut

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