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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.717   ! bisitz      4: # $Id: grades.pm,v 1.716 2014/01/30 18:04:36 bisitz Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
                    333: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    334: 	my ($toprow,$bottomrow);
                    335: 	foreach my $foil (@$order) {
                    336: 	    if ($grading{$foil} == 1) {
                    337: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    338: 	    } else {
                    339: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  342: 	}
                    343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   346: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  347:     } elsif ($response eq 'match') {
                    348: 	my %answer=&Apache::lonnet::str2hash($answer);
                    349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    350: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    351: 	my ($toprow,$middlerow,$bottomrow);
                    352: 	foreach my $foil (@$order) {
                    353: 	    my $item=shift(@items);
                    354: 	    if ($grading{$foil} == 1) {
                    355: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  356: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  357: 	    } else {
                    358: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  359: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  360: 	    }
1.398     albertel  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        362: 	}
1.126     ng        363: 	return '<blockquote><table border="1">'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  366: 	    $middlerow.'</tr>'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   368: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  369:     } elsif ($response eq 'radiobutton') {
                    370: 	my %answer=&Apache::lonnet::str2hash($answer);
                    371: 	my ($toprow,$bottomrow);
1.434     albertel  372: 	my $correct = 
1.640     raeburn   373: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  374: 	foreach my $foil (@$order) {
1.148     albertel  375: 	    if (exists($answer{$foil})) {
1.434     albertel  376: 		if ($foil eq $correct) {
1.466     albertel  377: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  378: 		} else {
1.466     albertel  379: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  380: 		}
                    381: 	    } else {
1.466     albertel  382: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  383: 	    }
1.398     albertel  384: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  385: 	}
                    386: 	return '<blockquote><table border="1">'.
1.466     albertel  387: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    388: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   389: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  390:     } elsif ($response eq 'essay') {
1.257     albertel  391: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        392: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  393: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    394: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        395: 
1.257     albertel  396: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    397: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    398: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    399: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    400: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    401: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        402: 	}
1.166     albertel  403: 	$answer =~ s-\n-<br />-g;
                    404: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  405:     } elsif ( $response eq 'organic') {
                    406: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    407: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    408: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    409: 	return $result;
1.335     albertel  410:     } elsif ( $response eq 'Task') {
                    411: 	if ( $answer eq 'SUBMITTED') {
                    412: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  413: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  414: 	    return $result;
                    415: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    416: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    417: 			       keys(%{$record}));
                    418: 	    return join('<br />',($version,@matches));
                    419: 			       
                    420: 			       
                    421: 	} else {
                    422: 	    my $result =
                    423: 		'<p>'
                    424: 		.&mt('Overall result: [_1]',
                    425: 		     $record->{$version."resource.$respid.$partid.status"})
                    426: 		.'</p>';
                    427: 	    
                    428: 	    $result .= '<ul>';
                    429: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    430: 			     keys(%{$record}));
                    431: 	    foreach my $grade (sort(@grade)) {
                    432: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    433: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    434: 				     $dim, $record->{$grade}).
                    435: 			  '</li>';
                    436: 	    }
                    437: 	    $result.='</ul>';
                    438: 	    return $result;
                    439: 	}
1.716     bisitz    440:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    441:         # Respect multiple input fields, see Bug #5409
1.440     albertel  442: 	$answer = 
                    443: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    444: 							      $answer);
1.122     ng        445:     }
1.118     ng        446:     return $answer;
                    447: }
                    448: 
                    449: #-- A couple of common js functions
                    450: sub commonJSfunctions {
                    451:     my $request = shift;
1.597     wenzelju  452:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        453:     function radioSelection(radioButton) {
                    454: 	var selection=null;
                    455: 	if (radioButton.length > 1) {
                    456: 	    for (var i=0; i<radioButton.length; i++) {
                    457: 		if (radioButton[i].checked) {
                    458: 		    return radioButton[i].value;
                    459: 		}
                    460: 	    }
                    461: 	} else {
                    462: 	    if (radioButton.checked) return radioButton.value;
                    463: 	}
                    464: 	return selection;
                    465:     }
                    466: 
                    467:     function pullDownSelection(selectOne) {
                    468: 	var selection="";
                    469: 	if (selectOne.length > 1) {
                    470: 	    for (var i=0; i<selectOne.length; i++) {
                    471: 		if (selectOne[i].selected) {
                    472: 		    return selectOne[i].value;
                    473: 		}
                    474: 	    }
                    475: 	} else {
1.138     albertel  476:             // only one value it must be the selected one
                    477: 	    return selectOne.value;
1.118     ng        478: 	}
                    479:     }
                    480: COMMONJSFUNCTIONS
                    481: }
                    482: 
1.44      ng        483: #--- Dumps the class list with usernames,list of sections,
                    484: #--- section, ids and fullnames for each user.
                    485: sub getclasslist {
1.449     banghart  486:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  487:     my @getsec;
1.450     banghart  488:     my @getgroup;
1.442     banghart  489:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  490:     if (!ref($getsec)) {
                    491: 	if ($getsec ne '' && $getsec ne 'all') {
                    492: 	    @getsec=($getsec);
                    493: 	}
                    494:     } else {
                    495: 	@getsec=@{$getsec};
                    496:     }
                    497:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  498:     if (!ref($getgroup)) {
                    499: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    500: 	    @getgroup=($getgroup);
                    501: 	}
                    502:     } else {
                    503: 	@getgroup=@{$getgroup};
                    504:     }
                    505:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  506: 
1.449     banghart  507:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  508:     # Bail out if we were unable to get the classlist
1.56      matthew   509:     return if (! defined($classlist));
1.449     banghart  510:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   511:     #
                    512:     my %sections;
                    513:     my %fullnames;
1.205     matthew   514:     foreach my $student (keys(%$classlist)) {
                    515:         my $end      = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    517:         my $start    = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    519:         my $id       = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    521:         my $section  = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    523:         my $fullname = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    525:         my $status   = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  527:         my $group   = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        529: 	# filter students according to status selected
1.442     banghart  530: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    531: 	    if (!($stu_status =~ $status)) {
1.450     banghart  532: 		delete($classlist->{$student});
1.76      ng        533: 		next;
                    534: 	    }
                    535: 	}
1.450     banghart  536: 	# filter students according to groups selected
1.453     banghart  537: 	my @stu_groups = split(/,/,$group);
1.450     banghart  538: 	if (@getgroup) {
                    539: 	    my $exclude = 1;
1.454     banghart  540: 	    foreach my $grp (@getgroup) {
                    541: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  542: 	            if ($stu_group eq $grp) {
                    543: 	                $exclude = 0;
                    544:     	            } 
1.450     banghart  545: 	        }
1.453     banghart  546:     	        if (($grp eq 'none') && !$group) {
                    547:         	        $exclude = 0;
                    548:         	}
1.450     banghart  549: 	    }
                    550: 	    if ($exclude) {
                    551: 	        delete($classlist->{$student});
                    552: 	    }
                    553: 	}
1.205     matthew   554: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  555: 	if (&canview($section)) {
1.291     albertel  556: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  557: 		$sections{$section}++;
1.450     banghart  558: 		if ($classlist->{$student}) {
                    559: 		    $fullnames{$student}=$fullname;
                    560: 		}
1.103     albertel  561: 	    } else {
1.205     matthew   562: 		delete($classlist->{$student});
1.103     albertel  563: 	    }
                    564: 	} else {
1.205     matthew   565: 	    delete($classlist->{$student});
1.103     albertel  566: 	}
1.44      ng        567:     }
                    568:     my %seen = ();
1.56      matthew   569:     my @sections = sort(keys(%sections));
                    570:     return ($classlist,\@sections,\%fullnames);
1.44      ng        571: }
                    572: 
1.103     albertel  573: sub canmodify {
                    574:     my ($sec)=@_;
                    575:     if ($perm{'mgr'}) {
                    576: 	if (!defined($perm{'mgr_section'})) {
                    577: 	    # can modify whole class
                    578: 	    return 1;
                    579: 	} else {
                    580: 	    if ($sec eq $perm{'mgr_section'}) {
                    581: 		#can modify the requested section
                    582: 		return 1;
                    583: 	    } else {
                    584: 		# can't modify the request section
                    585: 		return 0;
                    586: 	    }
                    587: 	}
                    588:     }
                    589:     #can't modify
                    590:     return 0;
                    591: }
                    592: 
                    593: sub canview {
                    594:     my ($sec)=@_;
                    595:     if ($perm{'vgr'}) {
                    596: 	if (!defined($perm{'vgr_section'})) {
                    597: 	    # can modify whole class
                    598: 	    return 1;
                    599: 	} else {
                    600: 	    if ($sec eq $perm{'vgr_section'}) {
                    601: 		#can modify the requested section
                    602: 		return 1;
                    603: 	    } else {
                    604: 		# can't modify the request section
                    605: 		return 0;
                    606: 	    }
                    607: 	}
                    608:     }
                    609:     #can't modify
                    610:     return 0;
                    611: }
                    612: 
1.44      ng        613: #--- Retrieve the grade status of a student for all the parts
                    614: sub student_gradeStatus {
1.324     albertel  615:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  616:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        617:     my %partstatus = ();
                    618:     foreach (@$partlist) {
1.128     ng        619: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        620: 	$status              = 'nothing' if ($status eq '');
                    621: 	$partstatus{$_}      = $status;
                    622: 	my $subkey           = "resource.$_.submitted_by";
                    623: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    624:     }
                    625:     return %partstatus;
                    626: }
                    627: 
1.45      ng        628: # hidden form and javascript that calls the form
                    629: # Use by verifyscript and viewgrades
                    630: # Shows a student's view of problem and submission
                    631: sub jscriptNform {
1.324     albertel  632:     my ($symb) = @_;
1.442     banghart  633:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  634:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        635: 	'    function viewOneStudent(user,domain) {'."\n".
                    636: 	'	document.onestudent.student.value = user;'."\n".
                    637: 	'	document.onestudent.userdom.value = domain;'."\n".
                    638: 	'	document.onestudent.submit();'."\n".
                    639: 	'    }'."\n".
1.597     wenzelju  640: 	"\n");
1.45      ng        641:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  642: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  643: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        644: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    645: 	'<input type="hidden" name="student" value="" />'."\n".
                    646: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    647: 	'</form>'."\n";
                    648:     return $jscript;
                    649: }
1.39      ng        650: 
1.447     foxr      651: 
                    652: 
1.315     bowersj2  653: # Given the score (as a number [0-1] and the weight) what is the final
                    654: # point value? This function will round to the nearest tenth, third,
                    655: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  656: sub compute_points {
1.315     bowersj2  657:     my ($score, $weight) = @_;
                    658:     
                    659:     my $tolerance = .00001;
                    660:     my $points = $score * $weight;
                    661: 
                    662:     # Check for nearness to 1/x.
                    663:     my $check_for_nearness = sub {
                    664:         my ($factor) = @_;
                    665:         my $num = ($points * $factor) + $tolerance;
                    666:         my $floored_num = floor($num);
1.316     albertel  667:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  668:             return $floored_num / $factor;
                    669:         }
                    670:         return $points;
                    671:     };
                    672: 
                    673:     $points = $check_for_nearness->(10);
                    674:     $points = $check_for_nearness->(3);
                    675:     $points = $check_for_nearness->(4);
                    676:     
                    677:     return $points;
                    678: }
                    679: 
1.44      ng        680: #------------------ End of general use routines --------------------
1.87      www       681: 
                    682: #
                    683: # Find most similar essay
                    684: #
                    685: 
                    686: sub most_similar {
1.674     raeburn   687:     my ($uname,$udom,$symb,$uessay)=@_;
                    688: 
                    689:     unless ($symb) { return ''; }
                    690: 
                    691:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       692: 
                    693: # ignore spaces and punctuation
                    694: 
                    695:     $uessay=~s/\W+/ /gs;
                    696: 
1.282     www       697: # ignore empty submissions (occuring when only files are sent)
                    698: 
1.598     www       699:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       700: 
1.87      www       701: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       702:     my $limit=0.6;
1.87      www       703:     my $sname='';
                    704:     my $sdom='';
                    705:     my $scrsid='';
                    706:     my $sessay='';
                    707: # go through all essays ...
1.674     raeburn   708:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  709: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       710: # ... except the same student
1.426     albertel  711:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   712: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  713: 	$tessay=~s/\W+/ /gs;
1.87      www       714: # String similarity gives up if not even limit
1.426     albertel  715: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       716: # Found one
1.426     albertel  717: 	if ($tsimilar>$limit) {
                    718: 	    $limit=$tsimilar;
                    719: 	    $sname=$tname;
                    720: 	    $sdom=$tdom;
                    721: 	    $scrsid=$tcrsid;
1.674     raeburn   722: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  723: 	}
1.87      www       724:     }
1.88      www       725:     if ($limit>0.6) {
1.87      www       726:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    727:     } else {
                    728:        return ('','','','',0);
                    729:     }
                    730: }
                    731: 
1.44      ng        732: #-------------------------------------------------------------------
                    733: 
                    734: #------------------------------------ Receipt Verification Routines
1.45      ng        735: #
1.602     www       736: 
                    737: sub initialverifyreceipt {
1.608     www       738:    my ($request,$symb) = @_;
1.602     www       739:    &commonJSfunctions($request);
1.694     bisitz    740:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       741:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    742:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       743:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    744:         '<input type="hidden" name="command" value="verify" />'.
                    745:         "</form>\n";
1.602     www       746: }
                    747: 
1.44      ng        748: #--- Check whether a receipt number is valid.---
                    749: sub verifyreceipt {
1.608     www       750:     my ($request,$symb)  = @_;
1.44      ng        751: 
1.257     albertel  752:     my $courseid = $env{'request.course.id'};
1.184     www       753:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  754: 	$env{'form.receipt'};
1.44      ng        755:     $receipt     =~ s/[^\-\d]//g;
                    756: 
1.487     albertel  757:     my $title.=
                    758: 	'<h3><span class="LC_info">'.
1.605     www       759: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    760: 	'</span></h3>'."\n";
1.44      ng        761: 
                    762:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   763:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  764:     
                    765:     my $receiptparts=0;
1.390     albertel  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  768:     my $parts=['0'];
1.582     raeburn   769:     if ($receiptparts) {
                    770:         my $res_error; 
                    771:         ($parts)=&response_type($symb,\$res_error);
                    772:         if ($res_error) {
                    773:             return &navmap_errormsg();
                    774:         } 
                    775:     }
1.486     albertel  776:     
                    777:     my $header = 
                    778: 	&Apache::loncommon::start_data_table().
                    779: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  780: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    781: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    782: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  783:     if ($receiptparts) {
1.487     albertel  784: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  785:     }
                    786:     $header.=
                    787: 	&Apache::loncommon::end_data_table_header_row();
                    788: 
1.294     albertel  789:     foreach (sort 
                    790: 	     {
                    791: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    792: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    793: 		 }
                    794: 		 return $a cmp $b;
                    795: 	     } (keys(%$fullname))) {
1.44      ng        796: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  797: 	foreach my $part (@$parts) {
                    798: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  799: 		$contents.=
                    800: 		    &Apache::loncommon::start_data_table_row().
                    801: 		    '<td>&nbsp;'."\n".
1.177     albertel  802: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  803: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  804: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    805: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    806: 		if ($receiptparts) {
                    807: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    808: 		}
1.486     albertel  809: 		$contents.= 
                    810: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  811: 		
                    812: 		$matches++;
                    813: 	    }
1.44      ng        814: 	}
                    815:     }
                    816:     if ($matches == 0) {
1.584     bisitz    817:         $string = $title
                    818:                  .'<p class="LC_warning">'
                    819:                  .&mt('No match found for the above receipt number.')
                    820:                  .'</p>';
1.44      ng        821:     } else {
1.324     albertel  822: 	$string = &jscriptNform($symb).$title.
1.487     albertel  823: 	    '<p>'.
1.584     bisitz    824: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  825: 	    '</p>'.
1.486     albertel  826: 	    $header.
                    827: 	    $contents.
                    828: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        829:     }
1.614     www       830:     return $string;
1.44      ng        831: }
                    832: 
                    833: #--- This is called by a number of programs.
                    834: #--- Called from the Grading Menu - View/Grade an individual student
                    835: #--- Also called directly when one clicks on the subm button 
                    836: #    on the problem page.
1.30      ng        837: sub listStudents {
1.617     www       838:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  839: 
1.257     albertel  840:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    841:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    842:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  843:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       844:     unless ($submitonly) {
                    845:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    846:     }
1.49      albertel  847: 
1.632     www       848:     my $result='';
1.623     www       849:     my $res_error;
                    850:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  851: 
1.559     raeburn   852:     my %lt = &Apache::lonlocal::texthash (
                    853: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    854: 		'single'   => 'Please select the student before clicking on the Next button.',
                    855: 	     );
1.597     wenzelju  856:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        857:     function checkSelect(checkBox) {
                    858: 	var ctr=0;
                    859: 	var sense="";
                    860: 	if (checkBox.length > 1) {
                    861: 	    for (var i=0; i<checkBox.length; i++) {
                    862: 		if (checkBox[i].checked) {
                    863: 		    ctr++;
                    864: 		}
                    865: 	    }
1.485     albertel  866: 	    sense = '$lt{'multiple'}';
1.110     ng        867: 	} else {
                    868: 	    if (checkBox.checked) {
                    869: 		ctr = 1;
                    870: 	    }
1.485     albertel  871: 	    sense = '$lt{'single'}';
1.110     ng        872: 	}
                    873: 	if (ctr == 0) {
1.485     albertel  874: 	    alert(sense);
1.110     ng        875: 	    return false;
                    876: 	}
                    877: 	document.gradesub.submit();
                    878:     }
                    879: 
                    880:     function reLoadList(formname) {
1.112     ng        881: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        882: 	formname.command.value = 'submission';
                    883: 	formname.submit();
                    884:     }
1.45      ng        885: LISTJAVASCRIPT
                    886: 
1.118     ng        887:     &commonJSfunctions($request);
1.41      ng        888:     $request->print($result);
1.39      ng        889: 
1.154     albertel  890:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       891: 	"\n";
1.485     albertel  892: 	
1.561     bisitz    893:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    894:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    895:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    897:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    898:                   .&Apache::lonhtmlcommon::row_closure();
                    899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    900:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    903:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  904: 
                    905:     my $submission_options;
1.442     banghart  906:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    907:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  908:     $env{'form.Status'} = $saveStatus;
1.485     albertel  909:     $submission_options.=
1.592     bisitz    910:         '<span class="LC_nobreak">'.
1.624     www       911:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     912:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    913:         '<span class="LC_nobreak">'.
                    914:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     915:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    916:         '<span class="LC_nobreak">'.
1.628     www       917:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     918:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    919:         '<span class="LC_nobreak">'.
                    920:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     921:         &mt('all submissions with details').'</label></span>';
                    922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    923:                   .$submission_options
                    924:                   .&Apache::lonhtmlcommon::row_closure();
                    925: 
                    926:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    927:                   .'<select name="increment">'
                    928:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    929:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    930:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    931:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    932:                   .'</select>'
                    933:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  934: 
                    935:     $gradeTable .= 
1.432     banghart  936:         &build_section_inputs().
1.45      ng        937: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  938: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        939: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    940: 
1.618     www       941:     if (exists($env{'form.Status'})) {
1.561     bisitz    942: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        943:     } else {
1.561     bisitz    944:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    945:                       .&Apache::lonhtmlcommon::StatusOptions(
                    946:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    947:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        948:     }
1.112     ng        949: 
1.561     bisitz    950:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    951:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    952:                   .&Apache::lonhtmlcommon::row_closure(1)
                    953:                   .&Apache::lonhtmlcommon::end_pick_box();
                    954: 
                    955:     $gradeTable .= '<p>'
1.618     www       956:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    957:                   .'<input type="hidden" name="command" value="processGroup" />'
                    958:                   .'</p>';
1.249     albertel  959: 
                    960: # checkall buttons
                    961:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        962:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    963:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    964:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  965:     $gradeTable.=&check_buttons();
1.450     banghart  966:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  967:     $gradeTable.= &Apache::loncommon::start_data_table().
                    968: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        969:     my $loop = 0;
                    970:     while ($loop < 2) {
1.485     albertel  971: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    972: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       973: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  974: 	    foreach my $part (sort(@$partlist)) {
                    975: 		my $display_part=
                    976: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    977: 		$gradeTable.=
                    978: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        979: 	    }
1.301     albertel  980: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  981: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        982: 	}
                    983: 	$loop++;
1.126     ng        984: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        985:     }
1.474     albertel  986:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        987: 
1.45      ng        988:     my $ctr = 0;
1.294     albertel  989:     foreach my $student (sort 
                    990: 			 {
                    991: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    992: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    993: 			     }
                    994: 			     return $a cmp $b;
                    995: 			 }
                    996: 			 (keys(%$fullname))) {
1.41      ng        997: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  998: 
1.110     ng        999: 	my %status = ();
1.301     albertel 1000: 
                   1001: 	if ($submitonly eq 'queued') {
                   1002: 	    my %queue_status = 
                   1003: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1004: 							$udom,$uname);
                   1005: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1006: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1007: 	}
                   1008: 
1.618     www      1009: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1010: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1011: 	    my $submitted = 0;
1.164     albertel 1012: 	    my $graded = 0;
1.248     albertel 1013: 	    my $incorrect = 0;
1.110     ng       1014: 	    foreach (keys(%status)) {
1.145     albertel 1015: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1016: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1017: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1018: 		
1.110     ng       1019: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1020: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1021: 		    $submitted = 0;
1.150     albertel 1022: 		    my ($part)=split(/\./,$partid);
1.110     ng       1023: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1024: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1025: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1026: 		}
1.41      ng       1027: 	    }
1.248     albertel 1028: 	    
1.156     albertel 1029: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1030: 				     $submitonly eq 'incorrect' ||
                   1031: 				     $submitonly eq 'graded'));
1.248     albertel 1032: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1033: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1034: 	}
1.34      ng       1035: 
1.45      ng       1036: 	$ctr++;
1.249     albertel 1037: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1038:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1039: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1040: 	    if ($ctr%2 ==1) {
                   1041: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1042: 	    }
1.126     ng       1043: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1044:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1045:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1046: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1047: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1048: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1049: 
1.618     www      1050: 	    if ($submitonly ne 'all') {
1.524     raeburn  1051: 		foreach (sort(keys(%status))) {
1.485     albertel 1052: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1053: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1054: 		}
1.41      ng       1055: 	    }
1.126     ng       1056: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1057: 	    if ($ctr%2 ==0) {
                   1058: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1059: 	    }
1.41      ng       1060: 	}
                   1061:     }
1.110     ng       1062:     if ($ctr%2 ==1) {
1.126     ng       1063: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1064: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1065: 		foreach (@$partlist) {
                   1066: 		    $gradeTable.='<td>&nbsp;</td>';
                   1067: 		}
1.301     albertel 1068: 	    } elsif ($submitonly eq 'queued') {
                   1069: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1070: 	    }
1.474     albertel 1071: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1072:     }
                   1073: 
1.474     albertel 1074:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1075:         '<input type="button" '.
                   1076:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1077:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1078:     if ($ctr == 0) {
1.96      albertel 1079: 	my $num_students=(scalar(keys(%$fullname)));
                   1080: 	if ($num_students eq 0) {
1.485     albertel 1081: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1082: 	} else {
1.171     albertel 1083: 	    my $submissions='submissions';
                   1084: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1085: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1086: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1087: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1088: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1089: 		    $num_students).
                   1090: 		'</span><br />';
1.96      albertel 1091: 	}
1.46      ng       1092:     } elsif ($ctr == 1) {
1.474     albertel 1093: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1094:     }
                   1095:     $request->print($gradeTable);
1.44      ng       1096:     return '';
1.10      ng       1097: }
                   1098: 
1.44      ng       1099: #---- Called from the listStudents routine
1.249     albertel 1100: 
                   1101: sub check_script {
                   1102:     my ($form, $type)=@_;
1.597     wenzelju 1103:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1104:     function checkall() {
                   1105:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1106:             ele = document.forms.'.$form.'.elements[i];
                   1107:             if (ele.name == "'.$type.'") {
                   1108:             document.forms.'.$form.'.elements[i].checked=true;
                   1109:                                        }
                   1110:         }
                   1111:     }
                   1112: 
                   1113:     function checksec() {
                   1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1115:             ele = document.forms.'.$form.'.elements[i];
                   1116:            string = document.forms.'.$form.'.chksec.value;
                   1117:            if
                   1118:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1119:               document.forms.'.$form.'.elements[i].checked=true;
                   1120:             }
                   1121:         }
                   1122:     }
                   1123: 
                   1124: 
                   1125:     function uncheckall() {
                   1126:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1127:             ele = document.forms.'.$form.'.elements[i];
                   1128:             if (ele.name == "'.$type.'") {
                   1129:             document.forms.'.$form.'.elements[i].checked=false;
                   1130:                                        }
                   1131:         }
                   1132:     }
                   1133: 
1.597     wenzelju 1134: '."\n");
1.249     albertel 1135:     return $chkallscript;
                   1136: }
                   1137: 
                   1138: sub check_buttons {
1.485     albertel 1139:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1140:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1141:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1142:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1143:     return $buttons;
                   1144: }
                   1145: 
1.44      ng       1146: #     Displays the submissions for one student or a group of students
1.34      ng       1147: sub processGroup {
1.619     www      1148:     my ($request,$symb)  = @_;
1.41      ng       1149:     my $ctr        = 0;
1.155     albertel 1150:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1151:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1152: 
1.396     banghart 1153:     foreach my $student (@stuchecked) {
                   1154: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1155: 	$env{'form.student'}        = $uname;
                   1156: 	$env{'form.userdom'}        = $udom;
                   1157: 	$env{'form.fullname'}       = $fullname;
1.619     www      1158: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1159: 	$ctr++;
                   1160:     }
                   1161:     return '';
1.35      ng       1162: }
1.34      ng       1163: 
1.44      ng       1164: #------------------------------------------------------------------------------------
                   1165: #
                   1166: #-------------------------- Next few routines handles grading by student, essentially
                   1167: #                           handles essay response type problem/part
                   1168: #
                   1169: #--- Javascript to handle the submission page functionality ---
                   1170: sub sub_page_js {
                   1171:     my $request = shift;
1.539     riegler  1172: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1173:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1174:     function updateRadio(formname,id,weight) {
1.125     ng       1175: 	var gradeBox = formname["GD_BOX"+id];
                   1176: 	var radioButton = formname["RADVAL"+id];
                   1177: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1178: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1179: 	gradeBox.value = pts;
                   1180: 	var resetbox = false;
                   1181: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1182: 	    alert("$alertmsg"+pts);
1.71      ng       1183: 	    for (var i=0; i<radioButton.length; i++) {
                   1184: 		if (radioButton[i].checked) {
                   1185: 		    gradeBox.value = i;
                   1186: 		    resetbox = true;
                   1187: 		}
                   1188: 	    }
                   1189: 	    if (!resetbox) {
                   1190: 		formtextbox.value = "";
                   1191: 	    }
                   1192: 	    return;
1.44      ng       1193: 	}
1.71      ng       1194: 
                   1195: 	if (pts > weight) {
                   1196: 	    var resp = confirm("You entered a value ("+pts+
                   1197: 			       ") greater than the weight for the part. Accept?");
                   1198: 	    if (resp == false) {
1.125     ng       1199: 		gradeBox.value = oldpts;
1.71      ng       1200: 		return;
                   1201: 	    }
1.44      ng       1202: 	}
1.13      albertel 1203: 
1.71      ng       1204: 	for (var i=0; i<radioButton.length; i++) {
                   1205: 	    radioButton[i].checked=false;
                   1206: 	    if (pts == i && pts != "") {
                   1207: 		radioButton[i].checked=true;
                   1208: 	    }
                   1209: 	}
                   1210: 	updateSelect(formname,id);
1.125     ng       1211: 	formname["stores"+id].value = "0";
1.41      ng       1212:     }
1.5       albertel 1213: 
1.72      ng       1214:     function writeBox(formname,id,pts) {
1.125     ng       1215: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1216: 	if (checkSolved(formname,id) == 'update') {
                   1217: 	    gradeBox.value = pts;
                   1218: 	} else {
1.125     ng       1219: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1220: 	    gradeBox.value = oldpts;
1.125     ng       1221: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1222: 	    for (var i=0; i<radioButton.length; i++) {
                   1223: 		radioButton[i].checked=false;
1.72      ng       1224: 		if (i == oldpts) {
1.71      ng       1225: 		    radioButton[i].checked=true;
                   1226: 		}
                   1227: 	    }
1.41      ng       1228: 	}
1.125     ng       1229: 	formname["stores"+id].value = "0";
1.71      ng       1230: 	updateSelect(formname,id);
                   1231: 	return;
1.41      ng       1232:     }
1.44      ng       1233: 
1.71      ng       1234:     function clearRadBox(formname,id) {
                   1235: 	if (checkSolved(formname,id) == 'noupdate') {
                   1236: 	    updateSelect(formname,id);
                   1237: 	    return;
                   1238: 	}
1.125     ng       1239: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1240: 	for (var i=0; i<gradeSelect.length; i++) {
                   1241: 	    if (gradeSelect[i].selected) {
                   1242: 		var selectx=i;
                   1243: 	    }
                   1244: 	}
1.125     ng       1245: 	var stores = formname["stores"+id];
1.71      ng       1246: 	if (selectx == stores.value) { return };
1.125     ng       1247: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1248: 	gradeBox.value = "";
1.125     ng       1249: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1250: 	for (var i=0; i<radioButton.length; i++) {
                   1251: 	    radioButton[i].checked=false;
                   1252: 	}
                   1253: 	stores.value = selectx;
                   1254:     }
1.5       albertel 1255: 
1.71      ng       1256:     function checkSolved(formname,id) {
1.125     ng       1257: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1258: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1259: 	    if (!reply) {return "noupdate";}
1.120     ng       1260: 	    formname.overRideScore.value = 'yes';
1.41      ng       1261: 	}
1.71      ng       1262: 	return "update";
1.13      albertel 1263:     }
1.71      ng       1264: 
                   1265:     function updateSelect(formname,id) {
1.125     ng       1266: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1267: 	return;
1.41      ng       1268:     }
1.33      ng       1269: 
1.121     ng       1270: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1271:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1272: 	formname.gradeOpt.value = val;
1.71      ng       1273: 	if (val == "Save & Next") {
                   1274: 	    for (i=0;i<=total;i++) {
                   1275: 		for (j=0;j<parttot;j++) {
1.125     ng       1276: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1277: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1278: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1279: 			if (points == "") {
1.125     ng       1280: 			    var name = formname["name"+i].value;
1.129     ng       1281: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1282: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1283: 					       ", part "+partid+". Continue?");
1.71      ng       1284: 			    if (resp == false) {
1.125     ng       1285: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1286: 				return false;
                   1287: 			    }
                   1288: 			}
                   1289: 		    }
                   1290: 		    
                   1291: 		}
                   1292: 	    }
                   1293: 	    
                   1294: 	}
1.120     ng       1295: 	formname.submit();
                   1296:     }
                   1297: 
1.71      ng       1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1299:     function checkSubmitPage(formname,total) {
                   1300: 	noscore = new Array(100);
                   1301: 	var ptr = 0;
                   1302: 	for (i=1;i<total;i++) {
1.125     ng       1303: 	    var partid = formname["q_"+i].value;
1.127     ng       1304: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1305: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1306: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1307: 		if (points == "" && status != "correct_by_student") {
                   1308: 		    noscore[ptr] = i;
                   1309: 		    ptr++;
                   1310: 		}
                   1311: 	    }
                   1312: 	}
                   1313: 	if (ptr != 0) {
                   1314: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1315: 	    var prolist = "";
                   1316: 	    if (ptr == 1) {
                   1317: 		prolist = noscore[0];
                   1318: 	    } else {
                   1319: 		var i = 0;
                   1320: 		while (i < ptr-1) {
                   1321: 		    prolist += noscore[i]+", ";
                   1322: 		    i++;
                   1323: 		}
                   1324: 		prolist += "and "+noscore[i];
                   1325: 	    }
                   1326: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1327: 	    if (resp == false) {
                   1328: 		return false;
                   1329: 	    }
                   1330: 	}
1.45      ng       1331: 
1.71      ng       1332: 	formname.submit();
                   1333:     }
                   1334: SUBJAVASCRIPT
                   1335: }
1.45      ng       1336: 
1.71      ng       1337: #--- javascript for essay type problem --
                   1338: sub sub_page_kw_js {
                   1339:     my $request = shift;
1.80      ng       1340:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1341:     &commonJSfunctions($request);
1.350     albertel 1342: 
1.629     www      1343:     my $inner_js_msg_central= (<<INNERJS);
                   1344: <script type="text/javascript">
1.350     albertel 1345:     function checkInput() {
                   1346:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1347:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1348:       var usrctr = document.msgcenter.usrctr.value;
                   1349:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1350:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1351: 
                   1352:       var msgchk = "";
                   1353:       if (document.msgcenter.subchk.checked) {
                   1354:          msgchk = "msgsub,";
                   1355:       }
                   1356:       var includemsg = 0;
                   1357:       for (var i=1; i<=nmsg; i++) {
                   1358:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1359:           var frmmsg = document.msgcenter["msg"+i];
                   1360:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1361:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1362:           showflg.value = "1";
                   1363:           var chkbox = document.msgcenter["msgn"+i];
                   1364:           if (chkbox.checked) {
                   1365:              msgchk += "savemsg"+i+",";
                   1366:              includemsg = 1;
                   1367:           }
                   1368:       }
                   1369:       if (document.msgcenter.newmsgchk.checked) {
                   1370:          msgchk += "newmsg"+usrctr;
                   1371:          includemsg = 1;
                   1372:       }
                   1373:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1374:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1375:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1376:       includemsg.value = msgchk;
                   1377: 
                   1378:       self.close()
                   1379: 
                   1380:     }
1.629     www      1381: </script>
1.350     albertel 1382: INNERJS
                   1383: 
1.629     www      1384:     my $inner_js_highlight_central= (<<INNERJS);
                   1385: <script type="text/javascript">
1.351     albertel 1386:     function updateChoice(flag) {
                   1387:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1388:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1389:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1390:       opener.document.SCORE.refresh.value = "on";
                   1391:       if (opener.document.SCORE.keywords.value!=""){
                   1392:          opener.document.SCORE.submit();
                   1393:       }
                   1394:       self.close()
                   1395:     }
1.629     www      1396: </script>
1.351     albertel 1397: INNERJS
                   1398: 
                   1399:     my $start_page_msg_central = 
                   1400:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1401: 				       {'js_ready'  => 1,
                   1402: 					'only_body' => 1,
                   1403: 					'bgcolor'   =>'#FFFFFF',});
                   1404:     my $end_page_msg_central = 
                   1405: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1406: 
                   1407: 
                   1408:     my $start_page_highlight_central = 
                   1409:         &Apache::loncommon::start_page('Highlight Central',
                   1410: 				       $inner_js_highlight_central,
1.350     albertel 1411: 				       {'js_ready'  => 1,
                   1412: 					'only_body' => 1,
                   1413: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1414:     my $end_page_highlight_central = 
1.350     albertel 1415: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1416: 
1.219     www      1417:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1418:     $docopen=~s/^document\.//;
1.652     raeburn  1419:     my %lt = &Apache::lonlocal::texthash(
                   1420:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1421:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1422:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1423:                 comp => 'Compose Message for: ',
                   1424:                 incl => 'Include',
1.656     raeburn  1425:                 type => 'Type',
1.652     raeburn  1426:                 subj => 'Subject',
                   1427:                 mesa => 'Message',
                   1428:                 new  => 'New',
                   1429:                 save => 'Save',
                   1430:                 canc => 'Cancel',
                   1431:                 kehi => 'Keyword Highlight Options',
                   1432:                 txtc => 'Text Color',
                   1433:                 font => 'Font Size',
1.656     raeburn  1434:                 fnst => 'Font Style',
1.652     raeburn  1435:              );
1.597     wenzelju 1436:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1437: 
1.44      ng       1438: //===================== Show list of keywords ====================
1.122     ng       1439:   function keywords(formname) {
1.652     raeburn  1440:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1441:     if (nret==null) return;
1.122     ng       1442:     formname.keywords.value = nret;
1.44      ng       1443: 
1.122     ng       1444:     if (formname.keywords.value != "") {
1.128     ng       1445: 	formname.refresh.value = "on";
1.122     ng       1446: 	formname.submit();
1.44      ng       1447:     }
                   1448:     return;
                   1449:   }
                   1450: 
                   1451: //===================== Script to view submitted by ==================
                   1452:   function viewSubmitter(submitter) {
                   1453:     document.SCORE.refresh.value = "on";
                   1454:     document.SCORE.NCT.value = "1";
                   1455:     document.SCORE.unamedom0.value = submitter;
                   1456:     document.SCORE.submit();
                   1457:     return;
                   1458:   }
                   1459: 
                   1460: //===================== Script to add keyword(s) ==================
                   1461:   function getSel() {
                   1462:     if (document.getSelection) txt = document.getSelection();
                   1463:     else if (document.selection) txt = document.selection.createRange().text;
                   1464:     else return;
                   1465:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1466:     if (cleantxt=="") {
1.652     raeburn  1467: 	alert("$lt{'plse'}");
1.44      ng       1468: 	return;
                   1469:     }
1.652     raeburn  1470:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1471:     if (nret==null) return;
1.127     ng       1472:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1473:     if (document.SCORE.keywords.value != "") {
1.127     ng       1474: 	document.SCORE.refresh.value = "on";
1.44      ng       1475: 	document.SCORE.submit();
                   1476:     }
                   1477:     return;
                   1478:   }
                   1479: 
                   1480: //====================== Script for composing message ==============
1.80      ng       1481:    // preload images
                   1482:    img1 = new Image();
                   1483:    img1.src = "$iconpath/mailbkgrd.gif";
                   1484:    img2 = new Image();
                   1485:    img2.src = "$iconpath/mailto.gif";
                   1486: 
1.44      ng       1487:   function msgCenter(msgform,usrctr,fullname) {
                   1488:     var Nmsg  = msgform.savemsgN.value;
                   1489:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1490:     var subject = msgform.msgsub.value;
1.127     ng       1491:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1492:     re = /msgsub/;
                   1493:     var shwsel = "";
                   1494:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1495:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1496:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1497:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1498: 	var testmsg = "savemsg"+i+",";
                   1499: 	re = new RegExp(testmsg,"g");
1.44      ng       1500: 	shwsel = "";
                   1501: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1502: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1503: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1504: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1505: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1506:     }
1.125     ng       1507:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1508:     shwsel = "";
                   1509:     re = /newmsg/;
                   1510:     if (re.test(msgchk)) { shwsel = "checked" }
                   1511:     newMsg(newmsg,shwsel);
                   1512:     msgTail(); 
                   1513:     return;
                   1514:   }
                   1515: 
1.123     ng       1516:   function checkEntities(strx) {
                   1517:     if (strx.length == 0) return strx;
                   1518:     var orgStr = ["&", "<", ">", '"']; 
                   1519:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1520:     var counter = 0;
                   1521:     while (counter < 4) {
                   1522: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1523: 	counter++;
                   1524:     }
                   1525:     return strx;
                   1526:   }
                   1527: 
                   1528:   function strReplace(strx, orgStr, newStr) {
                   1529:     return strx.split(orgStr).join(newStr);
                   1530:   }
                   1531: 
1.44      ng       1532:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1533:     var height = 70*Nmsg+250;
1.44      ng       1534:     if (height > 600) {
                   1535: 	height = 600;
                   1536:     }
1.118     ng       1537:     var xpos = (screen.width-600)/2;
                   1538:     xpos = (xpos < 0) ? '0' : xpos;
                   1539:     var ypos = (screen.height-height)/2-30;
                   1540:     ypos = (ypos < 0) ? '0' : ypos;
                   1541: 
1.668     www      1542:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1543:     pWin.focus();
                   1544:     pDoc = pWin.document;
1.219     www      1545:     pDoc.$docopen;
1.351     albertel 1546:     pDoc.write('$start_page_msg_central');
1.76      ng       1547: 
                   1548:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1549:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1550:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1551: 
1.676     golterma 1552:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1553:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1554: }
                   1555:     function displaySubject(msg,shwsel) {
1.76      ng       1556:     pDoc = pWin.document;
1.676     golterma 1557:     pDoc.write("<tr>");
                   1558:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1559:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1560:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1561: }
                   1562: 
1.72      ng       1563:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1564:     pDoc = pWin.document;
1.676     golterma 1565:     pDoc.write("<tr>");
                   1566:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1567:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1568:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1569: }
                   1570: 
                   1571:   function newMsg(newmsg,shwsel) {
1.76      ng       1572:     pDoc = pWin.document;
1.676     golterma 1573:     pDoc.write("<tr>");
                   1574:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1575:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1576:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1577: }
                   1578: 
                   1579:   function msgTail() {
1.76      ng       1580:     pDoc = pWin.document;
1.676     golterma 1581:     //pDoc.write("<\\/table>");
1.465     albertel 1582:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1584:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1585:     pDoc.write("<\\/form>");
1.351     albertel 1586:     pDoc.write('$end_page_msg_central');
1.128     ng       1587:     pDoc.close();
1.44      ng       1588: }
                   1589: 
                   1590: //====================== Script for keyword highlight options ==============
                   1591:   function kwhighlight() {
                   1592:     var kwclr    = document.SCORE.kwclr.value;
                   1593:     var kwsize   = document.SCORE.kwsize.value;
                   1594:     var kwstyle  = document.SCORE.kwstyle.value;
                   1595:     var redsel = "";
                   1596:     var grnsel = "";
                   1597:     var blusel = "";
                   1598:     if (kwclr=="red")   {var redsel="checked"};
                   1599:     if (kwclr=="green") {var grnsel="checked"};
                   1600:     if (kwclr=="blue")  {var blusel="checked"};
                   1601:     var sznsel = "";
                   1602:     var sz1sel = "";
                   1603:     var sz2sel = "";
                   1604:     if (kwsize=="0")  {var sznsel="checked"};
                   1605:     if (kwsize=="+1") {var sz1sel="checked"};
                   1606:     if (kwsize=="+2") {var sz2sel="checked"};
                   1607:     var synsel = "";
                   1608:     var syisel = "";
                   1609:     var sybsel = "";
                   1610:     if (kwstyle=="")    {var synsel="checked"};
                   1611:     if (kwstyle=="<i>") {var syisel="checked"};
                   1612:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1613:     highlightCentral();
                   1614:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1615:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1616:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1617:     highlightend();
                   1618:     return;
                   1619:   }
                   1620: 
                   1621:   function highlightCentral() {
1.76      ng       1622: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1623:     var xpos = (screen.width-400)/2;
                   1624:     xpos = (xpos < 0) ? '0' : xpos;
                   1625:     var ypos = (screen.height-330)/2-30;
                   1626:     ypos = (ypos < 0) ? '0' : ypos;
                   1627: 
1.206     albertel 1628:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1629:     hwdWin.focus();
                   1630:     var hDoc = hwdWin.document;
1.219     www      1631:     hDoc.$docopen;
1.351     albertel 1632:     hDoc.write('$start_page_highlight_central');
1.76      ng       1633:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1634:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1635: 
1.564     bisitz   1636:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1637:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1638:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1639:   }
                   1640: 
                   1641:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1642:     var hDoc = hwdWin.document;
                   1643:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1644:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1645:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1646:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1647:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1648:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1649:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1650:     hDoc.write("<\\/tr>");
1.44      ng       1651:   }
                   1652: 
                   1653:   function highlightend() { 
1.76      ng       1654:     var hDoc = hwdWin.document;
1.465     albertel 1655:     hDoc.write("<\\/table>");
                   1656:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1658:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1659:     hDoc.write("<\\/form>");
1.351     albertel 1660:     hDoc.write('$end_page_highlight_central');
1.128     ng       1661:     hDoc.close();
1.44      ng       1662:   }
                   1663: 
                   1664: SUBJAVASCRIPT
                   1665: }
                   1666: 
1.349     albertel 1667: sub get_increment {
1.348     bowersj2 1668:     my $increment = $env{'form.increment'};
                   1669:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1670:         $increment != .1) {
                   1671:         $increment = 1;
                   1672:     }
                   1673:     return $increment;
                   1674: }
                   1675: 
1.585     bisitz   1676: sub gradeBox_start {
                   1677:     return (
                   1678:         &Apache::loncommon::start_data_table()
                   1679:        .&Apache::loncommon::start_data_table_header_row()
                   1680:        .'<th>'.&mt('Part').'</th>'
                   1681:        .'<th>'.&mt('Points').'</th>'
                   1682:        .'<th>&nbsp;</th>'
                   1683:        .'<th>'.&mt('Assign Grade').'</th>'
                   1684:        .'<th>'.&mt('Weight').'</th>'
                   1685:        .'<th>'.&mt('Grade Status').'</th>'
                   1686:        .&Apache::loncommon::end_data_table_header_row()
                   1687:     );
                   1688: }
                   1689: 
                   1690: sub gradeBox_end {
                   1691:     return (
                   1692:         &Apache::loncommon::end_data_table()
                   1693:     );
                   1694: }
1.71      ng       1695: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1696: sub gradeBox {
1.322     albertel 1697:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1698:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1699: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1700:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1701:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1702:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1703:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1704:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1705: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1706:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1707:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1708:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1709: 				       [$partid]);
                   1710:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1711:     if ($last_resets{$partid}) {
                   1712:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1713:     }
1.695     bisitz   1714:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1715:     my $ctr = 0;
1.348     bowersj2 1716:     my $thisweight = 0;
1.349     albertel 1717:     my $increment = &get_increment();
1.485     albertel 1718: 
                   1719:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1720:     while ($thisweight<=$wgt) {
1.532     bisitz   1721: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1722:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1723: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1724: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1725: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1726:         $thisweight += $increment;
1.71      ng       1727: 	$ctr++;
                   1728:     }
1.485     albertel 1729:     $radio.='</tr></table>';
                   1730: 
                   1731:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1732: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1733: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1734: 	$wgt.')" /></td>'."\n";
1.485     albertel 1735:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1736: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1737: 	' </td>'."\n";
                   1738:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1739: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1740:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1741: 	$line.='<option></option>'.
                   1742: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1743:     } else {
1.485     albertel 1744: 	$line.='<option selected="selected"></option>'.
                   1745: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1746:     }
1.485     albertel 1747:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1748: 
                   1749: 
                   1750:     $result .= 
1.695     bisitz   1751: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1752:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1753:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1754:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1755: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1756: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1757: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1758:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1759:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1760:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1761:         $aggtries.'" />'."\n";
1.582     raeburn  1762:     my $res_error;
                   1763:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1764:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1765:     if ($res_error) {
                   1766:         return &navmap_errormsg();
                   1767:     }
1.318     banghart 1768:     return $result;
                   1769: }
1.322     albertel 1770: 
                   1771: sub handback_box {
1.623     www      1772:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1773:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1774:     my (@respids);
1.652     raeburn  1775:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1776:     foreach my $part_response_id (@part_response_id) {
                   1777:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1778:         if ($part eq $partid) {
1.375     albertel 1779:             push(@respids,$resp);
1.323     banghart 1780:         }
                   1781:     }
1.318     banghart 1782:     my $result;
1.323     banghart 1783:     foreach my $respid (@respids) {
1.322     albertel 1784: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1785: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1786: 	next if (!@$files);
1.654     raeburn  1787: 	my $file_counter = 0;
1.313     banghart 1788: 	foreach my $file (@$files) {
1.368     banghart 1789: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1790:                 $file_counter++;
1.368     banghart 1791:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1792:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1793:     	        $file_disp = "$name.$ext";
                   1794:     	        $file = $file_path.$file_disp;
                   1795:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1796:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1797:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1798:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1799: 	    }
1.322     albertel 1800: 	}
1.654     raeburn  1801:         if ($file_counter) {
                   1802:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1803:                        '<span class="LC_info">'.
                   1804:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1805:         }
1.313     banghart 1806:     }
1.318     banghart 1807:     return $result;    
1.71      ng       1808: }
1.44      ng       1809: 
1.58      albertel 1810: sub show_problem {
1.382     albertel 1811:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1812:     my $rendered;
1.382     albertel 1813:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1814:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1815:     if ($mode eq 'both' or $mode eq 'text') {
                   1816: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1817: 						       $env{'request.course.id'},
                   1818: 						       undef,\%form);
1.144     albertel 1819:     }
1.58      albertel 1820:     if ($removeform) {
                   1821: 	$rendered=~s|<form(.*?)>||g;
                   1822: 	$rendered=~s|</form>||g;
1.374     albertel 1823: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1824:     }
1.144     albertel 1825:     my $companswer;
                   1826:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1827: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1828: 	$companswer=
                   1829: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1830: 						    $env{'request.course.id'},
                   1831: 						    %form);
1.144     albertel 1832:     }
1.58      albertel 1833:     if ($removeform) {
                   1834: 	$companswer=~s|<form(.*?)>||g;
                   1835: 	$companswer=~s|</form>||g;
1.144     albertel 1836: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1837:     }
1.671     raeburn  1838:     my $renderheading = &mt('View of the problem');
                   1839:     my $answerheading = &mt('Correct answer');
                   1840:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1841:         my $stu_fullname = $env{'form.fullname'};
                   1842:         if ($stu_fullname eq '') {
                   1843:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1844:         }
                   1845:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1846:         if ($forwhom ne '') {
                   1847:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1848:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1849:         }
                   1850:     }
1.468     albertel 1851:     $rendered=
1.588     bisitz   1852:         '<div class="LC_Box">'
1.671     raeburn  1853:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1854:        .$rendered
                   1855:        .'</div>';
1.468     albertel 1856:     $companswer=
1.588     bisitz   1857:         '<div class="LC_Box">'
1.671     raeburn  1858:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1859:        .$companswer
                   1860:        .'</div>';
1.468     albertel 1861:     my $result;
1.144     albertel 1862:     if ($mode eq 'both') {
1.588     bisitz   1863:         $result=$rendered.$companswer;
1.144     albertel 1864:     } elsif ($mode eq 'text') {
1.588     bisitz   1865:         $result=$rendered;
1.144     albertel 1866:     } elsif ($mode eq 'answer') {
1.588     bisitz   1867:         $result=$companswer;
1.144     albertel 1868:     }
1.71      ng       1869:     return $result;
1.58      albertel 1870: }
1.397     albertel 1871: 
1.396     banghart 1872: sub files_exist {
                   1873:     my ($r, $symb) = @_;
                   1874:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1875: 
1.396     banghart 1876:     foreach my $student (@students) {
                   1877:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1878:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1879: 					      $udom,$uname);
1.396     banghart 1880:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1881:         foreach my $submission (@$string) {
                   1882:             my ($partid,$respid) =
                   1883: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1884:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1885: 					   \%record);
                   1886:             return 1 if (@$files);
1.396     banghart 1887:         }
                   1888:     }
1.397     albertel 1889:     return 0;
1.396     banghart 1890: }
1.397     albertel 1891: 
1.394     banghart 1892: sub download_all_link {
                   1893:     my ($r,$symb) = @_;
1.621     www      1894:     unless (&files_exist($r, $symb)) {
                   1895:        $r->print(&mt('There are currently no submitted documents.'));
                   1896:        return;
                   1897:     }
                   1898: 
1.395     albertel 1899:     my $all_students = 
                   1900: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1901: 
                   1902:     my $parts =
                   1903: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1904: 
1.394     banghart 1905:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1906:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1907:                              'cgi.'.$identifier.'.symb' => $symb,
                   1908:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1909:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1910: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1911:     return;
                   1912: }
                   1913: 
                   1914: sub submit_download_link {
                   1915:     my ($request,$symb) = @_;
                   1916:     if (!$symb) { return ''; }
                   1917: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1918:     &download_all_link($request,$symb);
1.394     banghart 1919: }
1.395     albertel 1920: 
1.432     banghart 1921: sub build_section_inputs {
                   1922:     my $section_inputs;
                   1923:     if ($env{'form.section'} eq '') {
                   1924:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1925:     } else {
                   1926:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1927:         foreach my $section (@sections) {
1.432     banghart 1928:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1929:         }
                   1930:     }
                   1931:     return $section_inputs;
                   1932: }
                   1933: 
1.44      ng       1934: # --------------------------- show submissions of a student, option to grade 
                   1935: sub submission {
1.608     www      1936:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1937:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1938:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1939:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1940:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1941: 
1.605     www      1942:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1943:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1944: 
                   1945:     if (!&canview($usec)) {
1.712     bisitz   1946:         $request->print(
                   1947:             '<span class="LC_warning">'.
1.713     bisitz   1948:             &mt('Unable to view requested student.').
1.712     bisitz   1949:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1950:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1951:             '</span>');
1.104     albertel 1952: 	return;
                   1953:     }
                   1954: 
1.257     albertel 1955:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1956:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1957:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1958:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1959:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1960: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1961: 	'/check.gif" height="16" border="0" />';
1.41      ng       1962: 
                   1963:     # header info
                   1964:     if ($counter == 0) {
                   1965: 	&sub_page_js($request);
1.621     www      1966: 	&sub_page_kw_js($request);
1.118     ng       1967: 
1.44      ng       1968: 	# option to display problem, only once else it cause problems 
                   1969:         # with the form later since the problem has a form.
1.257     albertel 1970: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1971: 	    my $mode;
1.257     albertel 1972: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1973: 		$mode='both';
1.257     albertel 1974: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1975: 		$mode='text';
1.257     albertel 1976: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1977: 		$mode='answer';
                   1978: 	    }
1.329     albertel 1979: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1980: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1981: 	}
1.441     www      1982: 
1.704     raeburn  1983: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       1984:         # if this subroutine has been called once.
1.41      ng       1985: 	my %keyhash = ();
1.624     www      1986: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1987:         if (1) {
1.41      ng       1988: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1989: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1990: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1991: 
1.257     albertel 1992: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1993: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1994: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1995: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1996: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1997: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1998: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1999: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2000: 	}
1.257     albertel 2001: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2002: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2003: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2004: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2005: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2006: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2007: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2008: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2009: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2010: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2011: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2012: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2013: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2014: 			&build_section_inputs().
1.326     albertel 2015: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2016: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2017: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2018: #	if ($env{'form.handgrade'} eq 'yes') {
                   2019:         if (1) {
1.257     albertel 2020: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2021: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2022: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2023: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2024: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2025: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2026: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2027: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2028: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2029: 	    }
1.123     ng       2030: 	}
1.41      ng       2031: 	
                   2032: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2033: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2034: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2035: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2036: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2037: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2038: 		'" />'."\n".
                   2039: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2040: 	    $cts++;
                   2041: 	}
                   2042: 	$request->print($prnmsg);
1.32      ng       2043: 
1.624     www      2044: #	if ($env{'form.handgrade'} eq 'yes') {
                   2045:         if (1) {
1.652     raeburn  2046: 
                   2047:             my %lt = &Apache::lonlocal::texthash(
                   2048:                           keyw => 'Keyword Options',
1.655     raeburn  2049:                           list => 'List',
1.652     raeburn  2050:                           past => 'Paste Selection to List',
1.661     www      2051:                           high => 'Highlight Attribute',
1.652     raeburn  2052:                      );    
1.88      www      2053: #
                   2054: # Print out the keyword options line
                   2055: #
1.41      ng       2056: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2057: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2058: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2059: <a href="#" onmousedown="javascript:getSel(); return false"
1.695     bisitz   2060:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
1.652     raeburn  2061: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2062: KEYWORDS
1.88      www      2063: #
                   2064: # Load the other essays for similarity check
                   2065: #
1.324     albertel 2066:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2067: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2068: 	    $apath=&escape($apath);
1.88      www      2069: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2070:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2071:         }
                   2072:     }
1.44      ng       2073: 
1.441     www      2074: # This is where output for one specific student would start
1.592     bisitz   2075:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2076:     $request->print(
                   2077:         "\n\n"
                   2078:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2079:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2080:        ."\n"
                   2081:     );
1.441     www      2082: 
1.592     bisitz   2083:     # Show additional functions if allowed
                   2084:     if ($perm{'vgr'}) {
                   2085:         $request->print(
                   2086:             &Apache::loncommon::track_student_link(
1.708     bisitz   2087:                 'View recent activity',
1.592     bisitz   2088:                 $uname,$udom,'check')
                   2089:            .' '
                   2090:         );
                   2091:     }
                   2092:     if ($perm{'opa'}) {
                   2093:         $request->print(
                   2094:             &Apache::loncommon::pprmlink(
                   2095:                 &mt('Set/Change parameters'),
                   2096:                 $uname,$udom,$symb,'check'));
                   2097:     }
                   2098: 
                   2099:     # Show Problem
1.257     albertel 2100:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2101: 	my $mode;
1.257     albertel 2102: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2103: 	    $mode='both';
1.257     albertel 2104: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2105: 	    $mode='text';
1.257     albertel 2106: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2107: 	    $mode='answer';
                   2108: 	}
1.329     albertel 2109: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2110: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2111:     }
1.144     albertel 2112: 
1.257     albertel 2113:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2114:     my $res_error;
                   2115:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2116:     if ($res_error) {
                   2117:         $request->print(&navmap_errormsg());
                   2118:         return;
                   2119:     }
1.41      ng       2120: 
1.44      ng       2121:     # Display student info
1.41      ng       2122:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2123: 
                   2124:     my $result='<div class="LC_Box">'
                   2125:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2126:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2127:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2128: #    if ($env{'form.handgrade'} eq 'no') {
                   2129:     if (1) {
1.588     bisitz   2130:         $result.='<p class="LC_info">'
                   2131:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2132:                 ."</p>\n";
1.469     albertel 2133:     }
                   2134: 
1.118     ng       2135:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2136:     my $fullname;
                   2137:     my $col_fullnames = [];
1.624     www      2138: #    if ($env{'form.handgrade'} eq 'yes') {
                   2139:     if (1) {
1.464     albertel 2140: 	(my $sub_result,$fullname,$col_fullnames)=
                   2141: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2142: 				 $counter);
                   2143: 	$result.=$sub_result;
1.41      ng       2144:     }
1.44      ng       2145:     $request->print($result."\n");
1.702     kruse    2146:     
1.44      ng       2147:     # print student answer/submission
1.588     bisitz   2148:     # Options are (1) Handgraded submission only
1.44      ng       2149:     #             (2) Last submission, includes submission that is not handgraded 
                   2150:     #                  (for multi-response type part)
                   2151:     #             (3) Last submission plus the parts info
                   2152:     #             (4) The whole record for this student
1.702     kruse    2153:     
                   2154:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2155: 	
1.702     kruse    2156:     my $lastsubonly;
1.468     albertel 2157: 
1.702     kruse    2158:     if ($$timestamp eq '') {
                   2159:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2160:     } else {
                   2161:         $lastsubonly =
                   2162:             '<div class="LC_grade_submissions_body">'
                   2163:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2164: 
                   2165: 	my %seenparts;
                   2166: 	my @part_response_id = &flatten_responseType($responseType);
                   2167: 	foreach my $part (@part_response_id) {
                   2168: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2169: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2170: 
1.702     kruse    2171: 	    my ($partid,$respid) = @{ $part };
                   2172: 	    my $display_part=&get_display_part($partid,$symb);
                   2173: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2174: 		if (exists($seenparts{$partid})) { next; }
                   2175: 		$seenparts{$partid}=1;
                   2176:                 $request->print(
                   2177:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2178:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2179:                                '<a href="javascript:viewSubmitter(\''.
                   2180:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2181:                                '\');" target="_self">'.
                   2182:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2183:                     '<br />');
                   2184: 		next;
                   2185: 		}
                   2186: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2187: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2188:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2189:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2190:                     ' <span class="LC_internal_info">'.
                   2191:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2192:                     '</span>&nbsp; &nbsp;'.
                   2193: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2194: 		next;
                   2195: 	    }
                   2196: 	    foreach my $submission (@$string) {
                   2197: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2198: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2199: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
                   2200: 		# Similarity check
                   2201:                 my $similar='';
                   2202:                 my ($type,$trial,$rndseed);
                   2203:                 if ($hide eq 'rand') {
                   2204:                     $type = 'randomizetry';
                   2205:                     $trial = $record{"resource.$partid.tries"};
                   2206:                     $rndseed = $record{"resource.$partid.rndseed"};
                   2207:                 }
                   2208: 	        if ($env{'form.checkPlag'}) {
                   2209:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2210: 		        &most_similar($uname,$udom,$symb,$subval);
                   2211: 		    if ($osim) {
                   2212: 			$osim=int($osim*100.0);
                   2213: 			my %old_course_desc = 
                   2214: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2215: 							{'one_time' => 1});
                   2216: 
                   2217:                         if ($hide eq 'anon') {
                   2218:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2219:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2220:                         } else {
                   2221: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2222: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2223: 				    $osim,
                   2224: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2225: 				        $old_course_desc{'description'},
                   2226: 				        $old_course_desc{'num'},
                   2227: 				        $old_course_desc{'domain'}).
                   2228: 				    '</span></h3><blockquote><i>'.
                   2229: 				    &keywords_highlight($oessay).
                   2230: 				    '</i></blockquote><hr />';
1.702     kruse    2231:                         }
                   2232: 	            }
                   2233: 		}
                   2234: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2235:                                      undef,$type,$trial,$rndseed);
                   2236:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2237: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2238: 		    my $display_part=&get_display_part($partid,$symb);
                   2239:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2240:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2241:                         ' <span class="LC_internal_info">'.
                   2242:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2243:                         '</span>&nbsp; &nbsp;';
                   2244: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2245:                         
                   2246: 		    if (@$files) {
                   2247:                         if ($hide eq 'anon') {
                   2248:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2249:                         } else {
                   2250:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2251:                                         .'<br /><span class="LC_warning">';
                   2252:                             if(@$files == 1) {
                   2253:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2254:                             } else {
1.702     kruse    2255:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2256:                             }
                   2257:                             $lastsubonly .= '</span>';                         
                   2258:                             foreach my $file (@$files) {
                   2259:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2260:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2261:                             }
                   2262:                         }
1.702     kruse    2263: 			$lastsubonly.='<br />';
                   2264:                     }
                   2265:                     if ($hide eq 'anon') {
                   2266:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2267:                     } else {
                   2268:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
                   2269: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2270: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2271:                     }
                   2272: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2273: 		    $lastsubonly.='</div>';
1.41      ng       2274: 		}
1.702     kruse    2275:             }
1.151     albertel 2276: 	}
1.702     kruse    2277: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2278:     }
                   2279:     $request->print($lastsubonly);
                   2280:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2281:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2282: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.702     kruse    2283:     } 
                   2284:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2285:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2286: 								 $env{'request.course.id'},
1.44      ng       2287: 								 $last,'.submission',
                   2288: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2289:     }
1.121     ng       2290:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2291: 	.$udom.'" />'."\n");
1.44      ng       2292:     # return if view submission with no grading option
1.618     www      2293:     if (!&canmodify($usec)) {
1.633     www      2294: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2295: 	return;
1.180     albertel 2296:     } else {
1.468     albertel 2297: 	$request->print('</div>'."\n");
1.41      ng       2298:     }
1.33      ng       2299: 
1.121     ng       2300:     # essay grading message center
1.624     www      2301: #    if ($env{'form.handgrade'} eq 'yes') {
                   2302:     if (1) {
1.468     albertel 2303: 	my $result='<div class="LC_grade_message_center">';
                   2304:     
                   2305: 	$result.='<div class="LC_grade_message_center_header">'.
                   2306: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2307: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2308: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2309: 	if (scalar(@$col_fullnames) > 0) {
                   2310: 	    my $lastone = pop(@$col_fullnames);
                   2311: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2312: 	}
                   2313: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2314: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2315: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2316: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2317: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2318: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2319: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2320: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2321: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2322: 	    '<br />&nbsp;('.
1.468     albertel 2323: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2324: 	$result.='</div></div>';
1.121     ng       2325: 	$request->print($result);
1.118     ng       2326:     }
1.41      ng       2327: 
                   2328:     my %seen = ();
                   2329:     my @partlist;
1.129     ng       2330:     my @gradePartRespid;
1.375     albertel 2331:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2332:     $request->print(
1.588     bisitz   2333:         '<div class="LC_Box">'
                   2334:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2335:     );
1.592     bisitz   2336:     $request->print(&gradeBox_start());
1.375     albertel 2337:     foreach my $part_response_id (@part_response_id) {
                   2338:     	my ($partid,$respid) = @{ $part_response_id };
                   2339: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2340: 	next if ($seen{$partid} > 0);
1.41      ng       2341: 	$seen{$partid}++;
1.393     albertel 2342: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2343: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2344: 	push(@partlist,$partid);
                   2345: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2346: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2347:     }
1.585     bisitz   2348:     $request->print(&gradeBox_end()); # </div>
                   2349:     $request->print('</div>');
1.468     albertel 2350: 
                   2351:     $request->print('<div class="LC_grade_info_links">');
                   2352:     $request->print('</div>');
                   2353: 
1.45      ng       2354:     $result='<input type="hidden" name="partlist'.$counter.
                   2355: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2356:     $result.='<input type="hidden" name="gradePartRespid'.
                   2357: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2358:     my $ctr = 0;
                   2359:     while ($ctr < scalar(@partlist)) {
                   2360: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2361: 	    $partlist[$ctr].'" />'."\n";
                   2362: 	$ctr++;
                   2363:     }
1.468     albertel 2364:     $request->print($result.''."\n");
1.41      ng       2365: 
1.441     www      2366: # Done with printing info for one student
                   2367: 
1.468     albertel 2368:     $request->print('</div>');#LC_grade_show_user
1.441     www      2369: 
                   2370: 
1.41      ng       2371:     # print end of form
                   2372:     if ($counter == $total) {
1.592     bisitz   2373:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2374: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2375: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2376: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2377: 	my $ntstu ='<select name="NTSTU">'.
                   2378: 	    '<option>1</option><option>2</option>'.
                   2379: 	    '<option>3</option><option>5</option>'.
                   2380: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2381: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2382: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2383:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2384: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2385: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2386: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2387: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2388:         $endform.='<span class="LC_warning">'.
                   2389:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2390:                   '</span>'."\n" ;
1.349     albertel 2391:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2392:             "' name='increment' />";
1.485     albertel 2393: 	$endform.='</td></tr></table></form>';
1.41      ng       2394: 	$request->print($endform);
                   2395:     }
                   2396:     return '';
1.38      ng       2397: }
                   2398: 
1.464     albertel 2399: sub check_collaborators {
                   2400:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2401:     my ($result,@col_fullnames);
                   2402:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2403:     foreach my $part (keys(%$handgrade)) {
                   2404: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2405: 					'.maxcollaborators',
                   2406: 					$symb,$udom,$uname);
                   2407: 	next if ($ncol <= 0);
                   2408: 	$part =~ s/\_/\./g;
                   2409: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2410: 	my (@good_collaborators, @bad_collaborators);
                   2411: 	foreach my $possible_collaborator
1.630     www      2412: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2413: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2414: 	    next if ($possible_collaborator eq '');
1.631     www      2415: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2416: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2417: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2418: 	    # Doing this grep allows 'fuzzy' specification
                   2419: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2420: 			       keys(%$classlist));
                   2421: 	    if (! scalar(@matches)) {
                   2422: 		push(@bad_collaborators, $possible_collaborator);
                   2423: 	    } else {
                   2424: 		push(@good_collaborators, @matches);
                   2425: 	    }
                   2426: 	}
                   2427: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2428: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2429: 	    foreach my $name (@good_collaborators) {
                   2430: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2431: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2432: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2433: 	    }
1.630     www      2434: 	    $result.='</ol><br />'."\n";
1.466     albertel 2435: 	    my ($part)=split(/\./,$part);
1.464     albertel 2436: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2437: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2438: 		"\n";
                   2439: 	}
                   2440: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2441: 	    $result.='<div class="LC_warning">';
1.464     albertel 2442: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2443: 	    $result .= '</div>';
                   2444: 	}         
                   2445: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2446: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2447: 	    $result .= &mt('This student has submitted too many '.
                   2448: 		'collaborators.  Maximum is [_1].',$ncol);
                   2449: 	    $result .= '</div>';
                   2450: 	}
                   2451:     }
                   2452:     return ($result,$fullname,\@col_fullnames);
                   2453: }
                   2454: 
1.44      ng       2455: #--- Retrieve the last submission for all the parts
1.38      ng       2456: sub get_last_submission {
1.119     ng       2457:     my ($returnhash)=@_;
1.596     raeburn  2458:     my (@string,$timestamp,%lasthidden);
1.119     ng       2459:     if ($$returnhash{'version'}) {
1.46      ng       2460: 	my %lasthash=();
                   2461: 	my ($version);
1.119     ng       2462: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2463: 	    foreach my $key (sort(split(/\:/,
                   2464: 					$$returnhash{$version.':keys'}))) {
                   2465: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2466: 		$timestamp = 
1.545     raeburn  2467: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2468: 	    }
                   2469: 	}
1.640     raeburn  2470:         my (%typeparts,%randombytry);
1.596     raeburn  2471:         my $showsurv = 
                   2472:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2473:         foreach my $key (sort(keys(%lasthash))) {
                   2474:             if ($key =~ /\.type$/) {
                   2475:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2476:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2477:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2478:                     my ($ign,@parts) = split(/\./,$key);
                   2479:                     pop(@parts);
1.641     raeburn  2480:                     my $id = join('.',@parts);
1.640     raeburn  2481:                     if ($lasthash{$key} eq 'randomizetry') {
                   2482:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2483:                     } else {
                   2484:                         unless ($showsurv) {
                   2485:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2486:                         }
1.596     raeburn  2487:                     }
                   2488:                     delete($lasthash{$key});
                   2489:                 }
                   2490:             }
                   2491:         }
                   2492:         my @hidden = keys(%typeparts);
1.640     raeburn  2493:         my @randomize = keys(%randombytry);
1.397     albertel 2494: 	foreach my $key (keys(%lasthash)) {
                   2495: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2496:             my $hide;
                   2497:             if (@hidden) {
                   2498:                 foreach my $id (@hidden) {
                   2499:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2500:                         $hide = 'anon';
1.596     raeburn  2501:                         last;
                   2502:                     }
                   2503:                 }
                   2504:             }
1.640     raeburn  2505:             unless ($hide) {
                   2506:                 if (@randomize) {
                   2507:                     foreach my $id (@hidden) {
                   2508:                         if ($key =~ /^\Q$id\E/) {
                   2509:                             $hide = 'rand';
                   2510:                             last;
                   2511:                         }
                   2512:                     }
                   2513:                 }
                   2514:             }
1.397     albertel 2515: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2516: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.717   ! bisitz   2517: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
1.716     bisitz   2518: 	    #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
                   2519:             push(@string, join(':', $key, $hide, $draft.(
                   2520:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2521:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2522: 	}
                   2523:     }
1.397     albertel 2524:     if (!@string) {
                   2525: 	$string[0] =
1.539     riegler  2526: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2527:     }
                   2528:     return (\@string,\$timestamp);
1.38      ng       2529: }
1.35      ng       2530: 
1.44      ng       2531: #--- High light keywords, with style choosen by user.
1.38      ng       2532: sub keywords_highlight {
1.44      ng       2533:     my $string    = shift;
1.257     albertel 2534:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2535:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2536:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2537:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2538:     foreach my $keyword (@keylist) {
                   2539: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2540:     }
                   2541:     return $string;
1.38      ng       2542: }
1.36      ng       2543: 
1.671     raeburn  2544: # For Tasks provide a mechanism to display previous version for one specific student
                   2545: 
                   2546: sub show_previous_task_version {
                   2547:     my ($request,$symb) = @_;
                   2548:     if ($symb eq '') {
1.717   ! bisitz   2549:         $request->print(
        !          2550:             '<span class="LC_error">'.
        !          2551:             &mt('Unable to handle ambiguous references.').
        !          2552:             '</span>');
1.671     raeburn  2553:         return '';
                   2554:     }
                   2555:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2556:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2557:     if (!&canview($usec)) {
1.712     bisitz   2558:         $request->print(
                   2559:             '<span class="LC_warning">'.
1.713     bisitz   2560:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2561:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2562:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2563:             '</span>');
1.671     raeburn  2564:         return;
                   2565:     }
                   2566:     my $mode = 'both';
                   2567:     my $isTask = ($symb =~/\.task$/);
                   2568:     if ($isTask) {
                   2569:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2570:             if ($env{'form.fullname'} eq '') {
                   2571:                 $env{'form.fullname'} =
                   2572:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2573:             }
                   2574:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2575:             $request->print("\n\n".
                   2576:                             '<div class="LC_grade_show_user">'.
                   2577:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2578:                             '</h2>'."\n");
                   2579:             &Apache::lonxml::clear_problem_counter();
                   2580:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2581:                             {'previousversion' => $env{'form.previousversion'} }));
                   2582:             $request->print("\n</div>");
                   2583:         }
                   2584:     }
                   2585:     return;
                   2586: }
                   2587: 
                   2588: sub choose_task_version_form {
                   2589:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2590:     my $isTask = ($symb =~/\.task$/);
                   2591:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2592:     if ($isTask) {
                   2593:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2594:                                               $udom,$uname);
                   2595:         if (($record{'resource.0.version'} eq '') ||
                   2596:             ($record{'resource.0.version'} < 2)) {
                   2597:             return ($record{'resource.0.version'},
                   2598:                     $record{'resource.0.version'},$result,$js);
                   2599:         } else {
                   2600:             $current = $record{'resource.0.version'};
                   2601:         }
                   2602:         if ($env{'form.previousversion'}) {
                   2603:             $displayed = $env{'form.previousversion'};
                   2604:             $rowtitle = &mt('Choose another version:')
                   2605:         } else {
                   2606:             $displayed = $current;
                   2607:             $rowtitle = &mt('Show earlier version:');
                   2608:         }
                   2609:         $result = '<div class="LC_left_float">';
                   2610:         my $list;
                   2611:         my $numversions = 0;
                   2612:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2613:             if ($i == $current) {
                   2614:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2615:                     next;
                   2616:                 } else {
                   2617:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2618:                     $numversions ++;
                   2619:                 }
                   2620:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2621:                 unless ($i == $env{'form.previousversion'}) {
                   2622:                     $numversions ++;
                   2623:                 }
                   2624:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2625:             }
                   2626:         }
                   2627:         if ($numversions) {
                   2628:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2629:             $result .=
                   2630:                 '<form name="getprev" method="post" action=""'.
                   2631:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2632:                 &Apache::loncommon::start_data_table().
                   2633:                 &Apache::loncommon::start_data_table_row().
                   2634:                 '<th align="left">'.$rowtitle.'</th>'.
                   2635:                 '<td><select name="version">'.
                   2636:                 '<option>'.&mt('Select').'</option>'.
                   2637:                 $list.
                   2638:                 '</select></td>'.
                   2639:                 &Apache::loncommon::end_data_table_row();
                   2640:             unless ($nomenu) {
                   2641:                 $result .= &Apache::loncommon::start_data_table_row().
                   2642:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2643:                 '<td><span class="LC_nobreak">'.
                   2644:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2645:                 &mt('Yes').'</label>'.
                   2646:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2647:                 '</span></td>'.
                   2648:                 &Apache::loncommon::end_data_table_row();
                   2649:             }
                   2650:             $result .=
                   2651:                 &Apache::loncommon::start_data_table_row().
                   2652:                 '<th align="left">&nbsp;</th>'.
                   2653:                 '<td>'.
                   2654:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2655:                 '</td>'.
                   2656:                 &Apache::loncommon::end_data_table_row().
                   2657:                 &Apache::loncommon::end_data_table().
                   2658:                 '</form>';
                   2659:             $js = &previous_display_javascript($nomenu,$current);
                   2660:         } elsif ($displayed && $nomenu) {
                   2661:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2662:         } else {
                   2663:             $result .= &mt('No previous versions to show for this student');
                   2664:         }
                   2665:         $result .= '</div>';
                   2666:     }
                   2667:     return ($current,$displayed,$result,$js);
                   2668: }
                   2669: 
                   2670: sub previous_display_javascript {
                   2671:     my ($nomenu,$current) = @_;
                   2672:     my $js = <<"JSONE";
                   2673: <script type="text/javascript">
                   2674: // <![CDATA[
                   2675: function previousVersion(uname,udom,symb) {
                   2676:     var current = '$current';
                   2677:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2678:     var prevstr = new RegExp("^\\\\d+\$");
                   2679:     if (!prevstr.test(version)) {
                   2680:         return false;
                   2681:     }
                   2682:     var url = '';
                   2683:     if (version == current) {
                   2684:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2685:     } else {
                   2686:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2687:     }
                   2688: JSONE
                   2689:     if ($nomenu) {
                   2690:         $js .= <<"JSTWO";
                   2691:     document.location.href = url;
                   2692: JSTWO
                   2693:     } else {
                   2694:         $js .= <<"JSTHREE";
                   2695:     var newwin = 0;
                   2696:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2697:         if (document.getprev.prevwin[i].checked == true) {
                   2698:             newwin = document.getprev.prevwin[i].value;
                   2699:         }
                   2700:     }
                   2701:     if (newwin == 1) {
                   2702:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2703:         url = url+'&inhibitmenu=yes';
                   2704:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2705:             previousWin = window.open(url,'',options,1);
                   2706:         } else {
                   2707:             previousWin.location.href = url;
                   2708:         }
                   2709:         previousWin.focus();
                   2710:         return false;
                   2711:     } else {
                   2712:         document.location.href = url;
                   2713:         return false;
                   2714:     }
                   2715: JSTHREE
                   2716:     }
                   2717:     $js .= <<"ENDJS";
                   2718:     return false;
                   2719: }
                   2720: // ]]>
                   2721: </script>
                   2722: ENDJS
                   2723: 
                   2724: }
                   2725: 
1.44      ng       2726: #--- Called from submission routine
1.38      ng       2727: sub processHandGrade {
1.608     www      2728:     my ($request,$symb) = @_;
1.324     albertel 2729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2730:     my $button = $env{'form.gradeOpt'};
                   2731:     my $ngrade = $env{'form.NCT'};
                   2732:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2733:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2734:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2735: 
1.44      ng       2736:     if ($button eq 'Save & Next') {
                   2737: 	my $ctr = 0;
                   2738: 	while ($ctr < $ngrade) {
1.257     albertel 2739: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2740: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2741: 	    if ($errorflag eq 'no_score') {
                   2742: 		$ctr++;
                   2743: 		next;
                   2744: 	    }
1.104     albertel 2745: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2746: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2747: 		$ctr++;
                   2748: 		next;
                   2749: 	    }
1.257     albertel 2750: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2751: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2752: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2753:             my ($feedurl,$showsymb) =
                   2754: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2755: 	    my $messagetail;
1.62      albertel 2756: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2757: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2758: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2759: 		$subject.=' ['.$restitle.']';
1.44      ng       2760: 		my (@msgnum) = split(/,/,$includemsg);
                   2761: 		foreach (@msgnum) {
1.257     albertel 2762: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2763: 		}
1.80      ng       2764: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2765: 		if ($env{'form.withgrades'.$ctr}) {
                   2766: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2767: 		    $messagetail = " for <a href=\"".
1.605     www      2768: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2769: 		}
                   2770: 		$msgstatus = 
                   2771:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2772: 						     $message.$messagetail,
1.418     albertel 2773:                                                      undef,$feedurl,undef,
1.386     raeburn  2774:                                                      undef,undef,$showsymb,
                   2775:                                                      $restitle);
1.574     bisitz   2776: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2777: 				$msgstatus.'<br />');
1.44      ng       2778: 	    }
1.257     albertel 2779: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2780: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2781: 		foreach my $collabstr (@collabstrs) {
                   2782: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2783: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2784: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2785: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2786: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2787: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2788: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2789: 			    next;
1.418     albertel 2790: 			} elsif ($message ne '') {
                   2791: 			    my ($baseurl,$showsymb) = 
                   2792: 				&get_feedurl_and_symb($symb,$collaborator,
                   2793: 						      $udom);
                   2794: 			    if ($env{'form.withgrades'.$ctr}) {
                   2795: 				$messagetail = " for <a href=\"".
1.605     www      2796:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2797: 			    }
1.418     albertel 2798: 			    $msgstatus = 
                   2799: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2800: 			}
1.44      ng       2801: 		    }
                   2802: 		}
                   2803: 	    }
                   2804: 	    $ctr++;
                   2805: 	}
                   2806:     }
                   2807: 
1.624     www      2808: #    if ($env{'form.handgrade'} eq 'yes') {
                   2809:     if (1) {
1.119     ng       2810: 	# Keywords sorted in alphabatical order
1.257     albertel 2811: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2812: 	my %keyhash = ();
1.257     albertel 2813: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2814: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2815: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2816: 	$env{'form.keywords'} = join(' ',@keywords);
                   2817: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2818: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2819: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2820: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2821: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2822: 
                   2823: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2824: 	# New messages are saved in env for the next student.
1.119     ng       2825: 	# All messages are saved in nohist_handgrade.db
                   2826: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2827: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2828: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2829: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2830: 		$idx++;
                   2831: 	    }
                   2832: 	    $ctr++;
1.41      ng       2833: 	}
1.119     ng       2834: 	$ctr = 0;
                   2835: 	while ($ctr < $ngrade) {
1.257     albertel 2836: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2837: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2838: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2839: 		$idx++;
                   2840: 	    }
                   2841: 	    $ctr++;
1.41      ng       2842: 	}
1.257     albertel 2843: 	$env{'form.savemsgN'} = --$idx;
                   2844: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2845: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2846: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2847:     }
1.44      ng       2848:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2849:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2850:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2851: 	my ($ctr,$total) = (0,0);
                   2852: 	while ($ctr < $ngrade) {
1.257     albertel 2853: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2854: 	    $ctr++;
                   2855: 	}
1.257     albertel 2856: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2857: 	$ctr = 0;
                   2858: 	while ($ctr < $total) {
1.257     albertel 2859: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2860: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2861: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2862: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2863: 	    $ctr++;
                   2864: 	}
                   2865: 	return '';
                   2866:     }
1.36      ng       2867: 
1.44      ng       2868:     # Get the next/previous one or group of students
1.257     albertel 2869:     my $firststu = $env{'form.unamedom0'};
                   2870:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2871:     my $ctr = 2;
1.41      ng       2872:     while ($laststu eq '') {
1.257     albertel 2873: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2874: 	$ctr++;
                   2875: 	$laststu = $firststu if ($ctr > $ngrade);
                   2876:     }
1.44      ng       2877: 
1.41      ng       2878:     my (@parsedlist,@nextlist);
                   2879:     my ($nextflg) = 0;
1.524     raeburn  2880:     foreach my $item (sort 
1.294     albertel 2881: 	     {
                   2882: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2883: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2884: 		 }
                   2885: 		 return $a cmp $b;
                   2886: 	     } (keys(%$fullname))) {
1.605     www      2887: # FIXME: this is fishy, looks like the button label
1.41      ng       2888: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2889: 	    push(@parsedlist,$item);
1.41      ng       2890: 	}
1.524     raeburn  2891: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2892: 	if ($button eq 'Previous') {
1.524     raeburn  2893: 	    last if ($item eq $firststu);
                   2894: 	    push(@parsedlist,$item);
1.41      ng       2895: 	}
                   2896:     }
                   2897:     $ctr = 0;
1.605     www      2898: # FIXME: this is fishy, looks like the button label
1.41      ng       2899:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2900:     my $res_error;
                   2901:     my ($partlist) = &response_type($symb,\$res_error);
                   2902:     if ($res_error) {
                   2903:         $request->print(&navmap_errormsg());
                   2904:         return;
                   2905:     }
1.41      ng       2906:     foreach my $student (@parsedlist) {
1.257     albertel 2907: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2908: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2909: 	
                   2910: 	if ($submitonly eq 'queued') {
                   2911: 	    my %queue_status = 
                   2912: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2913: 							$udom,$uname);
                   2914: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2915: 	}
                   2916: 
1.156     albertel 2917: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2918: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2919: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2920: 	    my $submitted = 0;
1.248     albertel 2921: 	    my $ungraded = 0;
                   2922: 	    my $incorrect = 0;
1.524     raeburn  2923: 	    foreach my $item (keys(%status)) {
                   2924: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2925: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2926: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2927: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2928: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2929: 		    $submitted = 0;
                   2930: 		}
1.41      ng       2931: 	    }
1.156     albertel 2932: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2933: 				     $submitonly eq 'incorrect' ||
                   2934: 				     $submitonly eq 'graded'));
1.248     albertel 2935: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2936: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2937: 	}
1.524     raeburn  2938: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2939: 	last if ($ctr == $ntstu);
1.41      ng       2940: 	$ctr++;
                   2941:     }
1.36      ng       2942: 
1.41      ng       2943:     $ctr = 0;
                   2944:     my $total = scalar(@nextlist)-1;
1.39      ng       2945: 
1.524     raeburn  2946:     foreach (sort(@nextlist)) {
1.41      ng       2947: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2948: 	$env{'form.student'}  = $uname;
                   2949: 	$env{'form.userdom'}  = $udom;
                   2950: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2951: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2952: 	$ctr++;
                   2953:     }
                   2954:     if ($total < 0) {
1.653     raeburn  2955: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2956: 	$request->print($the_end);
                   2957:     }
                   2958:     return '';
1.38      ng       2959: }
1.36      ng       2960: 
1.44      ng       2961: #---- Save the score and award for each student, if changed
1.38      ng       2962: sub saveHandGrade {
1.324     albertel 2963:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2964:     my @version_parts;
1.104     albertel 2965:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2966: 					   $env{'request.course.id'});
1.104     albertel 2967:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2968:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2969:     my @parts_graded;
1.77      ng       2970:     my %newrecord  = ();
                   2971:     my ($pts,$wgt) = ('','');
1.269     raeburn  2972:     my %aggregate = ();
                   2973:     my $aggregateflag = 0;
1.301     albertel 2974:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2975:     foreach my $new_part (@parts) {
1.337     banghart 2976: 	#collaborator ($submi may vary for different parts
1.259     banghart 2977: 	if ($submitter && $new_part ne $part) { next; }
                   2978: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2979: 	if ($dropMenu eq 'excused') {
1.259     banghart 2980: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2981: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2982: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2983: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2984: 		}
1.364     banghart 2985: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2986: 	    }
1.125     ng       2987: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2988: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2989: 	    foreach my $key (keys(%record)) {
1.259     banghart 2990: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2991: 	    }
1.259     banghart 2992: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2993: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2994:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2995: 
                   2996:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2997: 					       [$new_part]);
                   2998:             my $aggtries =$totaltries;
1.269     raeburn  2999:             if ($last_resets{$new_part}) {
1.270     albertel 3000:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3001: 					   $new_part);
1.269     raeburn  3002:             }
1.270     albertel 3003: 
                   3004:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3005:             if ($aggtries > 0) {
1.327     albertel 3006:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3007:                 $aggregateflag = 1;
                   3008:             }
1.125     ng       3009: 	} elsif ($dropMenu eq '') {
1.259     banghart 3010: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3011: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3012: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3013: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3014: 		next;
                   3015: 	    }
1.259     banghart 3016: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3017: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3018: 	    my $partial= $pts/$wgt;
1.259     banghart 3019: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3020: 		#do not update score for part if not changed.
1.346     banghart 3021:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3022: 		next;
1.251     banghart 3023: 	    } else {
1.524     raeburn  3024: 	        push(@parts_graded,$new_part);
1.153     albertel 3025: 	    }
1.259     banghart 3026: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3027: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3028: 	    }
1.259     banghart 3029: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3030: 	    if ($partial == 0) {
1.153     albertel 3031: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3032: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3033: 		}
1.41      ng       3034: 	    } else {
1.153     albertel 3035: 		if ($record{$reckey} ne 'correct_by_override') {
                   3036: 		    $newrecord{$reckey} = 'correct_by_override';
                   3037: 		}
                   3038: 	    }	    
                   3039: 	    if ($submitter && 
1.259     banghart 3040: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3041: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3042: 	    }
1.259     banghart 3043: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3044: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3045: 	}
1.259     banghart 3046: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3047: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3048: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3049: 	        $dropMenu eq 'reset status')
                   3050: 	   {
1.524     raeburn  3051: 	    push(@version_parts,$new_part);
1.259     banghart 3052: 	}
1.41      ng       3053:     }
1.301     albertel 3054:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3055:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3056: 
1.344     albertel 3057:     if (%newrecord) {
                   3058:         if (@version_parts) {
1.364     banghart 3059:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3060:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3061: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3062: 	    foreach my $new_part (@version_parts) {
                   3063: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3064: 				$new_part,\%newrecord);
                   3065: 	    }
1.259     banghart 3066:         }
1.44      ng       3067: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3068: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3069: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3070: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3071:     }
1.269     raeburn  3072:     if ($aggregateflag) {
                   3073:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3074: 			      $cdom,$cnum);
1.269     raeburn  3075:     }
1.301     albertel 3076:     return ('',$pts,$wgt);
1.36      ng       3077: }
1.322     albertel 3078: 
1.380     albertel 3079: sub check_and_remove_from_queue {
                   3080:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3081:     my @ungraded_parts;
                   3082:     foreach my $part (@{$parts}) {
                   3083: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3084: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3085: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3086: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3087: 		) {
                   3088: 	    push(@ungraded_parts, $part);
                   3089: 	}
                   3090:     }
                   3091:     if ( !@ungraded_parts ) {
                   3092: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3093: 					       $cnum,$domain,$stuname);
                   3094:     }
                   3095: }
                   3096: 
1.337     banghart 3097: sub handback_files {
                   3098:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3099:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3100:     my $res_error;
                   3101:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3102:     if ($res_error) {
                   3103:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3104:         return;
                   3105:     }
1.654     raeburn  3106:     my @handedback;
                   3107:     my $file_msg;
1.375     albertel 3108:     my @part_response_id = &flatten_responseType($responseType);
                   3109:     foreach my $part_response_id (@part_response_id) {
                   3110:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3111: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3112:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3113:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3114:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3115:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3116:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3117:                     my ($directory,$answer_file) = 
1.654     raeburn  3118:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3119:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3120: 		        &file_name_version_ext($answer_file);
1.355     banghart 3121: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3122:                     my $getpropath = 1;
1.662     raeburn  3123:                     my ($dir_list,$listerror) = 
                   3124:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3125:                                                  $domain,$stuname,$getpropath);
                   3126: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3127:                     # fix filename
1.355     banghart 3128:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3129:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3130:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3131:             	                                $save_file_name);
1.337     banghart 3132:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3133:                         $request->print('<br /><span class="LC_error">'.
                   3134:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3135:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3136:                                         '</span>');
1.356     banghart 3137:                     } else {
1.360     banghart 3138:                         # mark the file as read only
1.654     raeburn  3139:                         push(@handedback,$save_file_name);
1.367     albertel 3140: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3141: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3142: 			}
                   3143:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3144: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3145:                     }
1.686     bisitz   3146:                     $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 3147:                 }
                   3148:             }
                   3149:         }
1.654     raeburn  3150:     }
                   3151:     if (@handedback > 0) {
                   3152:         $request->print('<br />');
                   3153:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3154:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3155:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3156:         my ($subject,$message);
                   3157:         if (scalar(@handedback) == 1) {
                   3158:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3159:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3160:         } else {
                   3161:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3162:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3163:         }
                   3164:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3165:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3166:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3167:         my ($feedurl,$showsymb) =
                   3168:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3169:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3170:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3171:         my $msgstatus =
                   3172:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3173:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3174:                  $restitle);
                   3175:         if ($msgstatus) {
                   3176:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3177:         }
                   3178:     }
1.338     banghart 3179:     return;
1.337     banghart 3180: }
                   3181: 
1.418     albertel 3182: sub get_feedurl_and_symb {
                   3183:     my ($symb,$uname,$udom) = @_;
                   3184:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3185:     $url = &Apache::lonnet::clutter($url);
                   3186:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3187: 					$symb,$udom,$uname);
                   3188:     if ($encrypturl =~ /^yes$/i) {
                   3189: 	&Apache::lonenc::encrypted(\$url,1);
                   3190: 	&Apache::lonenc::encrypted(\$symb,1);
                   3191:     }
                   3192:     return ($url,$symb);
                   3193: }
                   3194: 
1.313     banghart 3195: sub get_submitted_files {
                   3196:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3197:     my @files;
                   3198:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3199:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3200:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3201:     	    push(@files,$file_url.$file);
                   3202:         }
                   3203:     }
                   3204:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3205:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3206:     }
                   3207:     return (\@files);
                   3208: }
1.322     albertel 3209: 
1.269     raeburn  3210: # ----------- Provides number of tries since last reset.
                   3211: sub get_num_tries {
                   3212:     my ($record,$last_reset,$part) = @_;
                   3213:     my $timestamp = '';
                   3214:     my $num_tries = 0;
                   3215:     if ($$record{'version'}) {
                   3216:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3217:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3218:                 $timestamp = $$record{$version.':timestamp'};
                   3219:                 if ($timestamp > $last_reset) {
                   3220:                     $num_tries ++;
                   3221:                 } else {
                   3222:                     last;
                   3223:                 }
                   3224:             }
                   3225:         }
                   3226:     }
                   3227:     return $num_tries;
                   3228: }
                   3229: 
                   3230: # ----------- Determine decrements required in aggregate totals 
                   3231: sub decrement_aggs {
                   3232:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3233:     my %decrement = (
                   3234:                         attempts => 0,
                   3235:                         users => 0,
                   3236:                         correct => 0
                   3237:                     );
                   3238:     $decrement{'attempts'} = $aggtries;
                   3239:     if ($solvedstatus =~ /^correct/) {
                   3240:         $decrement{'correct'} = 1;
                   3241:     }
                   3242:     if ($aggtries == $totaltries) {
                   3243:         $decrement{'users'} = 1;
                   3244:     }
1.524     raeburn  3245:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3246:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3247:     }
                   3248:     return;
                   3249: }
                   3250: 
                   3251: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3252: sub get_last_resets {
1.270     albertel 3253:     my ($symb,$courseid,$partids) =@_;
                   3254:     my %last_resets;
1.269     raeburn  3255:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3256:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3257:     my @keys;
                   3258:     foreach my $part (@{$partids}) {
                   3259: 	push(@keys,"$symb\0$part\0resettime");
                   3260:     }
                   3261:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3262: 				     $cdom,$cname);
                   3263:     foreach my $part (@{$partids}) {
                   3264: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3265:     }
1.270     albertel 3266:     return %last_resets;
1.269     raeburn  3267: }
                   3268: 
1.251     banghart 3269: # ----------- Handles creating versions for portfolio files as answers
                   3270: sub version_portfiles {
1.343     banghart 3271:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3272:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3273:     my @returned_keys;
1.255     banghart 3274:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3275:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3276:     foreach my $key (keys(%$record)) {
1.259     banghart 3277:         my $new_portfiles;
1.263     banghart 3278:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3279:             my @versioned_portfiles;
1.367     albertel 3280:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3281:             foreach my $file (@portfiles) {
1.306     banghart 3282:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3283:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3284: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3285: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3286:                 my $getpropath = 1;    
1.662     raeburn  3287:                 my ($dir_list,$listerror) = 
                   3288:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3289:                                              $stu_name,$getpropath);
                   3290:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3291:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3292:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3293:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3294:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3295:                         [$directory.$new_answer],
1.306     banghart 3296:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3297:                 }
1.252     banghart 3298:             }
1.343     banghart 3299:             $$record{$key} = join(',',@versioned_portfiles);
                   3300:             push(@returned_keys,$key);
1.251     banghart 3301:         }
                   3302:     } 
1.343     banghart 3303:     return (@returned_keys);   
1.305     banghart 3304: }
                   3305: 
1.307     banghart 3306: sub get_next_version {
1.341     banghart 3307:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3308:     my $version;
1.662     raeburn  3309:     if (ref($dir_list) eq 'ARRAY') {
                   3310:         foreach my $row (@{$dir_list}) {
                   3311:             my ($file) = split(/\&/,$row,2);
                   3312:             my ($file_name,$file_version,$file_ext) =
                   3313: 	        &file_name_version_ext($file);
                   3314:             if (($file_name eq $answer_name) && 
                   3315: 	        ($file_ext eq $answer_ext)) {
                   3316:                      # gets here if filename and extension match, 
                   3317:                      # regardless of version
1.307     banghart 3318:                 if ($file_version ne '') {
1.662     raeburn  3319:                     # a versioned file is found  so save it for later
                   3320:                     if ($file_version > $version) {
                   3321: 		        $version = $file_version;
                   3322: 	            }
                   3323:                 }
1.307     banghart 3324:             }
                   3325:         }
1.662     raeburn  3326:     }
1.307     banghart 3327:     $version ++;
                   3328:     return($version);
                   3329: }
                   3330: 
1.305     banghart 3331: sub version_selected_portfile {
1.306     banghart 3332:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3333:     my ($answer_name,$answer_ver,$answer_ext) =
                   3334:         &file_name_version_ext($file_name);
                   3335:     my $new_answer;
                   3336:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3337:     if($env{'form.copy'} eq '-1') {
                   3338:         $new_answer = 'problem getting file';
                   3339:     } else {
                   3340:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3341:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3342:                             $stu_name,$domain,'copy',
                   3343: 		        '/portfolio'.$directory.$new_answer);
                   3344:     }    
                   3345:     return ($new_answer);
1.251     banghart 3346: }
                   3347: 
1.304     albertel 3348: sub file_name_version_ext {
                   3349:     my ($file)=@_;
                   3350:     my @file_parts = split(/\./, $file);
                   3351:     my ($name,$version,$ext);
                   3352:     if (@file_parts > 1) {
                   3353: 	$ext=pop(@file_parts);
                   3354: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3355: 	    $version=pop(@file_parts);
                   3356: 	}
                   3357: 	$name=join('.',@file_parts);
                   3358:     } else {
                   3359: 	$name=join('.',@file_parts);
                   3360:     }
                   3361:     return($name,$version,$ext);
                   3362: }
                   3363: 
1.44      ng       3364: #--------------------------------------------------------------------------------------
                   3365: #
                   3366: #-------------------------- Next few routines handles grading by section or whole class
                   3367: #
                   3368: #--- Javascript to handle grading by section or whole class
1.42      ng       3369: sub viewgrades_js {
                   3370:     my ($request) = shift;
                   3371: 
1.539     riegler  3372:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3373:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3374:    function writePoint(partid,weight,point) {
1.125     ng       3375: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3376: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3377: 	if (point == "textval") {
1.125     ng       3378: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3379: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3380: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3381: 		var resetbox = false;
                   3382: 		for (var i=0; i<radioButton.length; i++) {
                   3383: 		    if (radioButton[i].checked) {
                   3384: 			textbox.value = i;
                   3385: 			resetbox = true;
                   3386: 		    }
                   3387: 		}
                   3388: 		if (!resetbox) {
                   3389: 		    textbox.value = "";
                   3390: 		}
                   3391: 		return;
                   3392: 	    }
1.109     matthew  3393: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3394: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3395: 				   ") greater than the weight for the part. Accept?");
                   3396: 		if (resp == false) {
                   3397: 		    textbox.value = "";
                   3398: 		    return;
                   3399: 		}
                   3400: 	    }
1.42      ng       3401: 	    for (var i=0; i<radioButton.length; i++) {
                   3402: 		radioButton[i].checked=false;
1.109     matthew  3403: 		if (parseFloat(point) == i) {
1.42      ng       3404: 		    radioButton[i].checked=true;
                   3405: 		}
                   3406: 	    }
1.41      ng       3407: 
1.42      ng       3408: 	} else {
1.125     ng       3409: 	    textbox.value = parseFloat(point);
1.42      ng       3410: 	}
1.41      ng       3411: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3412: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3413: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3414: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3415: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3416: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3417: 	    if (saveval != "correct") {
                   3418: 		scorename.value = point;
1.43      ng       3419: 		if (selname[0].selected != true) {
                   3420: 		    selname[0].selected = true;
                   3421: 		}
1.42      ng       3422: 	    }
                   3423: 	}
1.125     ng       3424: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3425:     }
                   3426: 
                   3427:     function writeRadText(partid,weight) {
1.125     ng       3428: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3429: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3430:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3431: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3432: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3433: 	    for (var i=0; i<radioButton.length; i++) {
                   3434: 		radioButton[i].checked=false;
                   3435: 
                   3436: 	    }
                   3437: 	    textbox.value = "";
                   3438: 
                   3439: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3440: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3441: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3442: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3443: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3444: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3445: 		if ((saveval != "correct") || override) {
1.42      ng       3446: 		    scorename.value = "";
1.125     ng       3447: 		    if (selval[1].selected) {
                   3448: 			selname[1].selected = true;
                   3449: 		    } else {
                   3450: 			selname[2].selected = true;
                   3451: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3452: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3453: 		    }
1.42      ng       3454: 		}
                   3455: 	    }
1.43      ng       3456: 	} else {
                   3457: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3458: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3459: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3460: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3461: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3462: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3463: 		if ((saveval != "correct") || override) {
1.125     ng       3464: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3465: 		    selname[0].selected = true;
                   3466: 		}
                   3467: 	    }
                   3468: 	}	    
1.42      ng       3469:     }
                   3470: 
                   3471:     function changeSelect(partid,user) {
1.125     ng       3472: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3473: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3474: 	var point  = textbox.value;
1.125     ng       3475: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3476: 
1.109     matthew  3477: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3478: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3479: 	    textbox.value = "";
                   3480: 	    return;
                   3481: 	}
1.109     matthew  3482: 	if (parseFloat(point) > parseFloat(weight)) {
                   3483: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3484: 			       ") greater than the weight of the part. Accept?");
                   3485: 	    if (resp == false) {
                   3486: 		textbox.value = "";
                   3487: 		return;
                   3488: 	    }
                   3489: 	}
1.42      ng       3490: 	selval[0].selected = true;
                   3491:     }
                   3492: 
                   3493:     function changeOneScore(partid,user) {
1.125     ng       3494: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3495: 	if (selval[1].selected || selval[2].selected) {
                   3496: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3497: 	    if (selval[2].selected) {
                   3498: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3499: 	    }
1.269     raeburn  3500:         }
1.42      ng       3501:     }
                   3502: 
                   3503:     function resetEntry(numpart) {
                   3504: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3505: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3506: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3507: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3508: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3509: 	    for (var i=0; i<radioButton.length; i++) {
                   3510: 		radioButton[i].checked=false;
                   3511: 
                   3512: 	    }
                   3513: 	    textbox.value = "";
                   3514: 	    selval[0].selected = true;
                   3515: 
                   3516: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3517: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3518: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3519: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3520: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3521: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3522: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3523: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3524: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3525: 		if (saveselval == "excused") {
1.43      ng       3526: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3527: 		} else {
1.43      ng       3528: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3529: 		}
                   3530: 	    }
1.41      ng       3531: 	}
1.42      ng       3532:     }
                   3533: 
1.41      ng       3534: VIEWJAVASCRIPT
1.42      ng       3535: }
                   3536: 
1.44      ng       3537: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3538: sub viewgrades {
1.608     www      3539:     my ($request,$symb) = @_;
1.42      ng       3540:     &viewgrades_js($request);
1.41      ng       3541: 
1.168     albertel 3542:     #need to make sure we have the correct data for later EXT calls, 
                   3543:     #thus invalidate the cache
                   3544:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3545:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3546:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3547:     &Apache::lonnet::clear_EXT_cache_status();
                   3548: 
1.398     albertel 3549:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3550: 
                   3551:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3552:     $result.=&jscriptNform($symb);
1.41      ng       3553: 
1.44      ng       3554:     #beginning of class grading form
1.442     banghart 3555:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3556:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3557: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3558: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3559: 	&build_section_inputs().
1.442     banghart 3560: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3561: 
1.560     raeburn  3562:     my ($common_header,$specific_header);
1.257     albertel 3563:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3564: 	$common_header = &mt('Assign Common Grade to Class');
                   3565:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3566:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3567:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3568: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3569:     } else {
1.560     raeburn  3570:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3571:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3572: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3573:     }
1.560     raeburn  3574:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3575:     #radio buttons/text box for assigning points for a section or class.
                   3576:     #handles different parts of a problem
1.582     raeburn  3577:     my $res_error;
                   3578:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3579:     if ($res_error) {
                   3580:         return &navmap_errormsg();
                   3581:     }
1.42      ng       3582:     my %weight = ();
                   3583:     my $ctsparts = 0;
1.45      ng       3584:     my %seen = ();
1.375     albertel 3585:     my @part_response_id = &flatten_responseType($responseType);
                   3586:     foreach my $part_response_id (@part_response_id) {
                   3587:     	my ($partid,$respid) = @{ $part_response_id };
                   3588: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3589: 	next if $seen{$partid};
                   3590: 	$seen{$partid}++;
1.375     albertel 3591: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3592: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3593: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3594: 
1.324     albertel 3595: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3596: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3597: 	my $ctr = 0;
1.42      ng       3598: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3599: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3600: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3601: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3602: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3603: 	    $ctr++;
                   3604: 	}
1.485     albertel 3605: 	$radio.='</tr></table>';
                   3606: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3607: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3608: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3609: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3610:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3611:             '<select name="SELVAL_'.$partid.'" '.
                   3612:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3613:                 $weight{$partid}.')"> '.
1.401     albertel 3614: 	    '<option selected="selected"> </option>'.
1.485     albertel 3615: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3616: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3617: 	    '</select></td>'.
                   3618:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3619: 	$line.='<input type="hidden" name="partid_'.
                   3620: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3621: 	$line.='<input type="hidden" name="weight_'.
                   3622: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3623: 
                   3624: 	$result.=
                   3625: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3626: 	    '<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 3627: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3628: 	$ctsparts++;
1.41      ng       3629:     }
1.474     albertel 3630:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3631: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3632:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3633: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3634: 
1.44      ng       3635:     #table listing all the students in a section/class
                   3636:     #header of table
1.560     raeburn  3637:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3638:               &Apache::loncommon::start_data_table().
                   3639: 	      &Apache::loncommon::start_data_table_header_row().
                   3640: 	      '<th>'.&mt('No.').'</th>'.
                   3641: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3642:     my $partserror;
                   3643:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3644:     if ($partserror) {
                   3645:         return &navmap_errormsg();
                   3646:     }
1.324     albertel 3647:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3648:     my @partids = ();
1.41      ng       3649:     foreach my $part (@parts) {
                   3650: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3651:         my $narrowtext = &mt('Tries');
                   3652: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3653: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3654: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3655:         push(@partids,$partid);
1.628     www      3656: #
                   3657: # FIXME: Looks like $display looks at English text
                   3658: #
1.324     albertel 3659: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3660: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3661: 	    $result.='<th>'.
1.697     bisitz   3662: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3663: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3664: 	    next;
1.485     albertel 3665: 	    
1.207     albertel 3666: 	} else {
1.485     albertel 3667: 	    if ($display =~ /Problem Status/) {
                   3668: 		my $grade_status_mt = &mt('Grade Status');
                   3669: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3670: 	    }
                   3671: 	    my $part_mt = &mt('Part:');
                   3672: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3673: 	}
1.485     albertel 3674: 
1.474     albertel 3675: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3676:     }
1.474     albertel 3677:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3678: 
1.270     albertel 3679:     my %last_resets = 
                   3680: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3681: 
1.41      ng       3682:     #get info for each student
1.44      ng       3683:     #list all the students - with points and grade status
1.257     albertel 3684:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3685:     my $ctr = 0;
1.294     albertel 3686:     foreach (sort 
                   3687: 	     {
                   3688: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3689: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3690: 		 }
                   3691: 		 return $a cmp $b;
                   3692: 	     } (keys(%$fullname))) {
1.126     ng       3693: 	$ctr++;
1.324     albertel 3694: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3695: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3696:     }
1.474     albertel 3697:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3698:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3699:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3700: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3701:     if (scalar(%$fullname) eq 0) {
                   3702: 	my $colspan=3+scalar(@parts);
1.433     banghart 3703: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3704:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3705: 	$result='<span class="LC_warning">'.
1.485     albertel 3706: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3707: 	        $section_display, $stu_status).
1.433     banghart 3708: 	    '</span>';
1.96      albertel 3709:     }
1.41      ng       3710:     return $result;
                   3711: }
                   3712: 
1.44      ng       3713: #--- call by previous routine to display each student
1.41      ng       3714: sub viewstudentgrade {
1.324     albertel 3715:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3716:     my ($uname,$udom) = split(/:/,$student);
                   3717:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3718:     my %aggregates = (); 
1.474     albertel 3719:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3720: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3721: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3722: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3723: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3724: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3725:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3726:     foreach my $apart (@$parts) {
                   3727: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3728: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3729:         $result.='<td align="center">';
1.269     raeburn  3730:         my ($aggtries,$totaltries);
                   3731:         unless (exists($aggregates{$part})) {
1.270     albertel 3732: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3733: 
                   3734: 	    $aggtries = $totaltries;
1.269     raeburn  3735:             if ($$last_resets{$part}) {  
1.270     albertel 3736:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3737: 					   $part);
                   3738:             }
1.269     raeburn  3739:             $result.='<input type="hidden" name="'.
                   3740:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3741:             $result.='<input type="hidden" name="'.
                   3742:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3743:             $aggregates{$part} = 1;
                   3744:         }
1.41      ng       3745: 	if ($type eq 'awarded') {
1.320     albertel 3746: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3747: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3748: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3749: 	    $result.='<input type="text" name="'.
1.89      albertel 3750: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3751:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3752: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3753: 	} elsif ($type eq 'solved') {
                   3754: 	    my ($status,$foo)=split(/_/,$score,2);
                   3755: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3756: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3757: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3758: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3759: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3760:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3761: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3762: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3763: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3764: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3765: 	} else {
                   3766: 	    $result.='<input type="hidden" name="'.
                   3767: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3768: 		    "\n";
1.233     albertel 3769: 	    $result.='<input type="text" name="'.
1.122     ng       3770: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3771: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3772: 	}
                   3773:     }
1.474     albertel 3774:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3775:     return $result;
1.38      ng       3776: }
                   3777: 
1.44      ng       3778: #--- change scores for all the students in a section/class
                   3779: #    record does not get update if unchanged
1.38      ng       3780: sub editgrades {
1.608     www      3781:     my ($request,$symb) = @_;
1.41      ng       3782: 
1.433     banghart 3783:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3784:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3785:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3786: 
1.477     albertel 3787:     my $result= &Apache::loncommon::start_data_table().
                   3788: 	&Apache::loncommon::start_data_table_header_row().
                   3789: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3790: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3791:     my %scoreptr = (
                   3792: 		    'correct'  =>'correct_by_override',
                   3793: 		    'incorrect'=>'incorrect_by_override',
                   3794: 		    'excused'  =>'excused',
                   3795: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3796:                     'credited' =>'credit_attempted',
1.43      ng       3797: 		    'nothing'  => '',
                   3798: 		    );
1.257     albertel 3799:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3800: 
1.44      ng       3801:     my (@partid);
                   3802:     my %weight = ();
1.54      albertel 3803:     my %columns = ();
1.44      ng       3804:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3805: 
1.582     raeburn  3806:     my $partserror;
                   3807:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3808:     if ($partserror) {
                   3809:         return &navmap_errormsg();
                   3810:     }
1.54      albertel 3811:     my $header;
1.257     albertel 3812:     while ($ctr < $env{'form.totalparts'}) {
                   3813: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3814: 	push(@partid,$partid);
1.257     albertel 3815: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3816: 	$ctr++;
1.54      albertel 3817:     }
1.324     albertel 3818:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3819:     foreach my $partid (@partid) {
1.478     albertel 3820: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3821: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3822: 	$columns{$partid}=2;
                   3823: 	foreach my $stores (@parts) {
                   3824: 	    my ($part,$type) = &split_part_type($stores);
                   3825: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3826: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3827: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3828: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3829:             my $narrowtext = &mt('Tries');
                   3830: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3831: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3832: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3833: 	    $columns{$partid}+=2;
                   3834: 	}
                   3835:     }
                   3836:     foreach my $partid (@partid) {
1.324     albertel 3837: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3838: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3839: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3840: 	    '</th>';
1.54      albertel 3841: 
1.44      ng       3842:     }
1.477     albertel 3843:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3844: 	&Apache::loncommon::start_data_table_header_row().
                   3845: 	$header.
                   3846: 	&Apache::loncommon::end_data_table_header_row();
                   3847:     my @noupdate;
1.126     ng       3848:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3849:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3850: 	my $line;
1.257     albertel 3851: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3852: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3853: 	my %newrecord;
                   3854: 	my $updateflag = 0;
1.281     albertel 3855: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3856: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3857: 	if (!&canmodify($usec)) {
1.126     ng       3858: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3859: 	    push(@noupdate,
1.478     albertel 3860: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3861: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3862: 	    next;
                   3863: 	}
1.269     raeburn  3864:         my %aggregate = ();
                   3865:         my $aggregateflag = 0;
1.281     albertel 3866: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3867: 	foreach (@partid) {
1.257     albertel 3868: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3869: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3870: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3871: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3872: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3873: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3874: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3875: 	    my $score;
                   3876: 	    if ($partial eq '') {
1.257     albertel 3877: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3878: 	    } elsif ($partial > 0) {
                   3879: 		$score = 'correct_by_override';
                   3880: 	    } elsif ($partial == 0) {
                   3881: 		$score = 'incorrect_by_override';
                   3882: 	    }
1.257     albertel 3883: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3884: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3885: 
1.292     albertel 3886: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3887: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3888: 	    if ($dropMenu eq 'reset status' &&
                   3889: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3890: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3891: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3892: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3893: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3894: 		$updateflag = 1;
1.269     raeburn  3895:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3896:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3897:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3898:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3899:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3900:                     $aggregateflag = 1;
                   3901:                 }
1.139     albertel 3902: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3903: 		$updateflag = 1;
                   3904: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3905: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3906: 		$rec_update++;
1.125     ng       3907: 	    }
                   3908: 
1.93      albertel 3909: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3910: 		'<td align="center">'.$awarded.
                   3911: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3912: 
1.54      albertel 3913: 
                   3914: 	    my $partid=$_;
                   3915: 	    foreach my $stores (@parts) {
                   3916: 		my ($part,$type) = &split_part_type($stores);
                   3917: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3918: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3919: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3920: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3921: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3922: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3923: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3924: 		    $updateflag=1;
                   3925: 		}
1.93      albertel 3926: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3927: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3928: 	    }
1.44      ng       3929: 	}
1.477     albertel 3930: 	$line.="\n";
1.301     albertel 3931: 
                   3932: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3933: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3934: 
1.44      ng       3935: 	if ($updateflag) {
                   3936: 	    $count++;
1.257     albertel 3937: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3938: 				    $udom,$uname);
1.301     albertel 3939: 
                   3940: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3941: 					      $cnum,$udom,$uname)) {
                   3942: 		# need to figure out if should be in queue.
                   3943: 		my %record =  
                   3944: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3945: 					     $udom,$uname);
                   3946: 		my $all_graded = 1;
                   3947: 		my $none_graded = 1;
                   3948: 		foreach my $part (@parts) {
                   3949: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3950: 			$all_graded = 0;
                   3951: 		    } else {
                   3952: 			$none_graded = 0;
                   3953: 		    }
                   3954: 		}
                   3955: 
                   3956: 		if ($all_graded || $none_graded) {
                   3957: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3958: 							   $symb,$cdom,$cnum,
                   3959: 							   $udom,$uname);
                   3960: 		}
                   3961: 	    }
                   3962: 
1.477     albertel 3963: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3964: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3965: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3966: 	    $updateCtr++;
1.93      albertel 3967: 	} else {
1.477     albertel 3968: 	    push(@noupdate,
                   3969: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3970: 	    $noupdateCtr++;
1.44      ng       3971: 	}
1.269     raeburn  3972:         if ($aggregateflag) {
                   3973:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3974: 				  $cdom,$cnum);
1.269     raeburn  3975:         }
1.93      albertel 3976:     }
1.477     albertel 3977:     if (@noupdate) {
1.126     ng       3978: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3979: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3980: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3981: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3982: 	    &mt('No Changes Occurred For the Students Below').
                   3983: 	    '</td>'.
1.477     albertel 3984: 	    &Apache::loncommon::end_data_table_row();
                   3985: 	foreach my $line (@noupdate) {
                   3986: 	    $result.=
                   3987: 		&Apache::loncommon::start_data_table_row().
                   3988: 		$line.
                   3989: 		&Apache::loncommon::end_data_table_row();
                   3990: 	}
1.44      ng       3991:     }
1.614     www      3992:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3993:     my $msg = '<p><b>'.
                   3994: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3995: 	    $rec_update,$count).'</b><br />'.
                   3996: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3997: 	'</b></p>';
1.44      ng       3998:     return $title.$msg.$result;
1.5       albertel 3999: }
1.54      albertel 4000: 
                   4001: sub split_part_type {
                   4002:     my ($partstr) = @_;
                   4003:     my ($temp,@allparts)=split(/_/,$partstr);
                   4004:     my $type=pop(@allparts);
1.439     albertel 4005:     my $part=join('_',@allparts);
1.54      albertel 4006:     return ($part,$type);
                   4007: }
                   4008: 
1.44      ng       4009: #------------- end of section for handling grading by section/class ---------
                   4010: #
                   4011: #----------------------------------------------------------------------------
                   4012: 
1.5       albertel 4013: 
1.44      ng       4014: #----------------------------------------------------------------------------
                   4015: #
                   4016: #-------------------------- Next few routines handles grading by csv upload
                   4017: #
                   4018: #--- Javascript to handle csv upload
1.27      albertel 4019: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4020:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4021:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4022:   return(<<ENDPICK);
                   4023:   function verify(vf) {
                   4024:     var foundsomething=0;
                   4025:     var founduname=0;
1.243     albertel 4026:     var foundID=0;
1.27      albertel 4027:     for (i=0;i<=vf.nfields.value;i++) {
                   4028:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4029:       if (i==0 && tw!=0) { foundID=1; }
                   4030:       if (i==1 && tw!=0) { founduname=1; }
                   4031:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4032:     }
1.246     albertel 4033:     if (founduname==0 && foundID==0) {
                   4034: 	alert('$error1');
                   4035: 	return;
1.27      albertel 4036:     }
                   4037:     if (foundsomething==0) {
1.246     albertel 4038: 	alert('$error2');
                   4039: 	return;
1.27      albertel 4040:     }
                   4041:     vf.submit();
                   4042:   }
                   4043:   function flip(vf,tf) {
                   4044:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4045:     var i;
                   4046:     for (i=0;i<=vf.nfields.value;i++) {
                   4047:       //can not pick the same destination field for both name and domain
                   4048:       if (((i ==0)||(i ==1)) && 
                   4049:           ((tf==0)||(tf==1)) && 
                   4050:           (i!=tf) &&
                   4051:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4052:         eval('vf.f'+i+'.selectedIndex=0;')
                   4053:       }
                   4054:     }
                   4055:   }
                   4056: ENDPICK
                   4057: }
                   4058: 
                   4059: sub csvupload_javascript_forward_associate {
1.573     bisitz   4060:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4061:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4062:   return(<<ENDPICK);
                   4063:   function verify(vf) {
                   4064:     var foundsomething=0;
                   4065:     var founduname=0;
1.243     albertel 4066:     var foundID=0;
1.27      albertel 4067:     for (i=0;i<=vf.nfields.value;i++) {
                   4068:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4069:       if (tw==1) { foundID=1; }
                   4070:       if (tw==2) { founduname=1; }
                   4071:       if (tw>3) { foundsomething=1; }
1.27      albertel 4072:     }
1.246     albertel 4073:     if (founduname==0 && foundID==0) {
                   4074: 	alert('$error1');
                   4075: 	return;
1.27      albertel 4076:     }
                   4077:     if (foundsomething==0) {
1.246     albertel 4078: 	alert('$error2');
                   4079: 	return;
1.27      albertel 4080:     }
                   4081:     vf.submit();
                   4082:   }
                   4083:   function flip(vf,tf) {
                   4084:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4085:     var i;
                   4086:     //can not pick the same destination field twice
                   4087:     for (i=0;i<=vf.nfields.value;i++) {
                   4088:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4089:         eval('vf.f'+i+'.selectedIndex=0;')
                   4090:       }
                   4091:     }
                   4092:   }
                   4093: ENDPICK
                   4094: }
                   4095: 
1.26      albertel 4096: sub csvuploadmap_header {
1.324     albertel 4097:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4098:     my $javascript;
1.257     albertel 4099:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4100: 	$javascript=&csvupload_javascript_reverse_associate();
                   4101:     } else {
                   4102: 	$javascript=&csvupload_javascript_forward_associate();
                   4103:     }
1.45      ng       4104: 
1.418     albertel 4105:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4106:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4107:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4108:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4109:     my $reverse=&mt("Reverse Association");
1.41      ng       4110:     $request->print(<<ENDPICK);
1.632     www      4111: <br />
                   4112: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4113: <input type="hidden" name="associate"  value="" />
                   4114: <input type="hidden" name="phase"      value="three" />
                   4115: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4116: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4117: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4118: <input type="hidden" name="upfile_associate" 
1.257     albertel 4119:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4120: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4121: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4122: <hr />
                   4123: ENDPICK
1.597     wenzelju 4124:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4125:     return '';
1.26      albertel 4126: 
                   4127: }
                   4128: 
                   4129: sub csvupload_fields {
1.582     raeburn  4130:     my ($symb,$errorref) = @_;
                   4131:     my (@parts) = &getpartlist($symb,$errorref);
                   4132:     if (ref($errorref)) {
                   4133:         if ($$errorref) {
                   4134:             return;
                   4135:         }
                   4136:     }
                   4137: 
1.556     weissno  4138:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4139: 		['username','Student Username'],
                   4140: 		['domain','Student Domain']);
1.324     albertel 4141:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4142:     foreach my $part (sort(@parts)) {
                   4143: 	my @datum;
                   4144: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4145: 	my $name=$part;
                   4146: 	if  (!$display) { $display = $name; }
                   4147: 	@datum=($name,$display);
1.244     albertel 4148: 	if ($name=~/^stores_(.*)_awarded/) {
                   4149: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4150: 	}
1.41      ng       4151: 	push(@fields,\@datum);
                   4152:     }
                   4153:     return (@fields);
1.26      albertel 4154: }
                   4155: 
                   4156: sub csvuploadmap_footer {
1.41      ng       4157:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4158:     my $buttontext = &mt('Assign Grades');
1.41      ng       4159:     $request->print(<<ENDPICK);
1.26      albertel 4160: </table>
                   4161: <input type="hidden" name="nfields" value="$i" />
                   4162: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4163: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4164: </form>
                   4165: ENDPICK
                   4166: }
                   4167: 
1.283     albertel 4168: sub checkforfile_js {
1.638     www      4169:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4170:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4171:     function checkUpload(formname) {
                   4172: 	if (formname.upfile.value == "") {
1.539     riegler  4173: 	    alert("$alertmsg");
1.86      ng       4174: 	    return false;
                   4175: 	}
                   4176: 	formname.submit();
                   4177:     }
                   4178: CSVFORMJS
1.283     albertel 4179:     return $result;
                   4180: }
                   4181: 
                   4182: sub upcsvScores_form {
1.608     www      4183:     my ($request,$symb) = @_;
1.283     albertel 4184:     if (!$symb) {return '';}
                   4185:     my $result=&checkforfile_js();
1.632     www      4186:     $result.=&Apache::loncommon::start_data_table().
                   4187:              &Apache::loncommon::start_data_table_header_row().
                   4188:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4189:              &Apache::loncommon::end_data_table_header_row().
                   4190:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4191:     my $upload=&mt("Upload Scores");
1.86      ng       4192:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4193:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4194:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4195:     $result.=<<ENDUPFORM;
1.106     albertel 4196: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4197: <input type="hidden" name="symb" value="$symb" />
                   4198: <input type="hidden" name="command" value="csvuploadmap" />
                   4199: $upfile_select
1.589     bisitz   4200: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4201: </form>
                   4202: ENDUPFORM
1.370     www      4203:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4204:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4205:              '</td>'.
                   4206:             &Apache::loncommon::end_data_table_row().
                   4207:             &Apache::loncommon::end_data_table();
1.86      ng       4208:     return $result;
                   4209: }
                   4210: 
                   4211: 
1.26      albertel 4212: sub csvuploadmap {
1.608     www      4213:     my ($request,$symb)= @_;
1.41      ng       4214:     if (!$symb) {return '';}
1.72      ng       4215: 
1.41      ng       4216:     my $datatoken;
1.257     albertel 4217:     if (!$env{'form.datatoken'}) {
1.41      ng       4218: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4219:     } else {
1.257     albertel 4220: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4221: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4222:     }
1.41      ng       4223:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4224:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4225:     my ($i,$keyfields);
                   4226:     if (@records) {
1.582     raeburn  4227:         my $fieldserror;
                   4228: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4229:         if ($fieldserror) {
                   4230:             $request->print(&navmap_errormsg());
                   4231:             return;
                   4232:         }
1.257     albertel 4233: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4234: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4235: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4236: 							  \@fields);
                   4237: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4238: 	    chop($keyfields);
                   4239: 	} else {
                   4240: 	    unshift(@fields,['none','']);
                   4241: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4242: 							    \@fields);
1.311     banghart 4243:             foreach my $rec (@records) {
                   4244:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4245:                 if (%temp) {
                   4246:                     $keyfields=join(',',sort(keys(%temp)));
                   4247:                     last;
                   4248:                 }
                   4249:             }
1.41      ng       4250: 	}
                   4251:     }
                   4252:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4253: 
1.41      ng       4254:     return '';
1.27      albertel 4255: }
                   4256: 
1.246     albertel 4257: sub csvuploadoptions {
1.608     www      4258:     my ($request,$symb)= @_;
1.632     www      4259:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4260:     $request->print(<<ENDPICK);
                   4261: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4262: <input type="hidden" name="command"    value="csvuploadassign" />
                   4263: <p>
                   4264: <label>
                   4265:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4266:    $overwrite
1.246     albertel 4267: </label>
                   4268: </p>
                   4269: ENDPICK
                   4270:     my %fields=&get_fields();
                   4271:     if (!defined($fields{'domain'})) {
1.257     albertel 4272: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4273: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4274:     }
1.257     albertel 4275:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4276: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4277: 	my $cleankey=$1;
                   4278: 	if ($cleankey eq 'command') { next; }
                   4279: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4280: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4281:     }
                   4282:     # FIXME do a check for any duplicated user ids...
                   4283:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4284:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4285: <hr /></form>'."\n");
1.246     albertel 4286:     return '';
                   4287: }
                   4288: 
                   4289: sub get_fields {
                   4290:     my %fields;
1.257     albertel 4291:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4292:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4293: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4294: 	    if ($env{'form.f'.$i} ne 'none') {
                   4295: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4296: 	    }
                   4297: 	} else {
1.257     albertel 4298: 	    if ($env{'form.f'.$i} ne 'none') {
                   4299: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4300: 	    }
                   4301: 	}
1.27      albertel 4302:     }
1.246     albertel 4303:     return %fields;
                   4304: }
                   4305: 
                   4306: sub csvuploadassign {
1.608     www      4307:     my ($request,$symb)= @_;
1.246     albertel 4308:     if (!$symb) {return '';}
1.345     bowersj2 4309:     my $error_msg = '';
1.246     albertel 4310:     &Apache::loncommon::load_tmp_file($request);
                   4311:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4312:     my %fields=&get_fields();
1.257     albertel 4313:     my $courseid=$env{'request.course.id'};
1.97      albertel 4314:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4315:     my @notallowed;
1.41      ng       4316:     my @skipped;
1.657     raeburn  4317:     my @warnings;
1.41      ng       4318:     my $countdone=0;
                   4319:     foreach my $grade (@gradedata) {
                   4320: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4321: 	my $domain;
                   4322: 	if ($entries{$fields{'domain'}}) {
                   4323: 	    $domain=$entries{$fields{'domain'}};
                   4324: 	} else {
1.257     albertel 4325: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4326: 	}
1.243     albertel 4327: 	$domain=~s/\s//g;
1.41      ng       4328: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4329: 	$username=~s/\s//g;
1.243     albertel 4330: 	if (!$username) {
                   4331: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4332: 	    $id=~s/\s//g;
1.243     albertel 4333: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4334: 	    $username=$ids{$id};
                   4335: 	}
1.41      ng       4336: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4337: 	    my $id=$entries{$fields{'ID'}};
                   4338: 	    $id=~s/\s//g;
                   4339: 	    if ($id) {
                   4340: 		push(@skipped,"$id:$domain");
                   4341: 	    } else {
                   4342: 		push(@skipped,"$username:$domain");
                   4343: 	    }
1.41      ng       4344: 	    next;
                   4345: 	}
1.108     albertel 4346: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4347: 	if (!&canmodify($usec)) {
                   4348: 	    push(@notallowed,"$username:$domain");
                   4349: 	    next;
                   4350: 	}
1.244     albertel 4351: 	my %points;
1.41      ng       4352: 	my %grades;
                   4353: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4354: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4355: 		$dest eq 'domain') { next; }
                   4356: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4357: 	    if ($dest=~/stores_(.*)_points/) {
                   4358: 		my $part=$1;
                   4359: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4360: 					      $symb,$domain,$username);
1.345     bowersj2 4361:                 if ($wgt) {
                   4362:                     $entries{$fields{$dest}}=~s/\s//g;
                   4363:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4364:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4365:                                           : 'correct_by_override';
1.638     www      4366:                     if ($pcr>1) {
1.657     raeburn  4367:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4368:                     }
1.345     bowersj2 4369:                     $grades{"resource.$part.awarded"}=$pcr;
                   4370:                     $grades{"resource.$part.solved"}=$award;
                   4371:                     $points{$part}=1;
                   4372:                 } else {
                   4373:                     $error_msg = "<br />" .
                   4374:                         &mt("Some point values were assigned"
                   4375:                             ." for problems with a weight "
                   4376:                             ."of zero. These values were "
                   4377:                             ."ignored.");
                   4378:                 }
1.244     albertel 4379: 	    } else {
                   4380: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4381: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4382: 		my $store_key=$dest;
                   4383: 		$store_key=~s/^stores/resource/;
                   4384: 		$store_key=~s/_/\./g;
                   4385: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4386: 	    }
1.41      ng       4387: 	}
1.508     www      4388: 	if (! %grades) { 
                   4389:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4390:         } else {
                   4391: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4392: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4393: 					   $env{'request.course.id'},
                   4394: 					   $domain,$username);
1.508     www      4395: 	   if ($result eq 'ok') {
1.627     www      4396: # Successfully stored
1.508     www      4397: 	      $request->print('.');
1.627     www      4398: # Remove from grading queue
                   4399:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4400:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4401:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4402:                                              $domain,$username);
                   4403:               $countdone++;
                   4404:            } else {
1.508     www      4405: 	      $request->print("<p><span class=\"LC_error\">".
                   4406:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4407:                                   "$username:$domain",$result)."</span></p>");
                   4408: 	   }
                   4409: 	   $request->rflush();
                   4410:         }
1.41      ng       4411:     }
1.570     www      4412:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4413:     if (@warnings) {
                   4414:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4415:         $request->print(join(', ',@warnings));
                   4416:     }
1.41      ng       4417:     if (@skipped) {
1.571     www      4418: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4419:         $request->print(join(', ',@skipped));
1.106     albertel 4420:     }
                   4421:     if (@notallowed) {
1.571     www      4422: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4423: 	$request->print(join(', ',@notallowed));
1.41      ng       4424:     }
1.106     albertel 4425:     $request->print("<br />\n");
1.345     bowersj2 4426:     return $error_msg;
1.26      albertel 4427: }
1.44      ng       4428: #------------- end of section for handling csv file upload ---------
                   4429: #
                   4430: #-------------------------------------------------------------------
                   4431: #
1.122     ng       4432: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4433: #
                   4434: #--- Select a page/sequence and a student to grade
1.68      ng       4435: sub pickStudentPage {
1.608     www      4436:     my ($request,$symb) = @_;
1.68      ng       4437: 
1.539     riegler  4438:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4439:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4440: 
                   4441: function checkPickOne(formname) {
1.76      ng       4442:     if (radioSelection(formname.student) == null) {
1.539     riegler  4443: 	alert("$alertmsg");
1.68      ng       4444: 	return;
                   4445:     }
1.125     ng       4446:     ptr = pullDownSelection(formname.selectpage);
                   4447:     formname.page.value = formname["page"+ptr].value;
                   4448:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4449:     formname.submit();
                   4450: }
                   4451: 
                   4452: LISTJAVASCRIPT
1.118     ng       4453:     &commonJSfunctions($request);
1.608     www      4454: 
1.257     albertel 4455:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4456:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4457:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4458: 
1.398     albertel 4459:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4460: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4461: 
1.80      ng       4462:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4463:     my $map_error;
                   4464:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4465:     if ($map_error) {
                   4466:         $request->print(&navmap_errormsg());
                   4467:         return; 
                   4468:     }
1.137     albertel 4469:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4470: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4471: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4472: 
                   4473:     # Collection of hidden fields
1.70      ng       4474:     my $ctr=0;
1.68      ng       4475:     foreach (@$titles) {
1.700     bisitz   4476:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4477:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4478:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4479:         $ctr++;
1.68      ng       4480:     }
1.700     bisitz   4481:     $result.='<input type="hidden" name="page" />'."\n".
                   4482:         '<input type="hidden" name="title" />'."\n";
                   4483: 
                   4484:     $result.=&build_section_inputs();
                   4485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4486:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4487: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4488: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4489: 
1.700     bisitz   4490:     # Show grading options
                   4491:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4492:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4493:     $ctr=0;
                   4494:     foreach (@$titles) {
                   4495: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4496: 	$select.='<option value="'.$ctr.'"'.
                   4497: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4498: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4499: 	$ctr++;
                   4500:     }
1.700     bisitz   4501:     $select.= '</select>';
1.68      ng       4502: 
1.700     bisitz   4503:     $result.=
                   4504:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4505:        .$select
                   4506:        .&Apache::lonhtmlcommon::row_closure();
                   4507: 
                   4508:     $result.=
                   4509:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4510:        .'<label><input type="radio" name="vProb" value="no"'
                   4511:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4512:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4513:            .&mt('yes').'</label>'."\n"
                   4514:        .&Apache::lonhtmlcommon::row_closure();
                   4515: 
                   4516:     $result.=
                   4517:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4518:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4519:            .&mt('none').' </label>'."\n"
                   4520:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4521:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4522:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4523:            .&mt('all submissions with details').' </label>'
                   4524:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4525:     
1.700     bisitz   4526:     $result.=
                   4527:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4528:        .'<input type="text" name="CODE" value="" />'
                   4529:        .&Apache::lonhtmlcommon::row_closure(1)
                   4530:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4531: 
1.700     bisitz   4532:     # Show list of students to select for grading
                   4533:     $result.='<br /><input type="button" '.
1.589     bisitz   4534:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4535: 
1.68      ng       4536:     $request->print($result);
                   4537: 
1.485     albertel 4538:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4539: 	&Apache::loncommon::start_data_table().
                   4540: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4541: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4542: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4543: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4544: 	'<th>'.&nameUserString('header').'</th>'.
                   4545: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4546:  
1.76      ng       4547:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4548:     my $ptr = 1;
1.294     albertel 4549:     foreach my $student (sort 
                   4550: 			 {
                   4551: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4552: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4553: 			     }
                   4554: 			     return $a cmp $b;
                   4555: 			 } (keys(%$fullname))) {
1.68      ng       4556: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4557: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4558:                                   : '</td>');
1.126     ng       4559: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4560: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4561: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4562: 	$studentTable.=
                   4563: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4564:                          : '');
1.68      ng       4565: 	$ptr++;
                   4566:     }
1.484     albertel 4567:     if ($ptr%2 == 0) {
                   4568: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4569: 	    &Apache::loncommon::end_data_table_row();
                   4570:     }
                   4571:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4572:     $studentTable.='<input type="button" '.
1.589     bisitz   4573:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4574: 
                   4575:     $request->print($studentTable);
                   4576: 
                   4577:     return '';
                   4578: }
                   4579: 
                   4580: sub getSymbMap {
1.582     raeburn  4581:     my ($map_error) = @_;
1.132     bowersj2 4582:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4583:     unless (ref($navmap)) {
                   4584:         if (ref($map_error)) {
                   4585:             $$map_error = 'navmap';
                   4586:         }
                   4587:         return;
                   4588:     }
1.68      ng       4589:     my %symbx = ();
                   4590:     my @titles = ();
1.117     bowersj2 4591:     my $minder = 0;
                   4592: 
                   4593:     # Gather every sequence that has problems.
1.240     albertel 4594:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4595: 					       1,0,1);
1.117     bowersj2 4596:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4597: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4598: 	    my $title = $minder.'.'.
                   4599: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4600: 	    push(@titles, $title); # minder in case two titles are identical
                   4601: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4602: 	    $minder++;
1.241     albertel 4603: 	}
1.68      ng       4604:     }
                   4605:     return \@titles,\%symbx;
                   4606: }
                   4607: 
1.72      ng       4608: #
                   4609: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4610: sub displayPage {
1.608     www      4611:     my ($request,$symb) = @_;
1.257     albertel 4612:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4613:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4614:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4615:     my $pageTitle = $env{'form.page'};
1.103     albertel 4616:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4617:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4618:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4619: 
                   4620:     #need to make sure we have the correct data for later EXT calls, 
                   4621:     #thus invalidate the cache
                   4622:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4623:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4624:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4625:     &Apache::lonnet::clear_EXT_cache_status();
                   4626: 
1.103     albertel 4627:     if (!&canview($usec)) {
1.712     bisitz   4628:         $request->print(
                   4629:             '<span class="LC_warning">'.
                   4630:             &mt('Unable to view requested student. ([_1])',
                   4631:                     $env{'form.student'}).
                   4632:             '</span>');
                   4633:         return;
1.103     albertel 4634:     }
1.398     albertel 4635:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4636:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4637: 	'</h3>'."\n";
1.500     albertel 4638:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4639:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4640: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4641:     } else {
                   4642: 	delete($env{'form.CODE'});
                   4643:     }
1.71      ng       4644:     &sub_page_js($request);
                   4645:     $request->print($result);
                   4646: 
1.132     bowersj2 4647:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4648:     unless (ref($navmap)) {
                   4649:         $request->print(&navmap_errormsg());
                   4650:         return;
                   4651:     }
1.257     albertel 4652:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4653:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4654:     if (!$map) {
1.485     albertel 4655: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4656: 	return; 
                   4657:     }
1.68      ng       4658:     my $iterator = $navmap->getIterator($map->map_start(),
                   4659: 					$map->map_finish());
                   4660: 
1.71      ng       4661:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4662: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4663: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4664: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4665: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4666: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4667: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4668: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4669: 
1.382     albertel 4670:     if (defined($env{'form.CODE'})) {
                   4671: 	$studentTable.=
                   4672: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4673:     }
1.381     albertel 4674:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4675: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4676: 
1.594     bisitz   4677:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4678:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4679:         '</span>'."\n".
1.484     albertel 4680: 	&Apache::loncommon::start_data_table().
                   4681: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4682: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4683: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4684: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4685: 
1.329     albertel 4686:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4687:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4688:     $iterator->next(); # skip the first BEGIN_MAP
                   4689:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4690:     while ($depth > 0) {
1.68      ng       4691:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4692:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4693: 
1.385     albertel 4694:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4695: 	    my $parts = $curRes->parts();
1.68      ng       4696:             my $title = $curRes->compTitle();
1.71      ng       4697: 	    my $symbx = $curRes->symb();
1.484     albertel 4698: 	    $studentTable.=
                   4699: 		&Apache::loncommon::start_data_table_row().
                   4700: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4701: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4702: 		                        : '<br />('.&mt('[_1]parts',
                   4703: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4704: 		 ).
                   4705: 		 '</td>';
1.71      ng       4706: 	    $studentTable.='<td valign="top">';
1.382     albertel 4707: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4708: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4709: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4710: 					     undef,'both',\%form);
1.71      ng       4711: 	    } else {
1.382     albertel 4712: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4713: 		$companswer =~ s|<form(.*?)>||g;
                   4714: 		$companswer =~ s|</form>||g;
1.71      ng       4715: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4716: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4717: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4718: #		}
1.116     ng       4719: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4720: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4721: 	    }
                   4722: 
1.257     albertel 4723: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4724: 
1.257     albertel 4725: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4726: 		if ($record{'version'} eq '') {
1.485     albertel 4727: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4728: 		} else {
1.116     ng       4729: 		    my %responseType = ();
                   4730: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4731: 			my @responseIds =$curRes->responseIds($partid);
                   4732: 			my @responseType =$curRes->responseType($partid);
                   4733: 			my %responseIds;
                   4734: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4735: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4736: 			}
                   4737: 			$responseType{$partid} = \%responseIds;
1.116     ng       4738: 		    }
1.148     albertel 4739: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4740: 
1.71      ng       4741: 		}
1.257     albertel 4742: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4743: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4744: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4745: 									$env{'request.course.id'},
1.71      ng       4746: 									'','.submission');
                   4747:  
                   4748: 	    }
1.103     albertel 4749: 	    if (&canmodify($usec)) {
1.585     bisitz   4750:             $studentTable.=&gradeBox_start();
1.103     albertel 4751: 		foreach my $partid (@{$parts}) {
                   4752: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4753: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4754: 		    $question++;
                   4755: 		}
1.585     bisitz   4756:             $studentTable.=&gradeBox_end();
1.196     albertel 4757: 		$prob++;
1.71      ng       4758: 	    }
                   4759: 	    $studentTable.='</td></tr>';
1.68      ng       4760: 
1.103     albertel 4761: 	}
1.68      ng       4762:         $curRes = $iterator->next();
                   4763:     }
                   4764: 
1.589     bisitz   4765:     $studentTable.=
                   4766:         '</table>'."\n".
                   4767:         '<input type="button" value="'.&mt('Save').'" '.
                   4768:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4769:         '</form>'."\n";
1.71      ng       4770:     $request->print($studentTable);
                   4771: 
                   4772:     return '';
1.119     ng       4773: }
                   4774: 
                   4775: sub displaySubByDates {
1.148     albertel 4776:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4777:     my $isCODE=0;
1.335     albertel 4778:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4779:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4780:     my $studentTable=&Apache::loncommon::start_data_table().
                   4781: 	&Apache::loncommon::start_data_table_header_row().
                   4782: 	'<th>'.&mt('Date/Time').'</th>'.
                   4783: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4784:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4785: 	'<th>'.&mt('Submission').'</th>'.
                   4786: 	'<th>'.&mt('Status').'</th>'.
                   4787: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4788:     my ($version);
                   4789:     my %mark;
1.148     albertel 4790:     my %orders;
1.119     ng       4791:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4792:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4793: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4794:     }
1.335     albertel 4795: 
                   4796:     my $interaction;
1.525     raeburn  4797:     my $no_increment = 1;
1.640     raeburn  4798:     my %lastrndseed;
1.119     ng       4799:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4800: 	my $timestamp = 
                   4801: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4802: 	if (exists($$record{$version.':resource.0.version'})) {
                   4803: 	    $interaction = $$record{$version.':resource.0.version'};
                   4804: 	}
1.671     raeburn  4805:         if ($isTask && $env{'form.previousversion'}) {
                   4806:             next unless ($interaction == $env{'form.previousversion'});
                   4807:         }
1.335     albertel 4808: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4809: 		             : "$version:resource");
1.467     albertel 4810: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4811: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4812: 	if ($isCODE) {
                   4813: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4814: 	}
1.671     raeburn  4815:         if ($isTask) {
                   4816:             $studentTable.='<td>'.$interaction.'</td>';
                   4817:         }
1.119     ng       4818: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4819: 	my @displaySub = ();
                   4820: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4821:             my ($hidden,$type);
                   4822:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4823:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4824:                 $hidden = 1;
                   4825:             }
1.335     albertel 4826: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4827: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4828: 	    
1.122     ng       4829: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4830: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4831: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4832: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4833: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4834:                     
1.335     albertel 4835: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4836: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4837:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4838:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4839:                                    .' <span class="LC_internal_info">'
1.625     www      4840:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4841:                                    .'</span>'
                   4842:                                    .' <b>';
1.596     raeburn  4843:                     if ($hidden) {
                   4844:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4845:                     } else {
1.640     raeburn  4846:                         my ($trial,$rndseed,$newvariation);
                   4847:                         if ($type eq 'randomizetry') {
                   4848:                             $trial = $$record{"$where.$partid.tries"};
                   4849:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4850:                         }
1.596     raeburn  4851: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4852: 			    $displaySub[0].=&mt('Trial not counted');
                   4853: 		        } else {
                   4854: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4855: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4856:                             if ($rndseed || $lastrndseed{$partid}) {
                   4857:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4858:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4859:                                 }
                   4860:                             }
                   4861:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4862: 		        }
                   4863: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4864:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4865: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4866: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4867: 			    $orders{$partid}->{$responseId}=
                   4868: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4869:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4870: 		        }
1.640     raeburn  4871: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4872: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4873: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4874:                     }
1.147     albertel 4875: 		}
                   4876: 	    }
1.335     albertel 4877: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4878: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4879: 				    $$record{"$where.$partid.checkedin"},
                   4880: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4881: 					'<br />';
1.335     albertel 4882: 	    }
                   4883: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4884: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4885: 		    lc($$record{"$where.$partid.award"}).' '.
                   4886: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4887: 		    '<br />';
                   4888: 	    }
1.335     albertel 4889: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4890: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4891: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4892: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4893: 		$displaySub[2].=
                   4894: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4895: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4896: 	    }
                   4897: 	}
                   4898: 	# needed because old essay regrader has not parts info
                   4899: 	if (exists $$record{"$version:resource.regrader"}) {
                   4900: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4901: 	}
                   4902: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4903: 	if ($displaySub[2]) {
1.467     albertel 4904: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4905: 	}
1.467     albertel 4906: 	$studentTable.='&nbsp;</td>'.
                   4907: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4908:     }
1.467     albertel 4909:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4910:     return $studentTable;
1.71      ng       4911: }
                   4912: 
                   4913: sub updateGradeByPage {
1.608     www      4914:     my ($request,$symb) = @_;
1.71      ng       4915: 
1.257     albertel 4916:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4917:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4918:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4919:     my $pageTitle = $env{'form.page'};
1.103     albertel 4920:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4921:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4922:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4923:     if (!&canmodify($usec)) {
1.526     raeburn  4924: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4925: 	return;
                   4926:     }
1.398     albertel 4927:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4928:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4929: 	'</h3>'."\n";
1.70      ng       4930: 
1.68      ng       4931:     $request->print($result);
                   4932: 
1.582     raeburn  4933: 
1.132     bowersj2 4934:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4935:     unless (ref($navmap)) {
                   4936:         $request->print(&navmap_errormsg());
                   4937:         return;
                   4938:     }
1.257     albertel 4939:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4940:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4941:     if (!$map) {
1.527     raeburn  4942: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4943: 	return; 
                   4944:     }
1.71      ng       4945:     my $iterator = $navmap->getIterator($map->map_start(),
                   4946: 					$map->map_finish());
1.70      ng       4947: 
1.484     albertel 4948:     my $studentTable=
                   4949: 	&Apache::loncommon::start_data_table().
                   4950: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4951: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4952: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4953: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4954: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4955: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4956: 
                   4957:     $iterator->next(); # skip the first BEGIN_MAP
                   4958:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4959:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4960:     while ($depth > 0) {
1.71      ng       4961:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4962:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4963: 
1.385     albertel 4964:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4965: 	    my $parts = $curRes->parts();
1.71      ng       4966:             my $title = $curRes->compTitle();
                   4967: 	    my $symbx = $curRes->symb();
1.484     albertel 4968: 	    $studentTable.=
                   4969: 		&Apache::loncommon::start_data_table_row().
                   4970: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4971: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4972:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4973: 		.')').'</td>';
1.71      ng       4974: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4975: 
                   4976: 	    my %newrecord=();
                   4977: 	    my @displayPts=();
1.269     raeburn  4978:             my %aggregate = ();
                   4979:             my $aggregateflag = 0;
1.71      ng       4980: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4981: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4982: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4983: 
1.257     albertel 4984: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4985: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4986: 		my $partial = $newpts/$wgt;
                   4987: 		my $score;
                   4988: 		if ($partial > 0) {
                   4989: 		    $score = 'correct_by_override';
1.125     ng       4990: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4991: 		    $score = 'incorrect_by_override';
                   4992: 		}
1.257     albertel 4993: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4994: 		if ($dropMenu eq 'excused') {
1.71      ng       4995: 		    $partial = '';
                   4996: 		    $score = 'excused';
1.125     ng       4997: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4998: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4999: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5000: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5001: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5002: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5003: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5004: 		    $changeflag++;
                   5005: 		    $newpts = '';
1.269     raeburn  5006:                     
                   5007:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5008:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5009:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5010:                     if ($aggtries > 0) {
                   5011:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5012:                         $aggregateflag = 1;
                   5013:                     }
1.71      ng       5014: 		}
1.324     albertel 5015: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5016: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5017: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5018: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5019: 		    '&nbsp;<br />';
1.526     raeburn  5020: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5021: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5022: 		    '&nbsp;<br />';
1.71      ng       5023: 		$question++;
1.380     albertel 5024: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5025: 
1.71      ng       5026: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5027: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5028: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5029: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5030: 
                   5031: 		$changeflag++;
                   5032: 	    }
                   5033: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5034: 		my %record = 
                   5035: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5036: 					     $udom,$uname);
                   5037: 
                   5038: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5039: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5040: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5041: 		    $newrecord{'resource.CODE'} = '';
                   5042: 		}
1.257     albertel 5043: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5044: 					$udom,$uname);
1.382     albertel 5045: 		%record = &Apache::lonnet::restore($symbx,
                   5046: 						   $env{'request.course.id'},
                   5047: 						   $udom,$uname);
1.380     albertel 5048: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5049: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5050: 	    }
1.380     albertel 5051: 	    
1.269     raeburn  5052:             if ($aggregateflag) {
                   5053:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5054:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5055:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5056:             }
1.125     ng       5057: 
1.71      ng       5058: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5059: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5060: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5061: 
1.196     albertel 5062: 	    $prob++;
1.68      ng       5063: 	}
1.71      ng       5064:         $curRes = $iterator->next();
1.68      ng       5065:     }
1.98      albertel 5066: 
1.484     albertel 5067:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5068:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5069: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5070: 		  $changeflag));
1.76      ng       5071:     $request->print($grademsg.$studentTable);
1.68      ng       5072: 
1.70      ng       5073:     return '';
                   5074: }
                   5075: 
1.72      ng       5076: #-------- end of section for handling grading by page/sequence ---------
                   5077: #
                   5078: #-------------------------------------------------------------------
                   5079: 
1.581     www      5080: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5081: #
                   5082: #------ start of section for handling grading by page/sequence ---------
                   5083: 
1.423     albertel 5084: =pod
                   5085: 
                   5086: =head1 Bubble sheet grading routines
                   5087: 
1.424     albertel 5088:   For this documentation:
                   5089: 
                   5090:    'scanline' refers to the full line of characters
                   5091:    from the file that we are parsing that represents one entire sheet
                   5092: 
                   5093:    'bubble line' refers to the data
1.659     raeburn  5094:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5095: 
                   5096: 
1.659     raeburn  5097: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5098: into a course. When a user wants to grade, they select a
1.659     raeburn  5099: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5100: one of the predefined configurations for what each scanline looks
                   5101: like.
                   5102: 
                   5103: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5104: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5105: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5106: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5107: invalid student/employee ID
1.424     albertel 5108: 
                   5109: If the CODE option is used that determines the randomization of the
1.556     weissno  5110: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5111: username:domain.
                   5112: 
                   5113: During the validation phase the instructor can choose to skip scanlines. 
                   5114: 
1.659     raeburn  5115: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5116: 
                   5117:   scantron_original_filename (unmodified original file)
                   5118:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5119:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5120: 
                   5121: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5122: correction information that isn't representable in the bubblesheet
1.424     albertel 5123: file (see &scantron_getfile() for more information)
                   5124: 
                   5125: After all scanlines are either valid, marked as valid or skipped, then
                   5126: foreach line foreach problem in the picked sequence, an ssi request is
                   5127: made that simulates a user submitting their selected letter(s) against
                   5128: the homework problem.
1.423     albertel 5129: 
                   5130: =over 4
                   5131: 
                   5132: 
                   5133: 
                   5134: =item defaultFormData
                   5135: 
                   5136:   Returns html hidden inputs used to hold context/default values.
                   5137: 
                   5138:  Arguments:
                   5139:   $symb - $symb of the current resource 
                   5140: 
                   5141: =cut
1.422     foxr     5142: 
1.81      albertel 5143: sub defaultFormData {
1.324     albertel 5144:     my ($symb)=@_;
1.613     www      5145:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5146: }
                   5147: 
1.447     foxr     5148: 
1.423     albertel 5149: =pod 
                   5150: 
                   5151: =item getSequenceDropDown
                   5152: 
                   5153:    Return html dropdown of possible sequences to grade
                   5154:  
                   5155:  Arguments:
1.582     raeburn  5156:    $symb - $symb of the current resource
                   5157:    $map_error - ref to scalar which will container error if
                   5158:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5159: 
                   5160: =cut
1.422     foxr     5161: 
1.75      albertel 5162: sub getSequenceDropDown {
1.582     raeburn  5163:     my ($symb,$map_error)=@_;
1.75      albertel 5164:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5165:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5166:     if (ref($map_error)) {
                   5167:         return if ($$map_error);
                   5168:     }
1.137     albertel 5169:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5170:     my $ctr=0;
                   5171:     foreach (@$titles) {
                   5172: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5173: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5174: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5175: 	    '>'.$showtitle.'</option>'."\n";
                   5176: 	$ctr++;
                   5177:     }
                   5178:     $result.= '</select>';
                   5179:     return $result;
                   5180: }
                   5181: 
1.495     albertel 5182: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5183:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5184: 
                   5185: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5186: 
1.509     raeburn  5187: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5188:                                    # matchresponse or rankresponse, where 
                   5189:                                    # an individual response can have multiple 
                   5190:                                    # lines
1.503     raeburn  5191: 
                   5192: my %responsetype_per_response;     # responsetype for each response
                   5193: 
1.691     raeburn  5194: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5195:                                    # numbered response. Needed when randomorder
                   5196:                                    # or randompick are in use. Key is ID, value 
                   5197:                                    # is response number.
                   5198: 
1.495     albertel 5199: # Save and restore the bubble lines array to the form env.
                   5200: 
                   5201: 
                   5202: sub save_bubble_lines {
                   5203:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5204: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5205: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5206: 	    $first_bubble_line{$line};
1.503     raeburn  5207:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5208:             $subdivided_bubble_lines{$line};
                   5209:         $env{"form.scantron.responsetype.$line"} =
                   5210:             $responsetype_per_response{$line};
1.495     albertel 5211:     }
1.691     raeburn  5212:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5213:         my $line = $masterseq_id_responsenum{$resid};
                   5214:         $env{"form.scantron.residpart.$line"} = $resid;
                   5215:     }
1.495     albertel 5216: }
                   5217: 
                   5218: 
                   5219: sub restore_bubble_lines {
                   5220:     my $line = 0;
                   5221:     %bubble_lines_per_response = ();
1.691     raeburn  5222:     %masterseq_id_responsenum = ();
1.495     albertel 5223:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5224: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5225: 	$bubble_lines_per_response{$line} = $value;
                   5226: 	$first_bubble_line{$line}  =
                   5227: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5228:         $subdivided_bubble_lines{$line} =
                   5229:             $env{"form.scantron.sub_bubblelines.$line"};
                   5230:         $responsetype_per_response{$line} =
                   5231:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5232:         my $id = $env{"form.scantron.residpart.$line"};
                   5233:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5234: 	$line++;
                   5235:     }
                   5236: }
                   5237: 
1.423     albertel 5238: =pod 
                   5239: 
                   5240: =item scantron_filenames
                   5241: 
                   5242:    Returns a list of the scantron files in the current course 
                   5243: 
                   5244: =cut
1.422     foxr     5245: 
1.202     albertel 5246: sub scantron_filenames {
1.257     albertel 5247:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5248:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5249:     my $getpropath = 1;
1.662     raeburn  5250:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5251:                                                         $cname,$getpropath);
1.202     albertel 5252:     my @possiblenames;
1.662     raeburn  5253:     if (ref($dirlist) eq 'ARRAY') {
                   5254:         foreach my $filename (sort(@{$dirlist})) {
                   5255: 	    ($filename)=split(/&/,$filename);
                   5256: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5257: 	    $filename=~s/^scantron_orig_//;
                   5258: 	    push(@possiblenames,$filename);
                   5259:         }
1.202     albertel 5260:     }
                   5261:     return @possiblenames;
                   5262: }
                   5263: 
1.423     albertel 5264: =pod 
                   5265: 
                   5266: =item scantron_uploads
                   5267: 
                   5268:    Returns  html drop-down list of scantron files in current course.
                   5269: 
                   5270:  Arguments:
                   5271:    $file2grade - filename to set as selected in the dropdown
                   5272: 
                   5273: =cut
1.422     foxr     5274: 
1.202     albertel 5275: sub scantron_uploads {
1.209     ng       5276:     my ($file2grade) = @_;
1.202     albertel 5277:     my $result=	'<select name="scantron_selectfile">';
                   5278:     $result.="<option></option>";
                   5279:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5280: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5281:     }
                   5282:     $result.="</select>";
                   5283:     return $result;
                   5284: }
                   5285: 
1.423     albertel 5286: =pod 
                   5287: 
                   5288: =item scantron_scantab
                   5289: 
                   5290:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5291:   file.
                   5292: 
                   5293: =cut
1.422     foxr     5294: 
1.82      albertel 5295: sub scantron_scantab {
                   5296:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5297:     $result.='<option></option>'."\n";
1.518     raeburn  5298:     my @lines = &get_scantronformat_file();
                   5299:     if (@lines > 0) {
                   5300:         foreach my $line (@lines) {
                   5301:             next if (($line =~ /^\#/) || ($line eq ''));
                   5302: 	    my ($name,$descrip)=split(/:/,$line);
                   5303: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5304:         }
1.82      albertel 5305:     }
                   5306:     $result.='</select>'."\n";
1.518     raeburn  5307:     return $result;
                   5308: }
                   5309: 
                   5310: =pod
                   5311: 
                   5312: =item get_scantronformat_file
                   5313: 
                   5314:   Returns an array containing lines from the scantron format file for
                   5315:   the domain of the course.
                   5316: 
                   5317:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5318:   lines are from this file.
                   5319: 
                   5320:   Otherwise, if a default.tab has been published in RES space by the 
                   5321:   domainconfig user, lines are from this file.
                   5322: 
                   5323:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5324:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5325: 
1.518     raeburn  5326: =cut
                   5327: 
                   5328: sub get_scantronformat_file {
                   5329:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5330:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5331:     my $gottab = 0;
                   5332:     my @lines;
                   5333:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5334:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5335:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5336:             if ($formatfile ne '-1') {
                   5337:                 @lines = split("\n",$formatfile,-1);
                   5338:                 $gottab = 1;
                   5339:             }
                   5340:         }
                   5341:     }
                   5342:     if (!$gottab) {
                   5343:         my $confname = $cdom.'-domainconfig';
                   5344:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5345:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5346:         if ($formatfile ne '-1') {
                   5347:             @lines = split("\n",$formatfile,-1);
                   5348:             $gottab = 1;
                   5349:         }
                   5350:     }
                   5351:     if (!$gottab) {
1.519     raeburn  5352:         my @domains = &Apache::lonnet::current_machine_domains();
                   5353:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5354:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5355:             @lines = <$fh>;
                   5356:             close($fh);
                   5357:         } else {
                   5358:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5359:             @lines = <$fh>;
                   5360:             close($fh);
                   5361:         }
1.518     raeburn  5362:     }
                   5363:     return @lines;
1.82      albertel 5364: }
                   5365: 
1.423     albertel 5366: =pod 
                   5367: 
                   5368: =item scantron_CODElist
                   5369: 
                   5370:   Returns html drop down of the saved CODE lists from current course,
                   5371:   generated from earlier printings.
                   5372: 
                   5373: =cut
1.422     foxr     5374: 
1.186     albertel 5375: sub scantron_CODElist {
1.257     albertel 5376:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5377:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5378:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5379:     my $namechoice='<option></option>';
1.225     albertel 5380:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5381: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5382: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5383: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5384:     }
                   5385:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5386:     return $namechoice;
                   5387: }
                   5388: 
1.423     albertel 5389: =pod 
                   5390: 
                   5391: =item scantron_CODEunique
                   5392: 
                   5393:   Returns the html for "Each CODE to be used once" radio.
                   5394: 
                   5395: =cut
1.422     foxr     5396: 
1.186     albertel 5397: sub scantron_CODEunique {
1.532     bisitz   5398:     my $result='<span class="LC_nobreak">
1.272     albertel 5399:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5400:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5401:                 </span>
1.532     bisitz   5402:                 <span class="LC_nobreak">
1.272     albertel 5403:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5404:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5405:                 </span>';
1.186     albertel 5406:     return $result;
                   5407: }
1.423     albertel 5408: 
                   5409: =pod 
                   5410: 
                   5411: =item scantron_selectphase
                   5412: 
1.659     raeburn  5413:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5414:   Allows for - starting a grading run.
1.424     albertel 5415:              - downloading existing scan data (original, corrected
1.423     albertel 5416:                                                 or skipped info)
                   5417: 
                   5418:              - uploading new scan data
                   5419: 
                   5420:  Arguments:
                   5421:   $r          - The Apache request object
                   5422:   $file2grade - name of the file that contain the scanned data to score
                   5423: 
                   5424: =cut
1.186     albertel 5425: 
1.75      albertel 5426: sub scantron_selectphase {
1.608     www      5427:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5428:     if (!$symb) {return '';}
1.582     raeburn  5429:     my $map_error;
                   5430:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5431:     if ($map_error) {
                   5432:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5433:         return;
                   5434:     }
1.324     albertel 5435:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5436:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5437:     my $format_selector=&scantron_scantab();
1.186     albertel 5438:     my $CODE_selector=&scantron_CODElist();
                   5439:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5440:     my $result;
1.422     foxr     5441: 
1.513     foxr     5442:     $ssi_error = 0;
                   5443: 
1.606     wenzelju 5444:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5445:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5446: 
                   5447: 	# Chunk of form to prompt for a scantron file upload.
                   5448: 
                   5449:         $r->print('
                   5450:     <br />
                   5451:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5452:        '.&Apache::loncommon::start_data_table_header_row().'
                   5453:             <th>
                   5454:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5455:             </th>
                   5456:        '.&Apache::loncommon::end_data_table_header_row().'
                   5457:        '.&Apache::loncommon::start_data_table_row().'
                   5458:             <td>
                   5459: ');
1.608     www      5460:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5461:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5462:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5463:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5464:     function checkUpload(formname) {
                   5465: 	if (formname.upfile.value == "") {
                   5466: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5467: 	    return false;
                   5468: 	}
                   5469: 	formname.submit();
                   5470:     }'));
                   5471:     $r->print('
                   5472:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5473:                 '.$default_form_data.'
                   5474:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5475:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5476:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5477:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5478:                 <br />
                   5479:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5480:               </form>
                   5481: ');
                   5482: 
                   5483:         $r->print('
                   5484:             </td>
                   5485:        '.&Apache::loncommon::end_data_table_row().'
                   5486:        '.&Apache::loncommon::end_data_table().'
                   5487: ');
                   5488:     }
                   5489: 
1.422     foxr     5490:     # Chunk of form to prompt for a file to grade and how:
                   5491: 
1.489     albertel 5492:     $result.= '
                   5493:     <br />
                   5494:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5495:     <input type="hidden" name="command" value="scantron_warning" />
                   5496:     '.$default_form_data.'
                   5497:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5498:        '.&Apache::loncommon::start_data_table_header_row().'
                   5499:             <th colspan="2">
1.492     albertel 5500:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5501:             </th>
                   5502:        '.&Apache::loncommon::end_data_table_header_row().'
                   5503:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5504:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5505:        '.&Apache::loncommon::end_data_table_row().'
                   5506:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5507:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5508:        '.&Apache::loncommon::end_data_table_row().'
                   5509:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5510:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5511:        '.&Apache::loncommon::end_data_table_row().'
                   5512:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5513:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5514:        '.&Apache::loncommon::end_data_table_row().'
                   5515:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5516:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5517:        '.&Apache::loncommon::end_data_table_row().'
                   5518:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5519: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5520:             <td>
1.492     albertel 5521: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5522:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5523:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5524: 	    </td>
1.489     albertel 5525:        '.&Apache::loncommon::end_data_table_row().'
                   5526:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5527:             <td colspan="2">
1.572     www      5528:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5529:             </td>
1.489     albertel 5530:        '.&Apache::loncommon::end_data_table_row().'
                   5531:     '.&Apache::loncommon::end_data_table().'
                   5532:     </form>
                   5533: ';
1.162     albertel 5534:    
                   5535:     $r->print($result);
                   5536: 
1.422     foxr     5537: 
                   5538: 
                   5539:     # Chunk of the form that prompts to view a scoring office file,
                   5540:     # corrected file, skipped records in a file.
                   5541: 
1.489     albertel 5542:     $r->print('
                   5543:    <br />
                   5544:    <form action="/adm/grades" name="scantron_download">
                   5545:      '.$default_form_data.'
                   5546:      <input type="hidden" name="command" value="scantron_download" />
                   5547:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5548:        '.&Apache::loncommon::start_data_table_header_row().'
                   5549:               <th>
1.492     albertel 5550:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5551:               </th>
                   5552:        '.&Apache::loncommon::end_data_table_header_row().'
                   5553:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5554:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5555:                 <br />
1.492     albertel 5556:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5557:        '.&Apache::loncommon::end_data_table_row().'
                   5558:      '.&Apache::loncommon::end_data_table().'
                   5559:    </form>
                   5560:    <br />
                   5561: ');
1.162     albertel 5562: 
1.457     banghart 5563:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5564: 
1.694     bisitz   5565:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5566:              $default_form_data."\n".
                   5567:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5568:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5569:              '<th colspan="2">
1.572     www      5570:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5571:              '</th>'."\n".
                   5572:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5573:               &Apache::loncommon::start_data_table_row()."\n".
                   5574:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5575:               '<td> '.$sequence_selector.' </td>'.
                   5576:               &Apache::loncommon::end_data_table_row()."\n".
                   5577:               &Apache::loncommon::start_data_table_row()."\n".
                   5578:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5579:               '<td> '.$file_selector.' </td>'."\n".
                   5580:               &Apache::loncommon::end_data_table_row()."\n".
                   5581:               &Apache::loncommon::start_data_table_row()."\n".
                   5582:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5583:               '<td> '.$format_selector.' </td>'."\n".
                   5584:               &Apache::loncommon::end_data_table_row()."\n".
                   5585:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5586:               '<td> '.&mt('Options').' </td>'."\n".
                   5587:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5588:               &Apache::loncommon::end_data_table_row()."\n".
                   5589:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5590:               '<td colspan="2">'."\n".
                   5591:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5592:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5593:               '</td>'."\n".
                   5594:               &Apache::loncommon::end_data_table_row()."\n".
                   5595:               &Apache::loncommon::end_data_table()."\n".
                   5596:               '</form><br />');
                   5597:     return;
1.75      albertel 5598: }
                   5599: 
1.423     albertel 5600: =pod
                   5601: 
                   5602: =item get_scantron_config
                   5603: 
1.711     bisitz   5604:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5605:    hash of configuration file fields.
                   5606: 
                   5607:  Arguments:
                   5608:     which - the name of the configuration to parse from the file.
                   5609: 
                   5610: 
                   5611:  Returns:
                   5612:             If the named configuration is not in the file, an empty
                   5613:             hash is returned.
                   5614:     a hash with the fields
                   5615:       name         - internal name for the this configuration setup
                   5616:       description  - text to display to operator that describes this config
                   5617:       CODElocation - if 0 or the string 'none'
                   5618:                           - no CODE exists for this config
                   5619:                      if -1 || the string 'letter'
                   5620:                           - a CODE exists for this config and is
                   5621:                             a string of letters
                   5622:                      Unsupported value (but planned for future support)
                   5623:                           if a positive integer
                   5624:                                - The CODE exists as the first n items from
                   5625:                                  the question section of the form
                   5626:                           if the string 'number'
                   5627:                                - The CODE exists for this config and is
                   5628:                                  a string of numbers
                   5629:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5630:                      the CODE starts
                   5631:       CODElength  - length of the CODE
1.573     bisitz   5632:       IDstart     - column where the student/employee ID starts
1.556     weissno  5633:       IDlength    - length of the student/employee ID info
1.423     albertel 5634:       Qstart      - column where the information from the bubbled
                   5635:                     'questions' start
                   5636:       Qlength     - number of columns comprising a single bubble line from
                   5637:                     the sheet. (usually either 1 or 10)
1.424     albertel 5638:       Qon         - either a single character representing the character used
1.423     albertel 5639:                     to signal a bubble was chosen in the positional setup, or
                   5640:                     the string 'letter' if the letter of the chosen bubble is
                   5641:                     in the final, or 'number' if a number representing the
                   5642:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5643:       Qoff        - the character used to represent that a bubble was
                   5644:                     left blank
1.423     albertel 5645:       PaperID     - if the scanning process generates a unique number for each
                   5646:                     sheet scanned the column that this ID number starts in
                   5647:       PaperIDlength - number of columns that comprise the unique ID number
                   5648:                       for the sheet of paper
1.424     albertel 5649:       FirstName   - column that the first name starts in
1.423     albertel 5650:       FirstNameLength - number of columns that the first name spans
                   5651:  
                   5652:       LastName    - column that the last name starts in
                   5653:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5654:       BubblesPerRow - number of bubbles available in each row used to 
                   5655:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5656: 
1.423     albertel 5657: =cut
1.422     foxr     5658: 
1.82      albertel 5659: sub get_scantron_config {
                   5660:     my ($which) = @_;
1.518     raeburn  5661:     my @lines = &get_scantronformat_file();
1.82      albertel 5662:     my %config;
1.157     albertel 5663:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5664:     foreach my $line (@lines) {
1.82      albertel 5665: 	my ($name,$descrip)=split(/:/,$line);
                   5666: 	if ($name ne $which ) { next; }
                   5667: 	chomp($line);
                   5668: 	my @config=split(/:/,$line);
                   5669: 	$config{'name'}=$config[0];
                   5670: 	$config{'description'}=$config[1];
                   5671: 	$config{'CODElocation'}=$config[2];
                   5672: 	$config{'CODEstart'}=$config[3];
                   5673: 	$config{'CODElength'}=$config[4];
                   5674: 	$config{'IDstart'}=$config[5];
                   5675: 	$config{'IDlength'}=$config[6];
                   5676: 	$config{'Qstart'}=$config[7];
1.497     foxr     5677:  	$config{'Qlength'}=$config[8];
1.82      albertel 5678: 	$config{'Qoff'}=$config[9];
                   5679: 	$config{'Qon'}=$config[10];
1.157     albertel 5680: 	$config{'PaperID'}=$config[11];
                   5681: 	$config{'PaperIDlength'}=$config[12];
                   5682: 	$config{'FirstName'}=$config[13];
                   5683: 	$config{'FirstNamelength'}=$config[14];
                   5684: 	$config{'LastName'}=$config[15];
                   5685: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5686:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5687: 	last;
                   5688:     }
                   5689:     return %config;
                   5690: }
                   5691: 
1.423     albertel 5692: =pod 
                   5693: 
                   5694: =item username_to_idmap
                   5695: 
1.556     weissno  5696:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5697:     student username:domain.
                   5698: 
                   5699:   Arguments:
                   5700: 
                   5701:     $classlist - reference to the class list hash. This is a hash
                   5702:                  keyed by student name:domain  whose elements are references
1.424     albertel 5703:                  to arrays containing various chunks of information
1.423     albertel 5704:                  about the student. (See loncoursedata for more info).
                   5705: 
                   5706:   Returns
                   5707:     %idmap - the constructed hash
                   5708: 
                   5709: =cut
                   5710: 
1.82      albertel 5711: sub username_to_idmap {
                   5712:     my ($classlist)= @_;
                   5713:     my %idmap;
                   5714:     foreach my $student (keys(%$classlist)) {
                   5715: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5716: 	    $student;
                   5717:     }
                   5718:     return %idmap;
                   5719: }
1.423     albertel 5720: 
                   5721: =pod
                   5722: 
1.424     albertel 5723: =item scantron_fixup_scanline
1.423     albertel 5724: 
                   5725:    Process a requested correction to a scanline.
                   5726: 
                   5727:   Arguments:
                   5728:     $scantron_config   - hash from &get_scantron_config()
                   5729:     $scan_data         - hash of correction information 
                   5730:                           (see &scantron_getfile())
                   5731:     $line              - existing scanline
                   5732:     $whichline         - line number of the passed in scanline
                   5733:     $field             - type of change to process 
                   5734:                          (either 
1.573     bisitz   5735:                           'ID'     -> correct the student/employee ID
1.423     albertel 5736:                           'CODE'   -> correct the CODE
                   5737:                           'answer' -> fixup the submitted answers)
                   5738:     
                   5739:    $args               - hash of additional info,
                   5740:                           - 'ID' 
                   5741:                                'newid' -> studentID to use in replacement
1.424     albertel 5742:                                           of existing one
1.423     albertel 5743:                           - 'CODE' 
                   5744:                                'CODE_ignore_dup' - set to true if duplicates
                   5745:                                                    should be ignored.
                   5746: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5747:                                         if the existing unfound code should
1.423     albertel 5748:                                         be used as is
                   5749:                           - 'answer'
                   5750:                                'response' - new answer or 'none' if blank
                   5751:                                'question' - the bubble line to change
1.503     raeburn  5752:                                'questionnum' - the question identifier,
                   5753:                                                may include subquestion. 
1.423     albertel 5754: 
                   5755:   Returns:
                   5756:     $line - the modified scanline
                   5757: 
                   5758:   Side effects: 
                   5759:     $scan_data - may be updated
                   5760: 
                   5761: =cut
                   5762: 
1.82      albertel 5763: 
1.157     albertel 5764: sub scantron_fixup_scanline {
                   5765:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5766:     if ($field eq 'ID') {
                   5767: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5768: 	    return ($line,1,'New value too large');
1.157     albertel 5769: 	}
                   5770: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5771: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5772: 				     $args->{'newid'});
                   5773: 	}
                   5774: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5775: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5776: 	if ($args->{'newid'}=~/^\s*$/) {
                   5777: 	    &scan_data($scan_data,"$whichline.user",
                   5778: 		       $args->{'username'}.':'.$args->{'domain'});
                   5779: 	}
1.186     albertel 5780:     } elsif ($field eq 'CODE') {
1.192     albertel 5781: 	if ($args->{'CODE_ignore_dup'}) {
                   5782: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5783: 	}
                   5784: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5785: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5786: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5787: 		return ($line,1,'New CODE value too large');
                   5788: 	    }
                   5789: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5790: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5791: 	    }
                   5792: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5793: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5794: 	}
1.157     albertel 5795:     } elsif ($field eq 'answer') {
1.497     foxr     5796: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5797: 	my $off=$scantron_config->{'Qoff'};
                   5798: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5799: 	my $answer=${off}x$length;
                   5800: 	if ($args->{'response'} eq 'none') {
                   5801: 	    &scan_data($scan_data,
1.503     raeburn  5802: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5803: 	} else {
                   5804: 	    if ($on eq 'letter') {
                   5805: 		my @alphabet=('A'..'Z');
                   5806: 		$answer=$alphabet[$args->{'response'}];
                   5807: 	    } elsif ($on eq 'number') {
                   5808: 		$answer=$args->{'response'}+1;
                   5809: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5810: 	    } else {
1.497     foxr     5811: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5812: 	    }
1.497     foxr     5813: 	    &scan_data($scan_data,
1.503     raeburn  5814: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5815: 	}
1.497     foxr     5816: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5817: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5818:     }
                   5819:     return $line;
                   5820: }
1.423     albertel 5821: 
                   5822: =pod
                   5823: 
                   5824: =item scan_data
                   5825: 
                   5826:     Edit or look up  an item in the scan_data hash.
                   5827: 
                   5828:   Arguments:
                   5829:     $scan_data  - The hash (see scantron_getfile)
                   5830:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5831:                   scantronfilename_key).
1.423     albertel 5832:     $data        - New value of the hash entry.
                   5833:     $delete      - If true, the entry is removed from the hash.
                   5834: 
                   5835:   Returns:
                   5836:     The new value of the hash table field (undefined if deleted).
                   5837: 
                   5838: =cut
                   5839: 
                   5840: 
1.157     albertel 5841: sub scan_data {
                   5842:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5843:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5844:     if (defined($value)) {
                   5845: 	$scan_data->{$filename.'_'.$key} = $value;
                   5846:     }
                   5847:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5848:     return $scan_data->{$filename.'_'.$key};
                   5849: }
1.423     albertel 5850: 
1.495     albertel 5851: # ----- These first few routines are general use routines.----
                   5852: 
                   5853: # Return the number of occurences of a pattern in a string.
                   5854: 
                   5855: sub occurence_count {
                   5856:     my ($string, $pattern) = @_;
                   5857: 
                   5858:     my @matches = ($string =~ /$pattern/g);
                   5859: 
                   5860:     return scalar(@matches);
                   5861: }
                   5862: 
                   5863: 
                   5864: # Take a string known to have digits and convert all the
                   5865: # digits into letters in the range J,A..I.
                   5866: 
                   5867: sub digits_to_letters {
                   5868:     my ($input) = @_;
                   5869: 
                   5870:     my @alphabet = ('J', 'A'..'I');
                   5871: 
                   5872:     my @input    = split(//, $input);
                   5873:     my $output ='';
                   5874:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5875: 	if ($input[$i] =~ /\d/) {
                   5876: 	    $output .= $alphabet[$input[$i]];
                   5877: 	} else {
                   5878: 	    $output .= $input[$i];
                   5879: 	}
                   5880:     }
                   5881:     return $output;
                   5882: }
                   5883: 
1.423     albertel 5884: =pod 
                   5885: 
                   5886: =item scantron_parse_scanline
                   5887: 
1.711     bisitz   5888:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5889: 
                   5890:  Arguments:
1.711     bisitz   5891:     line             - The text of the bubblesheet file line to process
1.423     albertel 5892:     whichline        - Line number
1.711     bisitz   5893:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5894:     scan_data        - Hash of extra information about the scanline
                   5895:                        (see scantron_getfile for more information)
                   5896:     just_header      - True if should not process question answers but only
                   5897:                        the stuff to the left of the answers.
1.691     raeburn  5898:     randomorder      - True if randomorder in use
                   5899:     randompick       - True if randompick in use
                   5900:     sequence         - Exam folder URL
                   5901:     master_seq       - Ref to array containing symbs in exam folder
                   5902:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5903:                        (corresponding values are resource objects)
                   5904:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5905:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5906:                        are refs to an array of resource objects, ordered
                   5907:                        according to order used for CODE, when randomorder
                   5908:                        and or randompick are in use.
                   5909:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5910:                        for current line to question number used for same question
                   5911:                         in "Master Sequence" (as seen by Course Coordinator).
                   5912:     startline        - Ref to hash where key is question number (0 is first)
                   5913:                        and value is number of first bubble line for current 
                   5914:                        student or code-based randompick and/or randomorder.
                   5915:     totalref         - Ref of scalar used to score total number of bubble
                   5916:                        lines needed for responses in a scan line (used when
                   5917:                        randompick in use. 
                   5918:     
1.423     albertel 5919:  Returns:
                   5920:    Hash containing the result of parsing the scanline
                   5921: 
                   5922:    Keys are all proceeded by the string 'scantron.'
                   5923: 
                   5924:        CODE    - the CODE in use for this scanline
                   5925:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5926:                  by the operator
                   5927:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5928:                             CODEs were selected, but the usage has been
                   5929:                             forced by the operator
1.556     weissno  5930:        ID  - student/employee ID
1.423     albertel 5931:        PaperID - if used, the ID number printed on the sheet when the 
                   5932:                  paper was scanned
                   5933:        FirstName - first name from the sheet
                   5934:        LastName  - last name from the sheet
                   5935: 
                   5936:      if just_header was not true these key may also exist
                   5937: 
1.447     foxr     5938:        missingerror - a list of bubble ranges that are considered to be answers
                   5939:                       to a single question that don't have any bubbles filled in.
                   5940:                       Of the form questionnumber:firstbubblenumber:count.
                   5941:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5942:                       to a single question that have more than one bubble filled in.
                   5943:                       Of the form questionnumber::firstbubblenumber:count
                   5944:    
                   5945:                 In the above, count is the number of bubble responses in the
                   5946:                 input line needed to represent the possible answers to the question.
                   5947:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5948:                 per line would have count = 2.
                   5949: 
1.423     albertel 5950:        maxquest     - the number of the last bubble line that was parsed
                   5951: 
                   5952:        (<number> starts at 1)
                   5953:        <number>.answer - zero or more letters representing the selected
                   5954:                          letters from the scanline for the bubble line 
                   5955:                          <number>.
                   5956:                          if blank there was either no bubble or there where
                   5957:                          multiple bubbles, (consult the keys missingerror and
                   5958:                          doubleerror if this is an error condition)
                   5959: 
                   5960: =cut
                   5961: 
1.82      albertel 5962: sub scantron_parse_scanline {
1.691     raeburn  5963:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5964:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5965:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5966: 
1.82      albertel 5967:     my %record;
1.691     raeburn  5968:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 5969:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5970: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5971: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5972: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5973: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5974: 	    $record{'scantron.CODE'}=substr($data,
                   5975: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5976: 					    $$scantron_config{'CODElength'});
1.191     albertel 5977: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5978: 		$record{'scantron.useCODE'}=1;
                   5979: 	    }
1.192     albertel 5980: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5981: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5982: 	    }
1.82      albertel 5983: 	} else {
                   5984: 	    #FIXME interpret first N questions
                   5985: 	}
                   5986:     }
1.83      albertel 5987:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5988: 				  $$scantron_config{'IDlength'});
1.157     albertel 5989:     $record{'scantron.PaperID'}=
                   5990: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5991: 	       $$scantron_config{'PaperIDlength'});
                   5992:     $record{'scantron.FirstName'}=
                   5993: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5994: 	       $$scantron_config{'FirstNamelength'});
                   5995:     $record{'scantron.LastName'}=
                   5996: 	substr($data,$$scantron_config{'LastName'}-1,
                   5997: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5998:     if ($just_header) { return \%record; }
1.194     albertel 5999: 
1.82      albertel 6000:     my @alphabet=('A'..'Z');
                   6001:     my $questnum=0;
1.447     foxr     6002:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6003: 
1.691     raeburn  6004:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6005:     if ($randompick || $randomorder) {
                   6006:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6007:                                          $master_seq,$symb_to_resource,
                   6008:                                          $partids_by_symb,$orderedforcode,
                   6009:                                          $respnumlookup,$startline);
                   6010:         if ($total) {
                   6011:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6012:         }
                   6013:         if (ref($totalref)) {
                   6014:             $$totalref = $total;
                   6015:         }
                   6016:     }
                   6017:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6018:     chomp($questions);		# Get rid of any trailing \n.
                   6019:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6020:     while (length($questions)) {
1.691     raeburn  6021:         my $answers_needed;
                   6022:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6023:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6024:         } else {
                   6025: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6026:         }
1.503     raeburn  6027:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6028:                              || 1;
                   6029:         $questnum++;
                   6030:         my $quest_id = $questnum;
                   6031:         my $currentquest = substr($questions,0,$answer_length);
                   6032:         $questions       = substr($questions,$answer_length);
                   6033:         if (length($currentquest) < $answer_length) { next; }
                   6034: 
1.691     raeburn  6035:         my $subdivided;
                   6036:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6037:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6038:         } else {
                   6039:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6040:         }
                   6041:         if ($subdivided =~ /,/) {
1.503     raeburn  6042:             my $subquestnum = 1;
                   6043:             my $subquestions = $currentquest;
1.691     raeburn  6044:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6045:             foreach my $subans (@subanswers_needed) {
                   6046:                 my $subans_length =
                   6047:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6048:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6049:                 $subquestions   = substr($subquestions,$subans_length);
                   6050:                 $quest_id = "$questnum.$subquestnum";
                   6051:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6052:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6053:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6054:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6055:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6056:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6057:                 } else {
                   6058:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6059:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6060:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6061:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6062:                 }
                   6063:                 $subquestnum ++;
                   6064:             }
                   6065:         } else {
                   6066:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6067:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6068:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6069:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6070:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6071:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6072:             } else {
                   6073:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6074:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6075:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6076:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6077:             }
                   6078:         }
                   6079:     }
                   6080:     $record{'scantron.maxquest'}=$questnum;
                   6081:     return \%record;
                   6082: }
1.447     foxr     6083: 
1.691     raeburn  6084: sub get_master_seq {
                   6085:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6086:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6087:                    (ref($symb_to_resource) eq 'HASH'));
                   6088:     my $resource_error;
                   6089:     foreach my $resource (@{$resources}) {
                   6090:         my $ressymb;
                   6091:         if (ref($resource)) {
                   6092:             $ressymb = $resource->symb();
                   6093:             push(@{$master_seq},$ressymb);
                   6094:             $symb_to_resource->{$ressymb} = $resource;
                   6095:         } else {
                   6096:             $resource_error = 1;
                   6097:             last;
                   6098:         }
                   6099:     }
                   6100:     return $resource_error;
                   6101: }
                   6102: 
                   6103: sub get_respnum_lookups {
                   6104:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6105:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6106:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6107:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6108:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6109:                    (ref($startline) eq 'HASH'));
                   6110:     my ($user,$scancode);
                   6111:     if ((exists($record->{'scantron.CODE'})) &&
                   6112:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6113:         $scancode = $record->{'scantron.CODE'};
                   6114:     } else {
                   6115:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6116:     }
                   6117:     my @mapresources =
                   6118:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6119:                      $orderedforcode);
                   6120:     my $total = 0;
                   6121:     my $count = 0;
                   6122:     foreach my $resource (@mapresources) {
                   6123:         my $id = $resource->id();
                   6124:         my $symb = $resource->symb();
                   6125:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6126:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6127:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6128:                 if ($respnum ne '') {
                   6129:                     $respnumlookup->{$count} = $respnum;
                   6130:                     $startline->{$count} = $total;
                   6131:                     $total += $bubble_lines_per_response{$respnum};
                   6132:                     $count ++;
                   6133:                 }
                   6134:             }
                   6135:         }
                   6136:     }
                   6137:     return $total;
                   6138: }
                   6139: 
1.503     raeburn  6140: sub scantron_validator_lettnum {
                   6141:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6142:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6143:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6144: 
                   6145:     # Qon 'letter' implies for each slot in currquest we have:
                   6146:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6147:     #    about anything else (esp. a value of Qoff) for missing
                   6148:     #    bubbles.
                   6149:     #
                   6150:     # Qon 'number' implies each slot gives a digit that indexes the
                   6151:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6152:     #    and * or ? for double bubbles on a single line.
                   6153:     #
1.447     foxr     6154: 
1.503     raeburn  6155:     my $matchon;
                   6156:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6157:         $matchon = '[A-Z]';
                   6158:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6159:         $matchon = '\d';
                   6160:     }
                   6161:     my $occurrences = 0;
1.691     raeburn  6162:     my $responsenum = $questnum-1;
                   6163:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6164:        $responsenum = $respnumlookup->{$questnum-1} 
                   6165:     }
                   6166:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6167:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6168:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6169:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6170:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6171:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6172:         my @singlelines = split('',$currquest);
                   6173:         foreach my $entry (@singlelines) {
                   6174:             $occurrences = &occurence_count($entry,$matchon);
                   6175:             if ($occurrences > 1) {
                   6176:                 last;
                   6177:             }
1.691     raeburn  6178:         }
1.503     raeburn  6179:     } else {
                   6180:         $occurrences = &occurence_count($currquest,$matchon); 
                   6181:     }
                   6182:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6183:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6184:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6185:             my $bubble = substr($currquest,$ans,1);
                   6186:             if ($bubble =~ /$matchon/ ) {
                   6187:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6188:                     if ($bubble == 0) {
                   6189:                         $bubble = 10; 
                   6190:                     }
                   6191:                     $record->{"scantron.$ansnum.answer"} = 
                   6192:                         $alphabet->[$bubble-1];
                   6193:                 } else {
                   6194:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6195:                 }
                   6196:             } else {
                   6197:                 $record->{"scantron.$ansnum.answer"}='';
                   6198:             }
                   6199:             $ansnum++;
                   6200:         }
                   6201:     } elsif (!defined($currquest)
                   6202:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6203:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6204:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6205:             $record->{"scantron.$ansnum.answer"}='';
                   6206:             $ansnum++;
                   6207:         }
                   6208:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6209:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6210:         }
                   6211:     } else {
                   6212:         if ($$scantron_config{'Qon'} eq 'number') {
                   6213:             $currquest = &digits_to_letters($currquest);            
                   6214:         }
                   6215:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6216:             my $bubble = substr($currquest,$ans,1);
                   6217:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6218:             $ansnum++;
                   6219:         }
                   6220:     }
                   6221:     return $ansnum;
                   6222: }
1.447     foxr     6223: 
1.503     raeburn  6224: sub scantron_validator_positional {
                   6225:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6226:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6227:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6228: 
1.503     raeburn  6229:     # Otherwise there's a positional notation;
                   6230:     # each bubble line requires Qlength items, and there are filled in
                   6231:     # bubbles for each case where there 'Qon' characters.
                   6232:     #
1.447     foxr     6233: 
1.503     raeburn  6234:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6235: 
1.503     raeburn  6236:     # If the split only gives us one element.. the full length of the
                   6237:     # answer string, no bubbles are filled in:
1.447     foxr     6238: 
1.507     raeburn  6239:     if ($answers_needed eq '') {
                   6240:         return;
                   6241:     }
                   6242: 
1.503     raeburn  6243:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6244:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6245:             $record->{"scantron.$ansnum.answer"}='';
                   6246:             $ansnum++;
                   6247:         }
                   6248:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6249:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6250:         }
                   6251:     } elsif (scalar(@array) == 2) {
                   6252:         my $location = length($array[0]);
                   6253:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6254:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6255:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6256:             if ($ans eq $line_num) {
                   6257:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6258:             } else {
                   6259:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6260:             }
                   6261:             $ansnum++;
                   6262:          }
                   6263:     } else {
                   6264:         #  If there's more than one instance of a bubble character
                   6265:         #  That's a double bubble; with positional notation we can
                   6266:         #  record all the bubbles filled in as well as the
                   6267:         #  fact this response consists of multiple bubbles.
                   6268:         #
1.691     raeburn  6269:         my $responsenum = $questnum-1;
                   6270:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6271:             $responsenum = $respnumlookup->{$questnum-1}
                   6272:         }
                   6273:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6274:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6275:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6276:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6277:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6278:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6279:             my $doubleerror = 0;
                   6280:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6281:                    (!$doubleerror)) {
                   6282:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6283:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6284:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6285:                if (length(@currarray) > 2) {
                   6286:                    $doubleerror = 1;
                   6287:                } 
                   6288:             }
                   6289:             if ($doubleerror) {
                   6290:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6291:             }
                   6292:         } else {
                   6293:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6294:         }
                   6295:         my $item = $ansnum;
                   6296:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6297:             $record->{"scantron.$item.answer"} = '';
                   6298:             $item ++;
                   6299:         }
1.447     foxr     6300: 
1.503     raeburn  6301:         my @ans=@array;
                   6302:         my $i=0;
                   6303:         my $increment = 0;
                   6304:         while ($#ans) {
                   6305:             $i+=length($ans[0]) + $increment;
                   6306:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6307:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6308:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6309:             shift(@ans);
                   6310:             $increment = 1;
                   6311:         }
                   6312:         $ansnum += $answers_needed;
1.82      albertel 6313:     }
1.503     raeburn  6314:     return $ansnum;
1.82      albertel 6315: }
                   6316: 
1.423     albertel 6317: =pod
                   6318: 
                   6319: =item scantron_add_delay
                   6320: 
                   6321:    Adds an error message that occurred during the grading phase to a
                   6322:    queue of messages to be shown after grading pass is complete
                   6323: 
                   6324:  Arguments:
1.424     albertel 6325:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6326:    $scanline    - the scanline that caused the error
                   6327:    $errormesage - the error message
                   6328:    $errorcode   - a numeric code for the error
                   6329: 
                   6330:  Side Effects:
1.424     albertel 6331:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6332: 
                   6333: =cut
                   6334: 
1.82      albertel 6335: sub scantron_add_delay {
1.140     albertel 6336:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6337:     push(@$delayqueue,
                   6338: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6339: 	  'ecode' => $errorcode }
                   6340: 	 );
1.82      albertel 6341: }
                   6342: 
1.423     albertel 6343: =pod
                   6344: 
                   6345: =item scantron_find_student
                   6346: 
1.424     albertel 6347:    Finds the username for the current scanline
                   6348: 
                   6349:   Arguments:
                   6350:    $scantron_record - hash result from scantron_parse_scanline
                   6351:    $scan_data       - hash of correction information 
                   6352:                       (see &scantron_getfile() form more information)
                   6353:    $idmap           - hash from &username_to_idmap()
                   6354:    $line            - number of current scanline
                   6355:  
                   6356:   Returns:
                   6357:    Either 'username:domain' or undef if unknown
                   6358: 
1.423     albertel 6359: =cut
                   6360: 
1.82      albertel 6361: sub scantron_find_student {
1.157     albertel 6362:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6363:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6364:     if ($scanID =~ /^\s*$/) {
                   6365:  	return &scan_data($scan_data,"$line.user");
                   6366:     }
1.83      albertel 6367:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6368:  	if (lc($id) eq lc($scanID)) {
                   6369:  	    return $$idmap{$id};
                   6370:  	}
1.83      albertel 6371:     }
                   6372:     return undef;
                   6373: }
                   6374: 
1.423     albertel 6375: =pod
                   6376: 
                   6377: =item scantron_filter
                   6378: 
1.424     albertel 6379:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6380:    hidden resources was selected
                   6381: 
1.423     albertel 6382: =cut
                   6383: 
1.83      albertel 6384: sub scantron_filter {
                   6385:     my ($curres)=@_;
1.331     albertel 6386: 
                   6387:     if (ref($curres) && $curres->is_problem()) {
                   6388: 	# if the user has asked to not have either hidden
                   6389: 	# or 'randomout' controlled resources to be graded
                   6390: 	# don't include them
                   6391: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6392: 	    && $curres->randomout) {
                   6393: 	    return 0;
                   6394: 	}
1.83      albertel 6395: 	return 1;
                   6396:     }
                   6397:     return 0;
1.82      albertel 6398: }
                   6399: 
1.423     albertel 6400: =pod
                   6401: 
                   6402: =item scantron_process_corrections
                   6403: 
1.424     albertel 6404:    Gets correction information out of submitted form data and corrects
                   6405:    the scanline
                   6406: 
1.423     albertel 6407: =cut
                   6408: 
1.157     albertel 6409: sub scantron_process_corrections {
                   6410:     my ($r) = @_;
1.257     albertel 6411:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6412:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6413:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6414:     my $which=$env{'form.scantron_line'};
1.200     albertel 6415:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6416:     my ($skip,$err,$errmsg);
1.257     albertel 6417:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6418: 	$skip=1;
1.257     albertel 6419:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6420: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6421: 	    $env{'form.scantron_domain'};
1.157     albertel 6422: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6423: 	($line,$err,$errmsg)=
                   6424: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6425: 				     'ID',{'newid'=>$newid,
1.257     albertel 6426: 				    'username'=>$env{'form.scantron_username'},
                   6427: 				    'domain'=>$env{'form.scantron_domain'}});
                   6428:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6429: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6430: 	my $newCODE;
1.192     albertel 6431: 	my %args;
1.190     albertel 6432: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6433: 	    $newCODE='use_unfound';
1.190     albertel 6434: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6435: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6436: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6437: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6438: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6439: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6440: 	}
1.257     albertel 6441: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6442: 	    $args{'CODE_ignore_dup'}=1;
                   6443: 	}
                   6444: 	$args{'CODE'}=$newCODE;
1.186     albertel 6445: 	($line,$err,$errmsg)=
                   6446: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6447: 				     'CODE',\%args);
1.257     albertel 6448:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6449: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6450: 	    ($line,$err,$errmsg)=
                   6451: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6452: 					 $which,'answer',
                   6453: 					 { 'question'=>$question,
1.503     raeburn  6454: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6455:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6456: 	    if ($err) { last; }
                   6457: 	}
                   6458:     }
                   6459:     if ($err) {
1.703     bisitz   6460:         $r->print(
                   6461:             '<p class="LC_error">'
                   6462:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6463:                 $errmsg)
1.704     raeburn  6464:            .'</p>');
1.157     albertel 6465:     } else {
1.200     albertel 6466: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6467: 	&scantron_putfile($scanlines,$scan_data);
                   6468:     }
                   6469: }
                   6470: 
1.423     albertel 6471: =pod
                   6472: 
                   6473: =item reset_skipping_status
                   6474: 
1.424     albertel 6475:    Forgets the current set of remember skipped scanlines (and thus
                   6476:    reverts back to considering all lines in the
                   6477:    scantron_skipped_<filename> file)
                   6478: 
1.423     albertel 6479: =cut
                   6480: 
1.200     albertel 6481: sub reset_skipping_status {
                   6482:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6483:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6484:     &scantron_putfile(undef,$scan_data);
                   6485: }
                   6486: 
1.423     albertel 6487: =pod
                   6488: 
                   6489: =item start_skipping
                   6490: 
1.424     albertel 6491:    Marks a scanline to be skipped. 
                   6492: 
1.423     albertel 6493: =cut
                   6494: 
1.376     albertel 6495: sub start_skipping {
1.200     albertel 6496:     my ($scan_data,$i)=@_;
                   6497:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6498:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6499: 	$remembered{$i}=2;
                   6500:     } else {
                   6501: 	$remembered{$i}=1;
                   6502:     }
1.200     albertel 6503:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6504: }
                   6505: 
1.423     albertel 6506: =pod
                   6507: 
                   6508: =item should_be_skipped
                   6509: 
1.424     albertel 6510:    Checks whether a scanline should be skipped.
                   6511: 
1.423     albertel 6512: =cut
                   6513: 
1.200     albertel 6514: sub should_be_skipped {
1.376     albertel 6515:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6516:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6517: 	# not redoing old skips
1.376     albertel 6518: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6519: 	return 0;
                   6520:     }
                   6521:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6522: 
                   6523:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6524: 	return 0;
                   6525:     }
1.200     albertel 6526:     return 1;
                   6527: }
                   6528: 
1.423     albertel 6529: =pod
                   6530: 
                   6531: =item remember_current_skipped
                   6532: 
1.424     albertel 6533:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6534:    file and remembers them into scan_data for later use.
                   6535: 
1.423     albertel 6536: =cut
                   6537: 
1.200     albertel 6538: sub remember_current_skipped {
                   6539:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6540:     my %to_remember;
                   6541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6542: 	if ($scanlines->{'skipped'}[$i]) {
                   6543: 	    $to_remember{$i}=1;
                   6544: 	}
                   6545:     }
1.376     albertel 6546: 
1.200     albertel 6547:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6548:     &scantron_putfile(undef,$scan_data);
                   6549: }
                   6550: 
1.423     albertel 6551: =pod
                   6552: 
                   6553: =item check_for_error
                   6554: 
1.424     albertel 6555:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6556:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6557:     something went wrong.
                   6558: 
1.423     albertel 6559: =cut
                   6560: 
1.200     albertel 6561: sub check_for_error {
                   6562:     my ($r,$result)=@_;
                   6563:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6564: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6565:     }
                   6566: }
1.157     albertel 6567: 
1.423     albertel 6568: =pod
                   6569: 
                   6570: =item scantron_warning_screen
                   6571: 
1.424     albertel 6572:    Interstitial screen to make sure the operator has selected the
                   6573:    correct options before we start the validation phase.
                   6574: 
1.423     albertel 6575: =cut
                   6576: 
1.203     albertel 6577: sub scantron_warning_screen {
1.650     raeburn  6578:     my ($button_text,$symb)=@_;
1.257     albertel 6579:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6580:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6581:     my $CODElist;
1.284     albertel 6582:     if ($scantron_config{'CODElocation'} &&
                   6583: 	$scantron_config{'CODEstart'} &&
                   6584: 	$scantron_config{'CODElength'}) {
                   6585: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6586: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6587: 	$CODElist=
1.492     albertel 6588: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6589: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6590:     }
1.663     raeburn  6591:     my $lastbubblepoints;
                   6592:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6593:         $lastbubblepoints =
                   6594:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6595:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6596:     }
1.492     albertel 6597:     return ('
1.203     albertel 6598: <p>
1.492     albertel 6599: <span class="LC_warning">
1.705     raeburn  6600: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6601: </p>
                   6602: <table>
1.492     albertel 6603: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6604: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6605: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6606: </table>
1.680     raeburn  6607: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6608: '.&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 6609: 
                   6610: <br />
1.492     albertel 6611: ');
1.203     albertel 6612: }
                   6613: 
1.423     albertel 6614: =pod
                   6615: 
                   6616: =item scantron_do_warning
                   6617: 
1.424     albertel 6618:    Check if the operator has picked something for all required
                   6619:    fields. Error out if something is missing.
                   6620: 
1.423     albertel 6621: =cut
                   6622: 
1.203     albertel 6623: sub scantron_do_warning {
1.608     www      6624:     my ($r,$symb)=@_;
1.203     albertel 6625:     if (!$symb) {return '';}
1.324     albertel 6626:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6627:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6628:     if ( $env{'form.selectpage'} eq '' ||
                   6629: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6630: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6631: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6632: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6633: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6634: 	} 
1.257     albertel 6635: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6636: 	    $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 6637: 	} 
1.257     albertel 6638: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6639: 	    $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 6640: 	} 
                   6641:     } else {
1.650     raeburn  6642: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6643:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6644: 	$r->print('
1.663     raeburn  6645: '.$warning.$bubbledbyhand.'
1.492     albertel 6646: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6647: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6648: ');
1.237     albertel 6649:     }
1.614     www      6650:     $r->print("</form><br />");
1.203     albertel 6651:     return '';
                   6652: }
                   6653: 
1.423     albertel 6654: =pod
                   6655: 
                   6656: =item scantron_form_start
                   6657: 
1.424     albertel 6658:     html hidden input for remembering all selected grading options
                   6659: 
1.423     albertel 6660: =cut
                   6661: 
1.203     albertel 6662: sub scantron_form_start {
                   6663:     my ($max_bubble)=@_;
                   6664:     my $result= <<SCANTRONFORM;
                   6665: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6666:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6667:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6668:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6669:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6670:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6671:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6672:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6673:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6674:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6675: SCANTRONFORM
1.447     foxr     6676: 
                   6677:   my $line = 0;
                   6678:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6679:        my $chunk =
                   6680: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6681:        $chunk .=
                   6682: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6683:        $chunk .= 
                   6684:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6685:        $chunk .=
                   6686:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6687:        $chunk .=
                   6688:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6689:        $result .= $chunk;
                   6690:        $line++;
1.691     raeburn  6691:     }
1.203     albertel 6692:     return $result;
                   6693: }
                   6694: 
1.423     albertel 6695: =pod
                   6696: 
                   6697: =item scantron_validate_file
                   6698: 
1.659     raeburn  6699:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6700: 
                   6701:     Also processes any necessary information resets that need to
                   6702:     occur before validation begins (ignore previous corrections,
                   6703:     restarting the skipped records processing)
                   6704: 
1.423     albertel 6705: =cut
                   6706: 
1.157     albertel 6707: sub scantron_validate_file {
1.608     www      6708:     my ($r,$symb) = @_;
1.157     albertel 6709:     if (!$symb) {return '';}
1.324     albertel 6710:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6711:     
1.703     bisitz   6712:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6713:     # them when doing the corrections reset
1.257     albertel 6714:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6715: 	&reset_skipping_status();
                   6716:     }
1.257     albertel 6717:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6718: 	&remember_current_skipped();
1.257     albertel 6719: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6720:     }
                   6721: 
1.257     albertel 6722:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6723: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6724: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6725: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6726: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6727:     }
1.200     albertel 6728: 
1.257     albertel 6729:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6730: 	&scantron_process_corrections($r);
                   6731:     }
1.503     raeburn  6732:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6733:     #get the student pick code ready
                   6734:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6735:     my $nav_error;
1.649     raeburn  6736:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6737:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6738:     if ($nav_error) {
                   6739:         $r->print(&navmap_errormsg());
                   6740:         return '';
                   6741:     }
1.203     albertel 6742:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6743:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6744:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6745:     }
1.157     albertel 6746:     $r->print($result);
                   6747:     
1.334     albertel 6748:     my @validate_phases=( 'sequence',
                   6749: 			  'ID',
1.157     albertel 6750: 			  'CODE',
                   6751: 			  'doublebubble',
                   6752: 			  'missingbubbles');
1.257     albertel 6753:     if (!$env{'form.validatepass'}) {
                   6754: 	$env{'form.validatepass'} = 0;
1.157     albertel 6755:     }
1.257     albertel 6756:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6757: 
1.448     foxr     6758: 
1.157     albertel 6759:     my $stop=0;
                   6760:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6761: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6762: 	$r->rflush();
1.691     raeburn  6763:      
1.157     albertel 6764: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6765: 	{
                   6766: 	    no strict 'refs';
                   6767: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6768: 	}
                   6769:     }
                   6770:     if (!$stop) {
1.650     raeburn  6771: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6772: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6773:                   $warning.
                   6774:                   &mt('Perform verification for each student after storage of submissions?').
                   6775:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6776:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6777:                   ('&nbsp;'x3).'<label>'.
                   6778:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6779:                   '</label></span><br />'.
                   6780:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6781:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6782:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6783:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6784:     } else {
                   6785: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6786: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6787:     }
                   6788:     if ($stop) {
1.334     albertel 6789: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6790: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6791: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6792: 
1.650     raeburn  6793: 	    $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 6794: 	} else {
1.503     raeburn  6795:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6796: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6797:             } else {
1.539     riegler  6798:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6799:             }
1.492     albertel 6800: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6801: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6802: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6803: 	}
1.157     albertel 6804:     }
1.614     www      6805:     $r->print(" </form><br />");
1.157     albertel 6806:     return '';
                   6807: }
                   6808: 
1.423     albertel 6809: 
                   6810: =pod
                   6811: 
                   6812: =item scantron_remove_file
                   6813: 
1.659     raeburn  6814:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6815:    scantron_original_<filename> is never removed
                   6816: 
                   6817: 
1.423     albertel 6818: =cut
                   6819: 
1.200     albertel 6820: sub scantron_remove_file {
1.192     albertel 6821:     my ($which)=@_;
1.257     albertel 6822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6824:     my $file='scantron_';
1.200     albertel 6825:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6826: 	$file.=$which.'_';
1.192     albertel 6827:     } else {
                   6828: 	return 'refused';
                   6829:     }
1.257     albertel 6830:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6831:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6832: }
                   6833: 
1.423     albertel 6834: 
                   6835: =pod
                   6836: 
                   6837: =item scantron_remove_scan_data
                   6838: 
1.659     raeburn  6839:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6840:    data file.  (In the case that both the are doing skipped records we need
                   6841:    to remember the old skipped lines for the time being so that element
                   6842:    persists for a while.)
                   6843: 
1.423     albertel 6844: =cut
                   6845: 
1.200     albertel 6846: sub scantron_remove_scan_data {
1.257     albertel 6847:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6848:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6849:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6850:     my @todelete;
1.257     albertel 6851:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6852:     foreach my $key (@keys) {
                   6853: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6854: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6855: 		$key=~/remember_skipping/) {
                   6856: 		next;
                   6857: 	    }
1.192     albertel 6858: 	    push(@todelete,$key);
                   6859: 	}
                   6860:     }
1.200     albertel 6861:     my $result;
1.192     albertel 6862:     if (@todelete) {
1.491     albertel 6863: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6864: 				       \@todelete,$cdom,$cname);
                   6865:     } else {
                   6866: 	$result = 'ok';
1.192     albertel 6867:     }
                   6868:     return $result;
                   6869: }
                   6870: 
1.423     albertel 6871: 
                   6872: =pod
                   6873: 
                   6874: =item scantron_getfile
                   6875: 
1.659     raeburn  6876:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6877:     the scan_data hash
                   6878:   
                   6879:   Arguments:
                   6880:     None
                   6881: 
                   6882:   Returns:
                   6883:     2 hash references
                   6884: 
                   6885:      - first one has 
                   6886:          orig      -
                   6887:          corrected -
                   6888:          skipped   -  each of which points to an array ref of the specified
                   6889:                       file broken up into individual lines
                   6890:          count     - number of scanlines
                   6891:  
                   6892:      - second is the scan_data hash possible keys are
1.425     albertel 6893:        ($number refers to scanline numbered $number and thus the key affects
                   6894:         only that scanline
                   6895:         $bubline refers to the specific bubble line element and the aspects
                   6896:         refers to that specific bubble line element)
                   6897: 
                   6898:        $number.user - username:domain to use
                   6899:        $number.CODE_ignore_dup 
                   6900:                     - ignore the duplicate CODE error 
                   6901:        $number.useCODE
                   6902:                     - use the CODE in the scanline as is
                   6903:        $number.no_bubble.$bubline
                   6904:                     - it is valid that there is no bubbled in bubble
                   6905:                       at $number $bubline
                   6906:        remember_skipping
                   6907:                     - a frozen hash containing keys of $number and values
                   6908:                       of either 
                   6909:                         1 - we are on a 'do skipped records pass' and plan
                   6910:                             on processing this line
                   6911:                         2 - we are on a 'do skipped records pass' and this
                   6912:                             scanline has been marked to skip yet again
1.424     albertel 6913: 
1.423     albertel 6914: =cut
                   6915: 
1.157     albertel 6916: sub scantron_getfile {
1.200     albertel 6917:     #FIXME really would prefer a scantron directory
1.257     albertel 6918:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6920:     my $lines;
                   6921:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6922: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6923:     my %scanlines;
                   6924:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6925:     my $temp=$scanlines{'orig'};
                   6926:     $scanlines{'count'}=$#$temp;
                   6927: 
                   6928:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6929: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6930:     if ($lines eq '-1') {
                   6931: 	$scanlines{'corrected'}=[];
                   6932:     } else {
                   6933: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6934:     }
                   6935:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6936: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6937:     if ($lines eq '-1') {
                   6938: 	$scanlines{'skipped'}=[];
                   6939:     } else {
                   6940: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6941:     }
1.175     albertel 6942:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6943:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6944:     my %scan_data = @tmp;
                   6945:     return (\%scanlines,\%scan_data);
                   6946: }
                   6947: 
1.423     albertel 6948: =pod
                   6949: 
                   6950: =item lonnet_putfile
                   6951: 
1.424     albertel 6952:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6953: 
                   6954:  Arguments:
                   6955:    $contents - data to store
                   6956:    $filename - filename to store $contents into
                   6957: 
                   6958:  Returns:
                   6959:    result value from &Apache::lonnet::finishuserfileupload
                   6960: 
1.423     albertel 6961: =cut
                   6962: 
1.157     albertel 6963: sub lonnet_putfile {
                   6964:     my ($contents,$filename)=@_;
1.257     albertel 6965:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6966:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6967:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6968:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6969: 
                   6970: }
                   6971: 
1.423     albertel 6972: =pod
                   6973: 
                   6974: =item scantron_putfile
                   6975: 
1.659     raeburn  6976:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6977:     scan_data hash. (Does not modify the original version only the
                   6978:     corrected and skipped versions.
                   6979: 
                   6980:  Arguments:
                   6981:     $scanlines - hash ref that looks like the first return value from
                   6982:                  &scantron_getfile()
                   6983:     $scan_data - hash ref that looks like the second return value from
                   6984:                  &scantron_getfile()
                   6985: 
1.423     albertel 6986: =cut
                   6987: 
1.157     albertel 6988: sub scantron_putfile {
                   6989:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6990:     #FIXME really would prefer a scantron directory
1.257     albertel 6991:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6992:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6993:     if ($scanlines) {
                   6994: 	my $prefix='scantron_';
1.157     albertel 6995: # no need to update orig, shouldn't change
                   6996: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6997: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6998: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6999: 			$prefix.'corrected_'.
1.257     albertel 7000: 			$env{'form.scantron_selectfile'});
1.200     albertel 7001: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7002: 			$prefix.'skipped_'.
1.257     albertel 7003: 			$env{'form.scantron_selectfile'});
1.200     albertel 7004:     }
1.175     albertel 7005:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7006: }
                   7007: 
1.423     albertel 7008: =pod
                   7009: 
                   7010: =item scantron_get_line
                   7011: 
1.424     albertel 7012:    Returns the correct version of the scanline
                   7013: 
                   7014:  Arguments:
                   7015:     $scanlines - hash ref that looks like the first return value from
                   7016:                  &scantron_getfile()
                   7017:     $scan_data - hash ref that looks like the second return value from
                   7018:                  &scantron_getfile()
                   7019:     $i         - number of the requested line (starts at 0)
                   7020: 
                   7021:  Returns:
                   7022:    A scanline, (either the original or the corrected one if it
                   7023:    exists), or undef if the requested scanline should be
                   7024:    skipped. (Either because it's an skipped scanline, or it's an
                   7025:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7026:    pass.
                   7027: 
1.423     albertel 7028: =cut
                   7029: 
1.157     albertel 7030: sub scantron_get_line {
1.200     albertel 7031:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7032:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7033:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7034:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7035:     return $scanlines->{'orig'}[$i]; 
                   7036: }
                   7037: 
1.423     albertel 7038: =pod
                   7039: 
                   7040: =item scantron_todo_count
                   7041: 
1.424     albertel 7042:     Counts the number of scanlines that need processing.
                   7043: 
                   7044:  Arguments:
                   7045:     $scanlines - hash ref that looks like the first return value from
                   7046:                  &scantron_getfile()
                   7047:     $scan_data - hash ref that looks like the second return value from
                   7048:                  &scantron_getfile()
                   7049: 
                   7050:  Returns:
                   7051:     $count - number of scanlines to process
                   7052: 
1.423     albertel 7053: =cut
                   7054: 
1.200     albertel 7055: sub get_todo_count {
                   7056:     my ($scanlines,$scan_data)=@_;
                   7057:     my $count=0;
                   7058:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7059: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7060: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7061: 	$count++;
                   7062:     }
                   7063:     return $count;
                   7064: }
                   7065: 
1.423     albertel 7066: =pod
                   7067: 
                   7068: =item scantron_put_line
                   7069: 
1.659     raeburn  7070:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7071:     data file.
                   7072: 
                   7073:  Arguments:
                   7074:     $scanlines - hash ref that looks like the first return value from
                   7075:                  &scantron_getfile()
                   7076:     $scan_data - hash ref that looks like the second return value from
                   7077:                  &scantron_getfile()
                   7078:     $i         - line number to update
                   7079:     $newline   - contents of the updated scanline
                   7080:     $skip      - if true make the line for skipping and update the
                   7081:                  'skipped' file
                   7082: 
1.423     albertel 7083: =cut
                   7084: 
1.157     albertel 7085: sub scantron_put_line {
1.200     albertel 7086:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7087:     if ($skip) {
                   7088: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7089: 	&start_skipping($scan_data,$i);
1.157     albertel 7090: 	return;
                   7091:     }
                   7092:     $scanlines->{'corrected'}[$i]=$newline;
                   7093: }
                   7094: 
1.423     albertel 7095: =pod
                   7096: 
                   7097: =item scantron_clear_skip
                   7098: 
1.424     albertel 7099:    Remove a line from the 'skipped' file
                   7100: 
                   7101:  Arguments:
                   7102:     $scanlines - hash ref that looks like the first return value from
                   7103:                  &scantron_getfile()
                   7104:     $scan_data - hash ref that looks like the second return value from
                   7105:                  &scantron_getfile()
                   7106:     $i         - line number to update
                   7107: 
1.423     albertel 7108: =cut
                   7109: 
1.376     albertel 7110: sub scantron_clear_skip {
                   7111:     my ($scanlines,$scan_data,$i)=@_;
                   7112:     if (exists($scanlines->{'skipped'}[$i])) {
                   7113: 	undef($scanlines->{'skipped'}[$i]);
                   7114: 	return 1;
                   7115:     }
                   7116:     return 0;
                   7117: }
                   7118: 
1.423     albertel 7119: =pod
                   7120: 
                   7121: =item scantron_filter_not_exam
                   7122: 
1.424     albertel 7123:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7124:    filter out resources that are not marked as 'exam' mode
                   7125: 
1.423     albertel 7126: =cut
                   7127: 
1.334     albertel 7128: sub scantron_filter_not_exam {
                   7129:     my ($curres)=@_;
                   7130:     
                   7131:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7132: 	# if the user has asked to not have either hidden
                   7133: 	# or 'randomout' controlled resources to be graded
                   7134: 	# don't include them
                   7135: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7136: 	    && $curres->randomout) {
                   7137: 	    return 0;
                   7138: 	}
                   7139: 	return 1;
                   7140:     }
                   7141:     return 0;
                   7142: }
                   7143: 
1.423     albertel 7144: =pod
                   7145: 
                   7146: =item scantron_validate_sequence
                   7147: 
1.424     albertel 7148:     Validates the selected sequence, checking for resource that are
                   7149:     not set to exam mode.
                   7150: 
1.423     albertel 7151: =cut
                   7152: 
1.334     albertel 7153: sub scantron_validate_sequence {
                   7154:     my ($r,$currentphase) = @_;
                   7155: 
                   7156:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7157:     unless (ref($navmap)) {
                   7158:         $r->print(&navmap_errormsg());
                   7159:         return (1,$currentphase);
                   7160:     }
1.334     albertel 7161:     my (undef,undef,$sequence)=
                   7162: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7163: 
                   7164:     my $map=$navmap->getResourceByUrl($sequence);
                   7165: 
                   7166:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7167:                                     value="ignore" />');
                   7168:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7169: 	my @resources=
                   7170: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7171: 	if (@resources) {
1.675     bisitz   7172: 	    $r->print(
                   7173:                 '<p class="LC_warning">'
                   7174:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7175:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7176:                    .' work correctly.')
                   7177:                .'</p>'
                   7178:             );
1.334     albertel 7179: 	    return (1,$currentphase);
                   7180: 	}
                   7181:     }
                   7182: 
                   7183:     return (0,$currentphase+1);
                   7184: }
                   7185: 
1.423     albertel 7186: 
                   7187: 
1.157     albertel 7188: sub scantron_validate_ID {
                   7189:     my ($r,$currentphase) = @_;
                   7190:     
                   7191:     #get student info
                   7192:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7193:     my %idmap=&username_to_idmap($classlist);
                   7194: 
                   7195:     #get scantron line setup
1.257     albertel 7196:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7197:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7198: 
                   7199:     my $nav_error;
1.649     raeburn  7200:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7201:     if ($nav_error) {
                   7202:         $r->print(&navmap_errormsg());
                   7203:         return(1,$currentphase);
                   7204:     }
1.157     albertel 7205: 
                   7206:     my %found=('ids'=>{},'usernames'=>{});
                   7207:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7208: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7209: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7210: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7211: 						 $scan_data);
                   7212: 	my $id=$$scan_record{'scantron.ID'};
                   7213: 	my $found;
                   7214: 	foreach my $checkid (keys(%idmap)) {
                   7215: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7216: 	}
                   7217: 	if ($found) {
                   7218: 	    my $username=$idmap{$found};
                   7219: 	    if ($found{'ids'}{$found}) {
                   7220: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7221: 					 $line,'duplicateID',$found);
1.194     albertel 7222: 		return(1,$currentphase);
1.157     albertel 7223: 	    } elsif ($found{'usernames'}{$username}) {
                   7224: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7225: 					 $line,'duplicateID',$username);
1.194     albertel 7226: 		return(1,$currentphase);
1.157     albertel 7227: 	    }
1.186     albertel 7228: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7229: 	    $found{'ids'}{$found}++;
                   7230: 	    $found{'usernames'}{$username}++;
                   7231: 	} else {
                   7232: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7233: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7234: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7235: 		    &scantron_get_correction($r,$i,$scan_record,
                   7236: 					     \%scantron_config,
                   7237: 					     $line,'duplicateID',$username);
1.194     albertel 7238: 		    return(1,$currentphase);
1.157     albertel 7239: 		} elsif (!defined($username)) {
                   7240: 		    &scantron_get_correction($r,$i,$scan_record,
                   7241: 					     \%scantron_config,
                   7242: 					     $line,'incorrectID');
1.194     albertel 7243: 		    return(1,$currentphase);
1.157     albertel 7244: 		}
                   7245: 		$found{'usernames'}{$username}++;
                   7246: 	    } else {
                   7247: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7248: 					 $line,'incorrectID');
1.194     albertel 7249: 		return(1,$currentphase);
1.157     albertel 7250: 	    }
                   7251: 	}
                   7252:     }
                   7253: 
                   7254:     return (0,$currentphase+1);
                   7255: }
                   7256: 
1.423     albertel 7257: 
1.157     albertel 7258: sub scantron_get_correction {
1.691     raeburn  7259:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7260:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7261: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7262: #to show both the current line and the previous one and allow skipping
                   7263: #the previous one or the current one
                   7264: 
1.333     albertel 7265:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7266:         $r->print(
                   7267:             '<p class="LC_warning">'
                   7268:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7269:                 "<b>$error</b>",
                   7270:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7271:            ."</p> \n");
1.157     albertel 7272:     } else {
1.658     bisitz   7273:         $r->print(
                   7274:             '<p class="LC_warning">'
                   7275:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7276:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7277:            ."</p> \n");
                   7278:     }
                   7279:     my $message =
                   7280:         '<p>'
                   7281:        .&mt('The ID on the form is [_1]',
                   7282:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7283:        .'<br />'
1.665     raeburn  7284:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7285:             $$scan_record{'scantron.LastName'},
                   7286:             $$scan_record{'scantron.FirstName'})
                   7287:        .'</p>';
1.242     albertel 7288: 
1.157     albertel 7289:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7290:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7291:                            # Array populated for doublebubble or
                   7292:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7293:                            # to validate radio button checking   
                   7294: 
1.157     albertel 7295:     if ($error =~ /ID$/) {
1.186     albertel 7296: 	if ($error eq 'incorrectID') {
1.658     bisitz   7297:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7298: 		      "</p>\n");
1.157     albertel 7299: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7300:             $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 7301: 	}
1.242     albertel 7302: 	$r->print($message);
1.492     albertel 7303: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7304: 	$r->print("\n<ul><li> ");
                   7305: 	#FIXME it would be nice if this sent back the user ID and
                   7306: 	#could do partial userID matches
                   7307: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7308: 				       'scantron_username','scantron_domain'));
                   7309: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7310: 	$r->print("\n:\n".
1.257     albertel 7311: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7312: 
                   7313: 	$r->print('</li>');
1.186     albertel 7314:     } elsif ($error =~ /CODE$/) {
                   7315: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7316: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7317: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7318: 	    $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 7319: 	}
1.658     bisitz   7320: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7321: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7322:                  ."</p>\n");
1.242     albertel 7323: 	$r->print($message);
1.658     bisitz   7324: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7325: 	$r->print("\n<br /> ");
1.194     albertel 7326: 	my $i=0;
1.273     albertel 7327: 	if ($error eq 'incorrectCODE' 
                   7328: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7329: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7330: 	    if ($closest > 0) {
                   7331: 		foreach my $testcode (@{$closest}) {
                   7332: 		    my $checked='';
1.569     bisitz   7333: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7334: 		    $r->print("
                   7335:    <label>
1.569     bisitz   7336:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7337:        ".&mt("Use the similar CODE [_1] instead.",
                   7338: 	    "<b><tt>".$testcode."</tt></b>")."
                   7339:     </label>
                   7340:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7341: 		    $r->print("\n<br />");
                   7342: 		    $i++;
                   7343: 		}
1.194     albertel 7344: 	    }
                   7345: 	}
1.273     albertel 7346: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7347: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7348: 	    $r->print("
                   7349:     <label>
1.569     bisitz   7350:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7351:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7352: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7353:     </label>");
1.273     albertel 7354: 	    $r->print("\n<br />");
                   7355: 	}
1.194     albertel 7356: 
1.597     wenzelju 7357: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7358: function change_radio(field) {
1.190     albertel 7359:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7360:     var i;
                   7361:     for (i=0;i<slct.length;i++) {
                   7362:         if (slct[i].value==field) { slct[i].checked=true; }
                   7363:     }
                   7364: }
                   7365: ENDSCRIPT
1.187     albertel 7366: 	my $href="/adm/pickcode?".
1.359     www      7367: 	   "form=".&escape("scantronupload").
                   7368: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7369: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7370: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7371: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7372: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7373: 	    $r->print("
                   7374:     <label>
                   7375:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7376:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7377: 	     "<a target='_blank' href='$href'>","</a>")."
                   7378:     </label> 
1.558     bisitz   7379:     ".&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 7380: 	    $r->print("\n<br />");
                   7381: 	}
1.492     albertel 7382: 	$r->print("
                   7383:     <label>
                   7384:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7385:        ".&mt("Use [_1] as the CODE.",
                   7386: 	     "</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 7387: 	$r->print("\n<br /><br />");
1.157     albertel 7388:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7389: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7390: 
                   7391: 	# The form field scantron_questions is acutally a list of line numbers.
                   7392: 	# represented by this form so:
                   7393: 
1.691     raeburn  7394: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7395:                                                 $respnumlookup,$startline);
1.497     foxr     7396: 
1.157     albertel 7397: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7398: 		  $line_list.'" />');
1.242     albertel 7399: 	$r->print($message);
1.492     albertel 7400: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7401: 	foreach my $question (@{$arg}) {
1.503     raeburn  7402: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7403:                                                    $scan_record, $error,
                   7404:                                                    $randomorder,$randompick,
                   7405:                                                    $respnumlookup,$startline);
1.524     raeburn  7406:             push(@lines_to_correct,@linenums);
1.157     albertel 7407: 	}
1.503     raeburn  7408:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7409:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7410: 	$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 7411: 	$r->print($message);
1.492     albertel 7412: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7413: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7414: 
1.503     raeburn  7415: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7416: 	# a list of question numbers. Therefore:
                   7417: 	#
1.691     raeburn  7418: 
                   7419: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7420:                                                 $respnumlookup,$startline);
1.497     foxr     7421: 
1.157     albertel 7422: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7423: 		  $line_list.'" />');
1.157     albertel 7424: 	foreach my $question (@{$arg}) {
1.503     raeburn  7425: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7426:                                                    $scan_record, $error,
                   7427:                                                    $randomorder,$randompick,
                   7428:                                                    $respnumlookup,$startline);
1.524     raeburn  7429:             push(@lines_to_correct,@linenums);
1.157     albertel 7430: 	}
1.503     raeburn  7431:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7432:     } else {
                   7433: 	$r->print("\n<ul>");
                   7434:     }
                   7435:     $r->print("\n</li></ul>");
1.497     foxr     7436: }
                   7437: 
1.503     raeburn  7438: sub verify_bubbles_checked {
                   7439:     my (@ansnums) = @_;
                   7440:     my $ansnumstr = join('","',@ansnums);
                   7441:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7442:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7443: function verify_bubble_radio(form) {
                   7444:     var ansnumArray = new Array ("$ansnumstr");
                   7445:     var need_bubble_count = 0;
                   7446:     for (var i=0; i<ansnumArray.length; i++) {
                   7447:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7448:             var bubble_picked = 0; 
                   7449:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7450:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7451:                     bubble_picked = 1;
                   7452:                 }
                   7453:             }
                   7454:             if (bubble_picked == 0) {
                   7455:                 need_bubble_count ++;
                   7456:             }
                   7457:         }
                   7458:     }
                   7459:     if (need_bubble_count) {
                   7460:         alert("$warning");
                   7461:         return;
                   7462:     }
                   7463:     form.submit(); 
                   7464: }
                   7465: ENDSCRIPT
                   7466:     return $output;
                   7467: }
                   7468: 
1.497     foxr     7469: =pod
                   7470: 
                   7471: =item  questions_to_line_list
1.157     albertel 7472: 
1.497     foxr     7473: Converts a list of questions into a string of comma separated
                   7474: line numbers in the answer sheet used by the questions.  This is
                   7475: used to fill in the scantron_questions form field.
                   7476: 
                   7477:   Arguments:
                   7478:      questions    - Reference to an array of questions.
1.691     raeburn  7479:      randomorder  - True if randomorder in use.
                   7480:      randompick   - True if randompick in use.
                   7481:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7482:                      for current line to question number used for same question
                   7483:                      in "Master Seqence" (as seen by Course Coordinator).
                   7484:      startline    - Reference to hash where key is question number (0 is first)
                   7485:                     and key is number of first bubble line for current student
                   7486:                     or code-based randompick and/or randomorder.
1.693     raeburn  7487: 
1.497     foxr     7488: =cut
                   7489: 
                   7490: 
                   7491: sub questions_to_line_list {
1.691     raeburn  7492:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7493:     my @lines;
                   7494: 
1.503     raeburn  7495:     foreach my $item (@{$questions}) {
                   7496:         my $question = $item;
                   7497:         my ($first,$count,$last);
                   7498:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7499:             $question = $1;
                   7500:             my $subquestion = $2;
1.691     raeburn  7501:             my $responsenum = $question-1;
                   7502:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7503:                 $responsenum = $respnumlookup->{$question-1};
                   7504:                 if (ref($startline) eq 'HASH') {
                   7505:                     $first = $startline->{$question-1} + 1;
                   7506:                 }
                   7507:             } else {
                   7508:                 $first = $first_bubble_line{$responsenum} + 1;
                   7509:             }
                   7510:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7511:             my $subcount = 1;
                   7512:             while ($subcount<$subquestion) {
                   7513:                 $first += $subans[$subcount-1];
                   7514:                 $subcount ++;
                   7515:             }
                   7516:             $count = $subans[$subquestion-1];
                   7517:         } else {
1.691     raeburn  7518:             my $responsenum = $question-1;
                   7519:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7520:                 $responsenum = $respnumlookup->{$question-1};
                   7521:                 if (ref($startline) eq 'HASH') {
                   7522:                     $first = $startline->{$question-1} + 1;
                   7523:                 }
                   7524:             } else {
                   7525:                 $first = $first_bubble_line{$responsenum} + 1;
                   7526:             }
                   7527: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7528:         }
1.506     raeburn  7529:         $last = $first+$count-1;
1.503     raeburn  7530:         push(@lines, ($first..$last));
1.497     foxr     7531:     }
                   7532:     return join(',', @lines);
                   7533: }
                   7534: 
                   7535: =pod 
                   7536: 
                   7537: =item prompt_for_corrections
                   7538: 
                   7539: Prompts for a potentially multiline correction to the
                   7540: user's bubbling (factors out common code from scantron_get_correction
                   7541: for multi and missing bubble cases).
                   7542: 
                   7543:  Arguments:
                   7544:    $r           - Apache request object.
                   7545:    $question    - The question number to prompt for.
                   7546:    $scan_config - The scantron file configuration hash.
                   7547:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7548:    $error       - Type of error
1.691     raeburn  7549:    $randomorder - True if randomorder in use.
                   7550:    $randompick  - True if randompick in use.
                   7551:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7552:                     for current line to question number used for same question
                   7553:                     in "Master Seqence" (as seen by Course Coordinator).
                   7554:    $startline   - Reference to hash where key is question number (0 is first)
                   7555:                   and value is number of first bubble line for current student
                   7556:                   or code-based randompick and/or randomorder.
                   7557: 
1.497     foxr     7558: 
                   7559:  Implicit inputs:
                   7560:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7561:                                   Numbered from 0 (but question numbers are from
                   7562:                                   1.
                   7563:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7564:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7565:                                   type problems render as separate sub-questions, 
1.503     raeburn  7566:                                   in exam mode. This hash contains a 
                   7567:                                   comma-separated list of the lines per 
                   7568:                                   sub-question.
1.510     raeburn  7569:    %responsetype_per_response   - essayresponse, formularesponse,
                   7570:                                   stringresponse, imageresponse, reactionresponse,
                   7571:                                   and organicresponse type problem parts can have
1.503     raeburn  7572:                                   multiple lines per response if the weight
                   7573:                                   assigned exceeds 10.  In this case, only
                   7574:                                   one bubble per line is permitted, but more 
                   7575:                                   than one line might contain bubbles, e.g.
                   7576:                                   bubbling of: line 1 - J, line 2 - J, 
                   7577:                                   line 3 - B would assign 22 points.  
1.497     foxr     7578: 
                   7579: =cut
                   7580: 
                   7581: sub prompt_for_corrections {
1.691     raeburn  7582:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7583:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7584:     my ($current_line,$lines);
                   7585:     my @linenums;
                   7586:     my $questionnum = $question;
1.691     raeburn  7587:     my ($first,$responsenum);
1.503     raeburn  7588:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7589:         $question = $1;
                   7590:         my $subquestion = $2;
1.691     raeburn  7591:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7592:             $responsenum = $respnumlookup->{$question-1};
                   7593:             if (ref($startline) eq 'HASH') {
                   7594:                 $first = $startline->{$question-1};
                   7595:             }
                   7596:         } else {
                   7597:             $responsenum = $question-1;
1.714     raeburn  7598:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7599:         }
                   7600:         $current_line = $first + 1 ;
                   7601:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7602:         my $subcount = 1;
                   7603:         while ($subcount<$subquestion) {
                   7604:             $current_line += $subans[$subcount-1];
                   7605:             $subcount ++;
                   7606:         }
                   7607:         $lines = $subans[$subquestion-1];
                   7608:     } else {
1.691     raeburn  7609:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7610:             $responsenum = $respnumlookup->{$question-1};
                   7611:             if (ref($startline) eq 'HASH') { 
                   7612:                 $first = $startline->{$question-1};
                   7613:             }
                   7614:         } else {
                   7615:             $responsenum = $question-1;
                   7616:             $first = $first_bubble_line{$responsenum};
                   7617:         }
                   7618:         $current_line = $first + 1;
                   7619:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7620:     }
1.497     foxr     7621:     if ($lines > 1) {
1.503     raeburn  7622:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7623:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7624:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7625:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7626:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7627:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7628:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7629:             $r->print(
                   7630:                 &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)
                   7631:                .'<br /><br />'
                   7632:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7633:                .'<br />'
                   7634:                .&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.')
                   7635:                .'<br />'
                   7636:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7637:                .'<br /><br />'
                   7638:             );
1.503     raeburn  7639:         } else {
                   7640:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7641:         }
1.497     foxr     7642:     }
                   7643:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7644:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7645: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7646: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7647:         push(@linenums,$current_line);
1.497     foxr     7648: 	$current_line++;
                   7649:     }
                   7650:     if ($lines > 1) {
                   7651: 	$r->print("<hr /><br />");
                   7652:     }
1.503     raeburn  7653:     return @linenums;
1.157     albertel 7654: }
1.423     albertel 7655: 
                   7656: =pod
                   7657: 
                   7658: =item scantron_bubble_selector
                   7659:   
                   7660:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7661:    possibly showing the existing the selected bubbles if known
1.423     albertel 7662: 
                   7663:  Arguments:
                   7664:     $r           - Apache request object
                   7665:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7666:     $line        - Number of the line being displayed.
1.503     raeburn  7667:     $questionnum - Question number (may include subquestion)
                   7668:     $error       - Type of error.
1.497     foxr     7669:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7670: 
                   7671: =cut
                   7672: 
1.157     albertel 7673: sub scantron_bubble_selector {
1.503     raeburn  7674:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7675:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7676: 
                   7677:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7678:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7679:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7680:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7681:             $max=$$scan_config{'BubblesPerRow'};
                   7682:             if (($scmode eq 'number') && ($max > 10)) {
                   7683:                 $max = 10;
                   7684:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7685:                 $max = 26;
                   7686:             }
                   7687:         } else {
                   7688:             $max = 10;
                   7689:         }
                   7690:     }
1.274     albertel 7691: 
1.157     albertel 7692:     my @alphabet=('A'..'Z');
1.503     raeburn  7693:     $r->print(&Apache::loncommon::start_data_table().
                   7694:               &Apache::loncommon::start_data_table_row());
                   7695:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7696:     for (my $i=0;$i<$max+1;$i++) {
                   7697: 	$r->print("\n".'<td align="center">');
                   7698: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7699: 	else { $r->print('&nbsp;'); }
                   7700: 	$r->print('</td>');
                   7701:     }
1.503     raeburn  7702:     $r->print(&Apache::loncommon::end_data_table_row().
                   7703:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7704:     for (my $i=0;$i<$max;$i++) {
                   7705: 	$r->print("\n".
                   7706: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7707: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7708:     }
1.503     raeburn  7709:     my $nobub_checked = ' ';
                   7710:     if ($error eq 'missingbubble') {
                   7711:         $nobub_checked = ' checked = "checked" ';
                   7712:     }
                   7713:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7714: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7715:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7716:               $line.'" value="'.$questionnum.'" /></td>');
                   7717:     $r->print(&Apache::loncommon::end_data_table_row().
                   7718:               &Apache::loncommon::end_data_table());
1.157     albertel 7719: }
                   7720: 
1.423     albertel 7721: =pod
                   7722: 
                   7723: =item num_matches
                   7724: 
1.424     albertel 7725:    Counts the number of characters that are the same between the two arguments.
                   7726: 
                   7727:  Arguments:
                   7728:    $orig - CODE from the scanline
                   7729:    $code - CODE to match against
                   7730: 
                   7731:  Returns:
                   7732:    $count - integer count of the number of same characters between the
                   7733:             two arguments
                   7734: 
1.423     albertel 7735: =cut
                   7736: 
1.194     albertel 7737: sub num_matches {
                   7738:     my ($orig,$code) = @_;
                   7739:     my @code=split(//,$code);
                   7740:     my @orig=split(//,$orig);
                   7741:     my $same=0;
                   7742:     for (my $i=0;$i<scalar(@code);$i++) {
                   7743: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7744:     }
                   7745:     return $same;
                   7746: }
                   7747: 
1.423     albertel 7748: =pod
                   7749: 
                   7750: =item scantron_get_closely_matching_CODEs
                   7751: 
1.424     albertel 7752:    Cycles through all CODEs and finds the set that has the greatest
                   7753:    number of same characters as the provided CODE
                   7754: 
                   7755:  Arguments:
                   7756:    $allcodes - hash ref returned by &get_codes()
                   7757:    $CODE     - CODE from the current scanline
                   7758: 
                   7759:  Returns:
                   7760:    2 element list
                   7761:     - first elements is number of how closely matching the best fit is 
                   7762:       (5 means best set has 5 matching characters)
                   7763:     - second element is an arrary ref containing the set of valid CODEs
                   7764:       that best fit the passed in CODE
                   7765: 
1.423     albertel 7766: =cut
                   7767: 
1.194     albertel 7768: sub scantron_get_closely_matching_CODEs {
                   7769:     my ($allcodes,$CODE)=@_;
                   7770:     my @CODEs;
                   7771:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7772: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7773:     }
                   7774: 
                   7775:     return ($#CODEs,$CODEs[-1]);
                   7776: }
                   7777: 
1.423     albertel 7778: =pod
                   7779: 
                   7780: =item get_codes
                   7781: 
1.424     albertel 7782:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7783:    set of remembered CODEs.
                   7784: 
                   7785:  Arguments:
                   7786:   $old_name - name of the set of remembered CODEs
                   7787:   $cdom     - domain of the course
                   7788:   $cnum     - internal course name
                   7789: 
                   7790:  Returns:
                   7791:   %allcodes - keys are the valid CODEs, values are all 1
                   7792: 
1.423     albertel 7793: =cut
                   7794: 
1.194     albertel 7795: sub get_codes {
1.280     foxr     7796:     my ($old_name, $cdom, $cnum) = @_;
                   7797:     if (!$old_name) {
                   7798: 	$old_name=$env{'form.scantron_CODElist'};
                   7799:     }
                   7800:     if (!$cdom) {
                   7801: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7802:     }
                   7803:     if (!$cnum) {
                   7804: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7805:     }
1.278     albertel 7806:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7807: 				    $cdom,$cnum);
                   7808:     my %allcodes;
                   7809:     if ($result{"type\0$old_name"} eq 'number') {
                   7810: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7811:     } else {
                   7812: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7813:     }
1.194     albertel 7814:     return %allcodes;
                   7815: }
                   7816: 
1.423     albertel 7817: =pod
                   7818: 
                   7819: =item scantron_validate_CODE
                   7820: 
1.424     albertel 7821:    Validates all scanlines in the selected file to not have any
                   7822:    invalid or underspecified CODEs and that none of the codes are
                   7823:    duplicated if this was requested.
                   7824: 
1.423     albertel 7825: =cut
                   7826: 
1.157     albertel 7827: sub scantron_validate_CODE {
                   7828:     my ($r,$currentphase) = @_;
1.257     albertel 7829:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7830:     if ($scantron_config{'CODElocation'} &&
                   7831: 	$scantron_config{'CODEstart'} &&
                   7832: 	$scantron_config{'CODElength'}) {
1.257     albertel 7833: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7834: 	    &FIXME_blow_up()
                   7835: 	}
                   7836:     } else {
                   7837: 	return (0,$currentphase+1);
                   7838:     }
                   7839:     
                   7840:     my %usedCODEs;
                   7841: 
1.194     albertel 7842:     my %allcodes=&get_codes();
1.186     albertel 7843: 
1.582     raeburn  7844:     my $nav_error;
1.649     raeburn  7845:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7846:     if ($nav_error) {
                   7847:         $r->print(&navmap_errormsg());
                   7848:         return(1,$currentphase);
                   7849:     }
1.447     foxr     7850: 
1.186     albertel 7851:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7852:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7853: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7854: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7855: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7856: 						 $scan_data);
                   7857: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7858: 	my $error=0;
1.224     albertel 7859: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7860: 	    &scantron_get_correction($r,$i,$scan_record,
                   7861: 				     \%scantron_config,
                   7862: 				     $line,'incorrectCODE',\%allcodes);
                   7863: 	    return(1,$currentphase);
                   7864: 	}
1.221     albertel 7865: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7866: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7867: 	    &scantron_get_correction($r,$i,$scan_record,
                   7868: 				     \%scantron_config,
1.194     albertel 7869: 				     $line,'incorrectCODE',\%allcodes);
                   7870: 	    return(1,$currentphase);
1.186     albertel 7871: 	}
1.214     albertel 7872: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7873: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7874: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7875: 	    &scantron_get_correction($r,$i,$scan_record,
                   7876: 				     \%scantron_config,
1.194     albertel 7877: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7878: 	    return(1,$currentphase);
1.186     albertel 7879: 	}
1.524     raeburn  7880: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7881:     }
1.157     albertel 7882:     return (0,$currentphase+1);
                   7883: }
                   7884: 
1.423     albertel 7885: =pod
                   7886: 
                   7887: =item scantron_validate_doublebubble
                   7888: 
1.424     albertel 7889:    Validates all scanlines in the selected file to not have any
                   7890:    bubble lines with multiple bubbles marked.
                   7891: 
1.423     albertel 7892: =cut
                   7893: 
1.157     albertel 7894: sub scantron_validate_doublebubble {
                   7895:     my ($r,$currentphase) = @_;
                   7896:     #get student info
                   7897:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7898:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7899:     my (undef,undef,$sequence)=
                   7900:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7901: 
                   7902:     #get scantron line setup
1.257     albertel 7903:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7904:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7905: 
                   7906:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7907:     unless (ref($navmap)) {
                   7908:         $r->print(&navmap_errormsg());
                   7909:         return(1,$currentphase);
                   7910:     }
                   7911:     my $map=$navmap->getResourceByUrl($sequence);
                   7912:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7913:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7914:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7915:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7916: 
1.583     raeburn  7917:     my $nav_error;
1.691     raeburn  7918:     if (ref($map)) {
                   7919:         $randomorder = $map->randomorder();
                   7920:         $randompick = $map->randompick();
                   7921:         if ($randomorder || $randompick) {
                   7922:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7923:             if ($nav_error) {
                   7924:                 $r->print(&navmap_errormsg());
                   7925:                 return(1,$currentphase);
                   7926:             }
                   7927:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7928:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7929:         }
                   7930:     } else {
                   7931:         $r->print(&navmap_errormsg());
                   7932:         return(1,$currentphase);
                   7933:     }
                   7934: 
1.649     raeburn  7935:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7936:     if ($nav_error) {
                   7937:         $r->print(&navmap_errormsg());
                   7938:         return(1,$currentphase);
                   7939:     }
1.447     foxr     7940: 
1.157     albertel 7941:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7942: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7943: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7944: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7945: 						 $scan_data,undef,\%idmap,$randomorder,
                   7946:                                                  $randompick,$sequence,\@master_seq,
                   7947:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7948:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7949: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7950: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7951: 				 'doublebubble',
1.691     raeburn  7952: 				 $$scan_record{'scantron.doubleerror'},
                   7953:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7954:     	return (1,$currentphase);
                   7955:     }
                   7956:     return (0,$currentphase+1);
                   7957: }
                   7958: 
1.423     albertel 7959: 
1.503     raeburn  7960: sub scantron_get_maxbubble {
1.649     raeburn  7961:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7962:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7963: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7964: 	&restore_bubble_lines();
1.257     albertel 7965: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7966:     }
1.330     albertel 7967: 
1.447     foxr     7968:     my (undef, undef, $sequence) =
1.257     albertel 7969: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7970: 
1.447     foxr     7971:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7972:     unless (ref($navmap)) {
                   7973:         if (ref($nav_error)) {
                   7974:             $$nav_error = 1;
                   7975:         }
1.591     raeburn  7976:         return;
1.582     raeburn  7977:     }
1.191     albertel 7978:     my $map=$navmap->getResourceByUrl($sequence);
                   7979:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7980:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7981: 
                   7982:     &Apache::lonxml::clear_problem_counter();
                   7983: 
1.557     raeburn  7984:     my $uname       = $env{'user.name'};
                   7985:     my $udom        = $env{'user.domain'};
1.435     foxr     7986:     my $cid         = $env{'request.course.id'};
                   7987:     my $total_lines = 0;
                   7988:     %bubble_lines_per_response = ();
1.447     foxr     7989:     %first_bubble_line         = ();
1.503     raeburn  7990:     %subdivided_bubble_lines   = ();
                   7991:     %responsetype_per_response = ();
1.691     raeburn  7992:     %masterseq_id_responsenum  = ();
1.554     raeburn  7993: 
1.447     foxr     7994:     my $response_number = 0;
                   7995:     my $bubble_line     = 0;
1.191     albertel 7996:     foreach my $resource (@resources) {
1.691     raeburn  7997:         my $resid = $resource->id(); 
1.672     raeburn  7998:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7999:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8000:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8001: 	    foreach my $part_id (@{$parts}) {
                   8002:                 my $lines;
                   8003: 
                   8004: 	        # TODO - make this a persistent hash not an array.
                   8005: 
                   8006:                 # optionresponse, matchresponse and rankresponse type items 
                   8007:                 # render as separate sub-questions in exam mode.
                   8008:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8009:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8010:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8011:                     my ($numbub,$numshown);
                   8012:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8013:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8014:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8015:                         }
                   8016:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8017:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8018:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8019:                         }
                   8020:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8021:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8022:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8023:                         }
                   8024:                     }
                   8025:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8026:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8027:                     }
1.649     raeburn  8028:                     my $bubbles_per_row =
                   8029:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8030:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8031:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8032:                         $inner_bubble_lines++;
                   8033:                     }
                   8034:                     for (my $i=0; $i<$numshown; $i++) {
                   8035:                         $subdivided_bubble_lines{$response_number} .= 
                   8036:                             $inner_bubble_lines.',';
                   8037:                     }
                   8038:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8039:                     $lines = $numshown * $inner_bubble_lines;
                   8040:                 } else {
                   8041:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8042:                 }
1.542     raeburn  8043: 
                   8044:                 $first_bubble_line{$response_number} = $bubble_line;
                   8045: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8046:                 $responsetype_per_response{$response_number} = 
                   8047:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8048:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8049: 	        $response_number++;
                   8050: 
                   8051: 	        $bubble_line +=  $lines;
                   8052: 	        $total_lines +=  $lines;
                   8053: 	    }
                   8054:         }
                   8055:     }
1.552     raeburn  8056:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8057: 
                   8058:     &save_bubble_lines();
                   8059:     $env{'form.scantron_maxbubble'} =
                   8060: 	$total_lines;
                   8061:     return $env{'form.scantron_maxbubble'};
                   8062: }
1.523     raeburn  8063: 
1.649     raeburn  8064: sub bubblesheet_bubbles_per_row {
                   8065:     my ($scantron_config) = @_;
                   8066:     my $bubbles_per_row;
                   8067:     if (ref($scantron_config) eq 'HASH') {
                   8068:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8069:     }
                   8070:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8071:         $bubbles_per_row = 10;
                   8072:     }
                   8073:     return $bubbles_per_row;
                   8074: }
                   8075: 
1.157     albertel 8076: sub scantron_validate_missingbubbles {
                   8077:     my ($r,$currentphase) = @_;
                   8078:     #get student info
                   8079:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8080:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8081:     my (undef,undef,$sequence)=
                   8082:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8083: 
                   8084:     #get scantron line setup
1.257     albertel 8085:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8086:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8087: 
                   8088:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8089:     unless (ref($navmap)) {
                   8090:         $r->print(&navmap_errormsg());
                   8091:         return(1,$currentphase);
                   8092:     }
                   8093: 
                   8094:     my $map=$navmap->getResourceByUrl($sequence);
                   8095:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8096:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8097:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8098:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8099: 
1.582     raeburn  8100:     my $nav_error;
1.691     raeburn  8101:     if (ref($map)) {
                   8102:         $randomorder = $map->randomorder();
                   8103:         $randompick = $map->randompick();
                   8104:         if ($randomorder || $randompick) {
                   8105:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8106:             if ($nav_error) {
                   8107:                 $r->print(&navmap_errormsg());
                   8108:                 return(1,$currentphase);
                   8109:             }
                   8110:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8111:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8112:         }
                   8113:     } else {
                   8114:         $r->print(&navmap_errormsg());
                   8115:         return(1,$currentphase);
                   8116:     }
                   8117: 
                   8118: 
1.649     raeburn  8119:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8120:     if ($nav_error) {
1.691     raeburn  8121:         $r->print(&navmap_errormsg());
1.693     raeburn  8122:         return(1,$currentphase);
1.582     raeburn  8123:     }
1.691     raeburn  8124: 
1.157     albertel 8125:     if (!$max_bubble) { $max_bubble=2**31; }
                   8126:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8127: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8128: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8129: 	my $scan_record =
                   8130:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8131: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8132:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8133:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8134: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8135: 	my @to_correct;
1.470     foxr     8136: 	
                   8137: 	# Probably here's where the error is...
                   8138: 
1.157     albertel 8139: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8140:             my $lastbubble;
                   8141:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8142:                my $question = $1;
                   8143:                my $subquestion = $2;
1.691     raeburn  8144:                my ($first,$responsenum);
                   8145:                if ($randomorder || $randompick) {
                   8146:                    $responsenum = $respnumlookup{$question-1};
                   8147:                    $first = $startline{$question-1};
                   8148:                } else {
                   8149:                    $responsenum = $question-1; 
                   8150:                    $first = $first_bubble_line{$responsenum};
                   8151:                }
                   8152:                if (!defined($first)) { next; }
                   8153:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8154:                my $subcount = 1;
                   8155:                while ($subcount<$subquestion) {
                   8156:                    $first += $subans[$subcount-1];
                   8157:                    $subcount ++;
                   8158:                }
                   8159:                my $count = $subans[$subquestion-1];
                   8160:                $lastbubble = $first + $count;
                   8161:             } else {
1.691     raeburn  8162:                my ($first,$responsenum);
                   8163:                if ($randomorder || $randompick) {
                   8164:                    $responsenum = $respnumlookup{$missing-1};
                   8165:                    $first = $startline{$missing-1};
                   8166:                } else {
                   8167:                    $responsenum = $missing-1;
                   8168:                    $first = $first_bubble_line{$responsenum};
                   8169:                }
                   8170:                if (!defined($first)) { next; }
                   8171:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8172:             }
                   8173:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8174: 	    push(@to_correct,$missing);
                   8175: 	}
                   8176: 	if (@to_correct) {
                   8177: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8178: 				     $line,'missingbubble',\@to_correct,
                   8179:                                      $randomorder,$randompick,\%respnumlookup,
                   8180:                                      \%startline);
1.157     albertel 8181: 	    return (1,$currentphase);
                   8182: 	}
                   8183: 
                   8184:     }
                   8185:     return (0,$currentphase+1);
                   8186: }
                   8187: 
1.663     raeburn  8188: sub hand_bubble_option {
                   8189:     my (undef, undef, $sequence) =
                   8190:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8191:     return if ($sequence eq '');
                   8192:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8193:     unless (ref($navmap)) {
                   8194:         return;
                   8195:     }
                   8196:     my $needs_hand_bubbles;
                   8197:     my $map=$navmap->getResourceByUrl($sequence);
                   8198:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8199:     foreach my $res (@resources) {
                   8200:         if (ref($res)) {
                   8201:             if ($res->is_problem()) {
                   8202:                 my $partlist = $res->parts();
                   8203:                 foreach my $part (@{ $partlist }) {
                   8204:                     my @types = $res->responseType($part);
                   8205:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8206:                         $needs_hand_bubbles = 1;
                   8207:                         last;
                   8208:                     }
                   8209:                 }
                   8210:             }
                   8211:         }
                   8212:     }
                   8213:     if ($needs_hand_bubbles) {
                   8214:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8215:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8216:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8217:                &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 />').
                   8218:                '<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;'.
                   8219:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8220:     }
                   8221:     return;
                   8222: }
1.423     albertel 8223: 
1.82      albertel 8224: sub scantron_process_students {
1.608     www      8225:     my ($r,$symb) = @_;
1.513     foxr     8226: 
1.257     albertel 8227:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8228:     if (!$symb) {
                   8229: 	return '';
                   8230:     }
1.324     albertel 8231:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8232: 
1.257     albertel 8233:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8234:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8235:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8236:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8237:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8238:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8239:     unless (ref($navmap)) {
                   8240:         $r->print(&navmap_errormsg());
                   8241:         return '';
1.691     raeburn  8242:     }
1.83      albertel 8243:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8244:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8245:         %grader_randomlists_by_symb);
1.677     raeburn  8246:     if (ref($map)) {
                   8247:         $randomorder = $map->randomorder();
1.689     raeburn  8248:         $randompick = $map->randompick();
1.691     raeburn  8249:     } else {
                   8250:         $r->print(&navmap_errormsg());
                   8251:         return '';
1.677     raeburn  8252:     }
1.691     raeburn  8253:     my $nav_error;
1.83      albertel 8254:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8255:     if ($randomorder || $randompick) {
                   8256:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8257:         if ($nav_error) {
                   8258:             $r->print(&navmap_errormsg());
                   8259:             return '';
                   8260:         }
                   8261:     }
1.557     raeburn  8262:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8263:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8264: 
1.554     raeburn  8265:     my ($uname,$udom);
1.82      albertel 8266:     my $result= <<SCANTRONFORM;
1.81      albertel 8267: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8268:   <input type="hidden" name="command" value="scantron_configphase" />
                   8269:   $default_form_data
                   8270: SCANTRONFORM
1.82      albertel 8271:     $r->print($result);
                   8272: 
                   8273:     my @delayqueue;
1.542     raeburn  8274:     my (%completedstudents,%scandata);
1.140     albertel 8275:     
1.520     www      8276:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8277:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8278:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8279:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8280:     $r->print('<br />');
1.140     albertel 8281:     my $start=&Time::HiRes::time();
1.158     albertel 8282:     my $i=-1;
1.542     raeburn  8283:     my $started;
1.447     foxr     8284: 
1.649     raeburn  8285:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8286:     if ($nav_error) {
                   8287:         $r->print(&navmap_errormsg());
                   8288:         return '';
                   8289:     }
                   8290: 
1.513     foxr     8291:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8292:     # the user and return.
                   8293: 
                   8294:     if ($ssi_error) {
                   8295: 	$r->print("</form>");
                   8296: 	&ssi_print_error($r);
1.520     www      8297:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8298: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8299:     }
1.447     foxr     8300: 
1.542     raeburn  8301:     my %lettdig = &letter_to_digits();
                   8302:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8303:     my %orderedforcode;
1.542     raeburn  8304: 
1.157     albertel 8305:     while ($i<$scanlines->{'count'}) {
                   8306:  	($uname,$udom)=('','');
                   8307:  	$i++;
1.200     albertel 8308:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8309:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8310: 	if ($started) {
1.667     www      8311: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8312: 	}
                   8313: 	$started=1;
1.691     raeburn  8314:         my %respnumlookup = ();
                   8315:         my %startline = ();
                   8316:         my $total;
1.157     albertel 8317:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8318:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8319:                                                  $randompick,$sequence,\@master_seq,
                   8320:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8321:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8322:                                                  \$total);
1.157     albertel 8323:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8324:  					      \%idmap,$i)) {
                   8325:   	    &scantron_add_delay(\@delayqueue,$line,
                   8326:  				'Unable to find a student that matches',1);
                   8327:  	    next;
                   8328:   	}
                   8329:  	if (exists $completedstudents{$uname}) {
                   8330:  	    &scantron_add_delay(\@delayqueue,$line,
                   8331:  				'Student '.$uname.' has multiple sheets',2);
                   8332:  	    next;
                   8333:  	}
1.677     raeburn  8334:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8335:         my $user = $uname.':'.$usec;
1.157     albertel 8336:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8337: 
1.677     raeburn  8338:         my $scancode;
                   8339:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8340:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8341:             $scancode = $scan_record->{'scantron.CODE'};
                   8342:         } else {
                   8343:             $scancode = '';
                   8344:         }
                   8345: 
                   8346:         my @mapresources = @resources;
1.689     raeburn  8347:         if ($randomorder || $randompick) {
1.678     raeburn  8348:             @mapresources = 
1.691     raeburn  8349:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8350:                              \%orderedforcode);
1.677     raeburn  8351:         }
1.586     raeburn  8352:         my (%partids_by_symb,$res_error);
1.677     raeburn  8353:         foreach my $resource (@mapresources) {
1.586     raeburn  8354:             my $ressymb;
                   8355:             if (ref($resource)) {
                   8356:                 $ressymb = $resource->symb();
                   8357:             } else {
                   8358:                 $res_error = 1;
                   8359:                 last;
                   8360:             }
1.557     raeburn  8361:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8362:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8363:                 my ($analysis,$parts) =
1.672     raeburn  8364:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8365:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8366:                 $partids_by_symb{$ressymb} = $parts;
                   8367:             } else {
                   8368:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8369:             }
1.554     raeburn  8370:         }
                   8371: 
1.586     raeburn  8372:         if ($res_error) {
                   8373:             &scantron_add_delay(\@delayqueue,$line,
                   8374:                                 'An error occurred while grading student '.$uname,2);
                   8375:             next;
                   8376:         }
                   8377: 
1.330     albertel 8378: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8379:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8380: 
                   8381: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8382: 	    &scantron_putfile($scanlines,$scan_data);
                   8383: 	}
1.161     albertel 8384: 	
1.542     raeburn  8385:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8386:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8387:                                    $bubbles_per_row,$randomorder,$randompick,
                   8388:                                    \%respnumlookup,\%startline) 
                   8389:             eq 'ssi_error') {
1.542     raeburn  8390:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8391:             $r->print("</form>");
                   8392:             &ssi_print_error($r);
                   8393:             &Apache::lonnet::remove_lock($lock);
                   8394:             return '';      # Why return ''?  Beats me.
                   8395:         }
1.513     foxr     8396: 
1.692     raeburn  8397:         if (($scancode) && ($randomorder || $randompick)) {
                   8398:             my $parmresult =
                   8399:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8400:                                                        '0_examcode',2,$scancode,
                   8401:                                                        'string_examcode',$uname,
                   8402:                                                        $udom);
                   8403:         }
1.140     albertel 8404: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8405:         if ($env{'form.verifyrecord'}) {
                   8406:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8407:             if ($randompick) {
                   8408:                 if ($total) {
                   8409:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8410:                 }
                   8411:             }
                   8412: 
1.542     raeburn  8413:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8414:             chomp($studentdata);
                   8415:             $studentdata =~ s/\r$//;
                   8416:             my $studentrecord = '';
                   8417:             my $counter = -1;
1.677     raeburn  8418:             foreach my $resource (@mapresources) {
1.554     raeburn  8419:                 my $ressymb = $resource->symb();
1.542     raeburn  8420:                 ($counter,my $recording) =
                   8421:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8422:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8423:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8424:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8425:                 $studentrecord .= $recording;
                   8426:             }
                   8427:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8428:                 &Apache::lonxml::clear_problem_counter();
                   8429:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8430:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8431:                                            $bubbles_per_row,$randomorder,$randompick,
                   8432:                                            \%respnumlookup,\%startline) 
                   8433:                     eq 'ssi_error') {
1.554     raeburn  8434:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8435:                     $r->print("</form>");
                   8436:                     &ssi_print_error($r);
                   8437:                     &Apache::lonnet::remove_lock($lock);
                   8438:                     delete($completedstudents{$uname});
                   8439:                     return '';
                   8440:                 }
1.542     raeburn  8441:                 $counter = -1;
                   8442:                 $studentrecord = '';
1.677     raeburn  8443:                 foreach my $resource (@mapresources) {
1.554     raeburn  8444:                     my $ressymb = $resource->symb();
1.542     raeburn  8445:                     ($counter,my $recording) =
                   8446:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8447:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8448:                                                  \%scantron_config,\%lettdig,$numletts,
                   8449:                                                  $randomorder,$randompick,\%respnumlookup,
                   8450:                                                  \%startline);
1.542     raeburn  8451:                     $studentrecord .= $recording;
                   8452:                 }
                   8453:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8454:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8455:                     if ($scancode eq '') {
1.658     bisitz   8456:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8457:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8458:                     } else {
1.658     bisitz   8459:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8460:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8461:                     }
                   8462:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8463:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8464:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8465:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8466:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8467:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8468:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8469:                               &Apache::loncommon::end_data_table_row().
                   8470:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8471:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8472:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8473:                               &Apache::loncommon::end_data_table_row().
                   8474:                               &Apache::loncommon::end_data_table().'</p>');
                   8475:                 } else {
                   8476:                     $r->print('<br /><span class="LC_warning">'.
                   8477:                              &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 />'.
                   8478:                              &mt("As a consequence, this user's submission history records two tries.").
                   8479:                                  '</span><br />');
                   8480:                 }
                   8481:             }
                   8482:         }
1.543     raeburn  8483:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8484:     } continue {
1.330     albertel 8485: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8486: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8487:     }
1.140     albertel 8488:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8489:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8490: #    my $lasttime = &Time::HiRes::time()-$start;
                   8491: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8492: 
1.200     albertel 8493:     $r->print("</form>");
1.157     albertel 8494:     return '';
1.75      albertel 8495: }
1.157     albertel 8496: 
1.557     raeburn  8497: sub graders_resources_pass {
1.649     raeburn  8498:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8499:         $bubbles_per_row) = @_;
1.557     raeburn  8500:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8501:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8502:         foreach my $resource (@{$resources}) {
                   8503:             my $ressymb = $resource->symb();
                   8504:             my ($analysis,$parts) =
                   8505:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8506:                                           $env{'user.name'},$env{'user.domain'},
                   8507:                                           1,$bubbles_per_row);
1.557     raeburn  8508:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8509:             if (ref($analysis) eq 'HASH') {
                   8510:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8511:                     $grader_randomlists_by_symb->{$ressymb} =
                   8512:                         $analysis->{'parts_withrandomlist'};
                   8513:                 }
                   8514:             }
                   8515:         }
                   8516:     }
                   8517:     return;
                   8518: }
                   8519: 
1.678     raeburn  8520: =pod
                   8521: 
                   8522: =item users_order
                   8523: 
                   8524:   Returns array of resources in current map, ordered based on either CODE,
                   8525:   if this is a CODEd exam, or based on student's identity if this is a 
                   8526:   "NAMEd" exam.
                   8527: 
1.691     raeburn  8528:   Should be used when randomorder and/or randompick applied when the 
                   8529:   corresponding exam was printed, prior to students completing bubblesheets 
                   8530:   for the version of the exam the student received.
1.678     raeburn  8531: 
                   8532: =cut
                   8533: 
                   8534: sub users_order  {
1.691     raeburn  8535:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8536:     my @mapresources;
1.691     raeburn  8537:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8538:         return @mapresources;
1.691     raeburn  8539:     }
                   8540:     if ($scancode) {
                   8541:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8542:             @mapresources = @{$orderedforcode->{$scancode}};
                   8543:         } else {
                   8544:             $env{'form.CODE'} = $scancode;
                   8545:             my $actual_seq =
                   8546:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8547:                                                                $master_seq,
                   8548:                                                                $user,$scancode,1);
                   8549:             if (ref($actual_seq) eq 'ARRAY') {
                   8550:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8551:                 if (ref($orderedforcode) eq 'HASH') {
                   8552:                     if (@mapresources > 0) { 
                   8553:                         $orderedforcode->{$scancode} = \@mapresources;
                   8554:                     }
                   8555:                 }
                   8556:             }
                   8557:             delete($env{'form.CODE'});
1.678     raeburn  8558:         }
                   8559:     } else {
                   8560:         my $actual_seq =
                   8561:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8562:                                                            $master_seq,
1.688     raeburn  8563:                                                            $user,undef,1);
1.678     raeburn  8564:         if (ref($actual_seq) eq 'ARRAY') {
                   8565:             @mapresources = 
                   8566:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8567:         }
1.691     raeburn  8568:     }
                   8569:     return @mapresources;
1.678     raeburn  8570: }
                   8571: 
1.542     raeburn  8572: sub grade_student_bubbles {
1.691     raeburn  8573:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8574:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8575:     my $uselookup = 0;
                   8576:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8577:         (ref($startline) eq 'HASH')) {
                   8578:         $uselookup = 1;
                   8579:     }
                   8580: 
1.554     raeburn  8581:     if (ref($resources) eq 'ARRAY') {
                   8582:         my $count = 0;
                   8583:         foreach my $resource (@{$resources}) {
                   8584:             my $ressymb = $resource->symb();
                   8585:             my %form = ('submitted'      => 'scantron',
                   8586:                         'grade_target'   => 'grade',
                   8587:                         'grade_username' => $uname,
                   8588:                         'grade_domain'   => $udom,
                   8589:                         'grade_courseid' => $env{'request.course.id'},
                   8590:                         'grade_symb'     => $ressymb,
                   8591:                         'CODE'           => $scancode
                   8592:                        );
1.649     raeburn  8593:             if ($bubbles_per_row ne '') {
                   8594:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8595:             }
1.663     raeburn  8596:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8597:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8598:             }
1.554     raeburn  8599:             if (ref($parts) eq 'HASH') {
                   8600:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8601:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8602:                         if ($uselookup) {
                   8603:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8604:                         } else {
                   8605:                             $form{'scantron_questnum_start.'.$part} =
                   8606:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8607:                         }
1.554     raeburn  8608:                         $count++;
                   8609:                     }
                   8610:                 }
                   8611:             }
                   8612:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8613:             return 'ssi_error' if ($ssi_error);
                   8614:             last if (&Apache::loncommon::connection_aborted($r));
                   8615:         }
1.542     raeburn  8616:     }
                   8617:     return;
                   8618: }
                   8619: 
1.157     albertel 8620: sub scantron_upload_scantron_data {
1.608     www      8621:     my ($r,$symb)=@_;
1.565     raeburn  8622:     my $dom = $env{'request.role.domain'};
                   8623:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8624:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8625:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8626: 							  'domainid',
1.565     raeburn  8627: 							  'coursename',$dom);
                   8628:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8629:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8630:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8631:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8632:     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 8633:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8634:     function checkUpload(formname) {
                   8635: 	if (formname.upfile.value == "") {
1.579     raeburn  8636: 	    alert("'.$nofile_alert.'");
1.157     albertel 8637: 	    return false;
                   8638: 	}
1.565     raeburn  8639:         if (formname.courseid.value == "") {
1.579     raeburn  8640:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8641:             return false;
                   8642:         }
1.157     albertel 8643: 	formname.submit();
                   8644:     }
1.565     raeburn  8645: 
                   8646:     function ToSyllabus() {
                   8647:         var cdom = '."'$dom'".';
                   8648:         var cnum = document.rules.courseid.value;
                   8649:         if (cdom == "" || cdom == null) {
                   8650:             return;
                   8651:         }
                   8652:         if (cnum == "" || cnum == null) {
                   8653:            return;
                   8654:         }
                   8655:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8656:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8657:         return;
                   8658:     }
                   8659: 
1.597     wenzelju 8660: '));
                   8661:     $r->print('
1.648     bisitz   8662: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8663: 
1.492     albertel 8664: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8665: '.$default_form_data.
                   8666:   &Apache::lonhtmlcommon::start_pick_box().
                   8667:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8668:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8669:   &Apache::lonhtmlcommon::row_closure().
                   8670:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8671:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8672:   &Apache::lonhtmlcommon::row_closure().
                   8673:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8674:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8675:   &Apache::lonhtmlcommon::row_closure().
                   8676:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8677:   '<input type="file" name="upfile" size="50" />'.
                   8678:   &Apache::lonhtmlcommon::row_closure(1).
                   8679:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8680: 
1.492     albertel 8681: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8682: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8683: </form>
1.492     albertel 8684: ');
1.157     albertel 8685:     return '';
                   8686: }
                   8687: 
1.423     albertel 8688: 
1.157     albertel 8689: sub scantron_upload_scantron_data_save {
1.608     www      8690:     my($r,$symb)=@_;
1.182     albertel 8691:     my $doanotherupload=
                   8692: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8693: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8694: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8695: 	'</form>'."\n";
1.257     albertel 8696:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8697: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8698: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8699: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8700: 	unless ($symb) {
1.182     albertel 8701: 	    $r->print($doanotherupload);
                   8702: 	}
1.162     albertel 8703: 	return '';
                   8704:     }
1.257     albertel 8705:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8706:     my $uploadedfile;
1.710     bisitz   8707:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8708:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8709:         $r->print(
                   8710:             &Apache::lonhtmlcommon::confirm_success(
                   8711:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8712:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8713:     } else {
1.568     raeburn  8714:         my $result = 
                   8715:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8716:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8717:         if ($result =~ m{^/uploaded/}) {
                   8718:             $r->print(
                   8719:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8720:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8721:                         (length($env{'form.upfile'})-1),
                   8722:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8723:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8724:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8725:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8726:         } else {
                   8727:             $r->print(
                   8728:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8729:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8730:                           $result,
1.568     raeburn  8731: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8732: 	}
                   8733:     }
1.174     albertel 8734:     if ($symb) {
1.612     www      8735: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8736:     } else {
1.182     albertel 8737: 	$r->print($doanotherupload);
1.174     albertel 8738:     }
1.157     albertel 8739:     return '';
                   8740: }
                   8741: 
1.567     raeburn  8742: sub validate_uploaded_scantron_file {
                   8743:     my ($cdom,$cname,$fname) = @_;
                   8744:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8745:     my @lines;
                   8746:     if ($scanlines ne '-1') {
                   8747:         @lines=split("\n",$scanlines,-1);
                   8748:     }
                   8749:     my $output;
                   8750:     if (@lines) {
                   8751:         my (%counts,$max_match_format);
1.710     bisitz   8752:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8753:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8754:         my %idmap = &username_to_idmap($classlist);
                   8755:         foreach my $key (keys(%idmap)) {
                   8756:             my $lckey = lc($key);
                   8757:             $idmap{$lckey} = $idmap{$key};
                   8758:         }
                   8759:         my %unique_formats;
                   8760:         my @formatlines = &get_scantronformat_file();
                   8761:         foreach my $line (@formatlines) {
                   8762:             chomp($line);
                   8763:             my @config = split(/:/,$line);
                   8764:             my $idstart = $config[5];
                   8765:             my $idlength = $config[6];
                   8766:             if (($idstart ne '') && ($idlength > 0)) {
                   8767:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8768:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8769:                 } else {
                   8770:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8771:                 }
                   8772:             }
                   8773:         }
                   8774:         foreach my $key (keys(%unique_formats)) {
                   8775:             my ($idstart,$idlength) = split(':',$key);
                   8776:             %{$counts{$key}} = (
                   8777:                                'found'   => 0,
                   8778:                                'total'   => 0,
                   8779:                               );
                   8780:             foreach my $line (@lines) {
                   8781:                 next if ($line =~ /^#/);
                   8782:                 next if ($line =~ /^[\s\cz]*$/);
                   8783:                 my $id = substr($line,$idstart-1,$idlength);
                   8784:                 $id = lc($id);
                   8785:                 if (exists($idmap{$id})) {
                   8786:                     $counts{$key}{'found'} ++;
                   8787:                 }
                   8788:                 $counts{$key}{'total'} ++;
                   8789:             }
                   8790:             if ($counts{$key}{'total'}) {
                   8791:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8792:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8793:                     $max_match_pct = $percent_match;
                   8794:                     $max_match_format = $key;
1.710     bisitz   8795:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8796:                     $max_match_count = $counts{$key}{'total'};
                   8797:                 }
                   8798:             }
                   8799:         }
                   8800:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8801:             my $format_descs;
                   8802:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8803:             for (my $i=0; $i<$numwithformat; $i++) {
                   8804:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8805:                 if ($i<$numwithformat-2) {
                   8806:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8807:                 } elsif ($i==$numwithformat-2) {
                   8808:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8809:                 } elsif ($i==$numwithformat-1) {
                   8810:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8811:                 }
                   8812:             }
                   8813:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8814:             $output .= '<br />';
                   8815:             if ($found_match_count == $max_match_count) {
                   8816:                 # 100% matching entries
                   8817:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8818:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8819:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8820:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8821:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8822:                     ' in the file (for the format defined for [_3]).',
                   8823:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8824:             } else {
                   8825:                 # Not all entries matching? -> Show warning and additional info
                   8826:                 $output .=
                   8827:                     &Apache::lonhtmlcommon::confirm_success(
                   8828:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8829:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8830:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8831:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8832:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8833:                         ' in the file (for the format defined for [_3]).',
                   8834:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8835:                     '<p class="LC_info">'.
                   8836:                     &mt('A low percentage of matches results from one of the following:').
                   8837:                     '</p><ul>'.
                   8838:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8839:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8840:                                '<i>'.$cdom.'</i>').'</li>'.
                   8841:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8842:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8843:                     '</ul>';
                   8844:             }
1.567     raeburn  8845:         }
                   8846:     } else {
1.710     bisitz   8847:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8848:     }
                   8849:     return $output;
                   8850: }
                   8851: 
1.202     albertel 8852: sub valid_file {
                   8853:     my ($requested_file)=@_;
                   8854:     foreach my $filename (sort(&scantron_filenames())) {
                   8855: 	if ($requested_file eq $filename) { return 1; }
                   8856:     }
                   8857:     return 0;
                   8858: }
                   8859: 
                   8860: sub scantron_download_scantron_data {
1.608     www      8861:     my ($r,$symb)=@_;
                   8862:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8863:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8864:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8865:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8866:     if (! &valid_file($file)) {
1.492     albertel 8867: 	$r->print('
1.202     albertel 8868: 	<p>
1.686     bisitz   8869: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8870:         </p>
1.492     albertel 8871: ');
1.202     albertel 8872: 	return;
                   8873:     }
                   8874:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8875:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8876:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8877:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8878:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8879:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8880:     $r->print('
1.202     albertel 8881:     <p>
1.711     bisitz   8882: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
1.492     albertel 8883: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8884:     </p>
                   8885:     <p>
1.492     albertel 8886: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8887: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8888:     </p>
                   8889:     <p>
1.492     albertel 8890: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8891: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8892:     </p>
1.492     albertel 8893: ');
1.202     albertel 8894:     return '';
                   8895: }
1.157     albertel 8896: 
1.523     raeburn  8897: sub checkscantron_results {
1.608     www      8898:     my ($r,$symb) = @_;
1.523     raeburn  8899:     if (!$symb) {return '';}
                   8900:     my $cid = $env{'request.course.id'};
1.542     raeburn  8901:     my %lettdig = &letter_to_digits();
1.523     raeburn  8902:     my $numletts = scalar(keys(%lettdig));
                   8903:     my $cnum = $env{'course.'.$cid.'.num'};
                   8904:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8905:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8906:     my %record;
                   8907:     my %scantron_config =
                   8908:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8909:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8910:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8911:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8912:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8913:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8914:     unless (ref($navmap)) {
                   8915:         $r->print(&navmap_errormsg());
                   8916:         return '';
                   8917:     }
1.523     raeburn  8918:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8919:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8920:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8921:     if (ref($map)) { 
                   8922:         $randomorder=$map->randomorder();
1.689     raeburn  8923:         $randompick=$map->randompick();
1.677     raeburn  8924:     }
1.557     raeburn  8925:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8926:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8927:     if ($nav_error) {
                   8928:         $r->print(&navmap_errormsg());
                   8929:         return '';
1.678     raeburn  8930:     }
1.673     raeburn  8931:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8932:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8933:     my ($uname,$udom);
1.523     raeburn  8934:     my (%scandata,%lastname,%bylast);
                   8935:     $r->print('
                   8936: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8937: 
                   8938:     my @delayqueue;
                   8939:     my %completedstudents;
                   8940: 
1.691     raeburn  8941:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8942:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8943:     my ($username,$domain,$started);
1.649     raeburn  8944:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8945:     if ($nav_error) {
                   8946:         $r->print(&navmap_errormsg());
                   8947:         return '';
                   8948:     }
1.523     raeburn  8949: 
1.667     www      8950:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8951:     my $start=&Time::HiRes::time();
                   8952:     my $i=-1;
                   8953: 
                   8954:     while ($i<$scanlines->{'count'}) {
                   8955:         ($username,$domain,$uname)=('','','');
                   8956:         $i++;
                   8957:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8958:         if ($line=~/^[\s\cz]*$/) { next; }
                   8959:         if ($started) {
1.667     www      8960:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8961:         }
                   8962:         $started=1;
                   8963:         my $scan_record=
                   8964:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8965:                                                      $scan_data);
1.693     raeburn  8966:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8967:                                               \%idmap,$i)) {
1.523     raeburn  8968:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8969:                                 'Unable to find a student that matches',1);
                   8970:             next;
                   8971:         }
                   8972:         if (exists $completedstudents{$uname}) {
                   8973:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8974:                                 'Student '.$uname.' has multiple sheets',2);
                   8975:             next;
                   8976:         }
                   8977:         my $pid = $scan_record->{'scantron.ID'};
                   8978:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8979:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  8980:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8981:         my $user = $uname.':'.$usec;
1.523     raeburn  8982:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  8983: 
1.678     raeburn  8984:         my $scancode;
1.677     raeburn  8985:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8986:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8987:             $scancode = $scan_record->{'scantron.CODE'};
                   8988:         } else {
                   8989:             $scancode = '';
                   8990:         }
                   8991: 
                   8992:         my @mapresources = @resources;
1.691     raeburn  8993:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8994:         my %respnumlookup=();
                   8995:         my %startline=();
1.689     raeburn  8996:         if ($randomorder || $randompick) {
1.678     raeburn  8997:             @mapresources =
1.691     raeburn  8998:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8999:                              \%orderedforcode);
                   9000:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9001:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9002:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9003:                                              \%respnumlookup,\%startline);
                   9004:             if ($randompick && $total) {
                   9005:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9006:             }
1.677     raeburn  9007:         }
1.691     raeburn  9008:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9009:         chomp($scandata{$pid});
                   9010:         $scandata{$pid} =~ s/\r$//;
                   9011: 
1.523     raeburn  9012:         my $counter = -1;
1.677     raeburn  9013:         foreach my $resource (@mapresources) {
1.557     raeburn  9014:             my $parts;
1.554     raeburn  9015:             my $ressymb = $resource->symb();
1.557     raeburn  9016:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9017:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9018:                 (my $analysis,$parts) =
1.672     raeburn  9019:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9020:                                               $username,$domain,undef,
                   9021:                                               $bubbles_per_row);
1.557     raeburn  9022:             } else {
                   9023:                 $parts = $grader_partids_by_symb{$ressymb};
                   9024:             }
1.542     raeburn  9025:             ($counter,my $recording) =
                   9026:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9027:                                          $scandata{$pid},$parts,
1.691     raeburn  9028:                                          \%scantron_config,\%lettdig,$numletts,
                   9029:                                          $randomorder,$randompick,
                   9030:                                          \%respnumlookup,\%startline);
1.542     raeburn  9031:             $record{$pid} .= $recording;
1.523     raeburn  9032:         }
                   9033:     }
                   9034:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9035:     $r->print('<br />');
                   9036:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9037:     $passed = 0;
                   9038:     $failed = 0;
                   9039:     $numstudents = 0;
                   9040:     foreach my $last (sort(keys(%bylast))) {
                   9041:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9042:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9043:                 my $showscandata = $scandata{$pid};
                   9044:                 my $showrecord = $record{$pid};
                   9045:                 $showscandata =~ s/\s/&nbsp;/g;
                   9046:                 $showrecord =~ s/\s/&nbsp;/g;
                   9047:                 if ($scandata{$pid} eq $record{$pid}) {
                   9048:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9049:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9050: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9051: '</tr>'."\n".
                   9052: '<tr class="'.$css_class.'">'."\n".
                   9053: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   9054:                     $passed ++;
                   9055:                 } else {
                   9056:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9057:                     $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  9058: '</tr>'."\n".
                   9059: '<tr class="'.$css_class.'">'."\n".
                   9060: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   9061: '</tr>'."\n";
                   9062:                     $failed ++;
                   9063:                 }
                   9064:                 $numstudents ++;
                   9065:             }
                   9066:         }
                   9067:     }
1.648     bisitz   9068:     $r->print(
                   9069:         '<p>'
                   9070:        .&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).',
                   9071:             '<b>',
                   9072:             $numstudents,
                   9073:             '</b>',
                   9074:             $env{'form.scantron_maxbubble'})
                   9075:        .'</p>'
                   9076:     );
1.682     raeburn  9077:     $r->print('<p>'
1.683     raeburn  9078:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9079:              .'<br />'
                   9080:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9081:              .'</p>'
                   9082:     );
1.523     raeburn  9083:     if ($passed) {
1.572     www      9084:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9085:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9086:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9087:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9088:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9089:                  $okstudents."\n".
                   9090:                  &Apache::loncommon::end_data_table().'<br />');
                   9091:     }
                   9092:     if ($failed) {
1.572     www      9093:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9094:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9095:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9096:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9097:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9098:                  $badstudents."\n".
                   9099:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9100:                  &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  9101:     }
1.614     www      9102:     $r->print('</form><br />');
1.523     raeburn  9103:     return;
                   9104: }
                   9105: 
1.542     raeburn  9106: sub verify_scantron_grading {
1.554     raeburn  9107:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9108:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9109:         $respnumlookup,$startline) = @_;
1.542     raeburn  9110:     my ($record,%expected,%startpos);
                   9111:     return ($counter,$record) if (!ref($resource));
                   9112:     return ($counter,$record) if (!$resource->is_problem());
                   9113:     my $symb = $resource->symb();
1.554     raeburn  9114:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9115:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9116:         $counter ++;
                   9117:         $expected{$part_id} = 0;
1.691     raeburn  9118:         my $respnum = $counter;
                   9119:         if ($randomorder || $randompick) {
                   9120:             $respnum = $respnumlookup->{$counter};
                   9121:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9122:         } else {
                   9123:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9124:         }
                   9125:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9126:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9127:             foreach my $item (@sub_lines) {
                   9128:                 $expected{$part_id} += $item;
                   9129:             }
                   9130:         } else {
1.691     raeburn  9131:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9132:         }
                   9133:     }
                   9134:     if ($symb) {
                   9135:         my %recorded;
                   9136:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9137:         if ($returnhash{'version'}) {
                   9138:             my %lasthash=();
                   9139:             my $version;
                   9140:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9141:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9142:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9143:                 }
                   9144:             }
                   9145:             foreach my $key (keys(%lasthash)) {
                   9146:                 if ($key =~ /\.scantron$/) {
                   9147:                     my $value = &unescape($lasthash{$key});
                   9148:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9149:                     if ($value eq '') {
                   9150:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9151:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9152:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9153:                             }
                   9154:                         }
                   9155:                     } else {
                   9156:                         my @tocheck;
                   9157:                         my @items = split(//,$value);
                   9158:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9159:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9160:                             if (@items < $expected{$part_id}) {
                   9161:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9162:                                 my @singles = split(//,$fragment);
                   9163:                                 foreach my $pos (@singles) {
                   9164:                                     if ($pos eq ' ') {
                   9165:                                         push(@tocheck,$pos);
                   9166:                                     } else {
                   9167:                                         my $next = shift(@items);
                   9168:                                         push(@tocheck,$next);
                   9169:                                     }
                   9170:                                 }
                   9171:                             } else {
                   9172:                                 @tocheck = @items;
                   9173:                             }
                   9174:                             foreach my $letter (@tocheck) {
                   9175:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9176:                                     if ($letter !~ /^[A-J]$/) {
                   9177:                                         $letter = $scantron_config->{'Qoff'};
                   9178:                                     }
                   9179:                                     $recorded{$part_id} .= $letter;
                   9180:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9181:                                     my $digit;
                   9182:                                     if ($letter !~ /^[A-J]$/) {
                   9183:                                         $digit = $scantron_config->{'Qoff'};
                   9184:                                     } else {
                   9185:                                         $digit = $lettdig->{$letter};
                   9186:                                     }
                   9187:                                     $recorded{$part_id} .= $digit;
                   9188:                                 }
                   9189:                             }
                   9190:                         } else {
                   9191:                             @tocheck = @items;
                   9192:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9193:                                 my $curr_sub = shift(@tocheck);
                   9194:                                 my $digit;
                   9195:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9196:                                     $digit = $lettdig->{$curr_sub}-1;
                   9197:                                 }
                   9198:                                 if ($curr_sub eq 'J') {
                   9199:                                     $digit += scalar($numletts);
                   9200:                                 }
                   9201:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9202:                                     if ($j == $digit) {
                   9203:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9204:                                     } else {
                   9205:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9206:                                     }
                   9207:                                 }
                   9208:                             }
                   9209:                         }
                   9210:                     }
                   9211:                 }
                   9212:             }
                   9213:         }
1.554     raeburn  9214:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9215:             if ($recorded{$part_id} eq '') {
                   9216:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9217:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9218:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9219:                     }
                   9220:                 }
                   9221:             }
                   9222:             $record .= $recorded{$part_id};
                   9223:         }
                   9224:     }
                   9225:     return ($counter,$record);
                   9226: }
                   9227: 
1.691     raeburn  9228: sub letter_to_digits {
1.542     raeburn  9229:     my %lettdig = (
                   9230:                     A => 1,
                   9231:                     B => 2,
                   9232:                     C => 3,
                   9233:                     D => 4,
                   9234:                     E => 5,
                   9235:                     F => 6,
                   9236:                     G => 7,
                   9237:                     H => 8,
                   9238:                     I => 9,
                   9239:                     J => 0,
                   9240:                   );
                   9241:     return %lettdig;
                   9242: }
                   9243: 
1.423     albertel 9244: 
1.75      albertel 9245: #-------- end of section for handling grading scantron forms -------
                   9246: #
                   9247: #-------------------------------------------------------------------
                   9248: 
1.72      ng       9249: #-------------------------- Menu interface -------------------------
                   9250: #
1.614     www      9251: #--- Href with symb and command ---
                   9252: 
                   9253: sub href_symb_cmd {
                   9254:     my ($symb,$cmd)=@_;
1.669     raeburn  9255:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9256: }
                   9257: 
1.443     banghart 9258: sub grading_menu {
1.608     www      9259:     my ($request,$symb) = @_;
1.443     banghart 9260:     if (!$symb) {return '';}
                   9261: 
                   9262:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9263:                   'command'=>'individual');
1.538     schulted 9264:     
1.598     www      9265:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9266: 
                   9267:     $fields{'command'}='ungraded';
                   9268:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9269: 
                   9270:     $fields{'command'}='table';
                   9271:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9272: 
                   9273:     $fields{'command'}='all_for_one';
                   9274:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9275: 
1.621     www      9276:     $fields{'command'}='downloadfilesselect';
                   9277:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9278: 
1.443     banghart 9279:     $fields{'command'} = 'csvform';
1.538     schulted 9280:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9281:     
1.443     banghart 9282:     $fields{'command'} = 'processclicker';
1.538     schulted 9283:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9284:     
1.443     banghart 9285:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9286:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9287: 
                   9288:     $fields{'command'} = 'initialverifyreceipt';
                   9289:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9290:     
1.598     www      9291:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9292:             items =>[
1.598     www      9293:                         {	linktext => 'Select individual students to grade',
                   9294:                     		url => $url1a,
1.538     schulted 9295:                     		permission => 'F',
1.636     wenzelju 9296:                     		icon => 'grade_students.png',
1.598     www      9297:                     		linktitle => 'Grade current resource for a selection of students.'
                   9298:                         }, 
                   9299:                         {       linktext => 'Grade ungraded submissions.',
                   9300:                                 url => $url1b,
                   9301:                                 permission => 'F',
1.636     wenzelju 9302:                                 icon => 'ungrade_sub.png',
1.598     www      9303:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9304:                         },
1.598     www      9305: 
                   9306:                         {       linktext => 'Grading table',
                   9307:                                 url => $url1c,
                   9308:                                 permission => 'F',
1.636     wenzelju 9309:                                 icon => 'grading_table.png',
1.598     www      9310:                                 linktitle => 'Grade current resource for all students.'
                   9311:                         },
1.615     www      9312:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9313:                                 url => $url1d,
                   9314:                                 permission => 'F',
1.636     wenzelju 9315:                                 icon => 'grade_PageFolder.png',
1.598     www      9316:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9317:                         },
                   9318:                         {       linktext => 'Download submissions',
                   9319:                                 url => $url1e,
                   9320:                                 permission => 'F',
1.636     wenzelju 9321:                                 icon => 'download_sub.png',
1.621     www      9322:                                 linktitle => 'Download all students submissions.'
1.598     www      9323:                         }]},
                   9324:                          { categorytitle=>'Automated Grading',
                   9325:                items =>[
                   9326: 
1.538     schulted 9327:                 	    {	linktext => 'Upload Scores',
                   9328:                     		url => $url2,
                   9329:                     		permission => 'F',
                   9330:                     		icon => 'uploadscores.png',
                   9331:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9332:                 	    },
                   9333:                 	    {	linktext => 'Process Clicker',
                   9334:                     		url => $url3,
                   9335:                     		permission => 'F',
                   9336:                     		icon => 'addClickerInfoFile.png',
                   9337:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9338:                 	    },
1.587     raeburn  9339:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9340:                     		url => $url4,
                   9341:                     		permission => 'F',
1.636     wenzelju 9342:                     		icon => 'bubblesheet.png',
1.648     bisitz   9343:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9344:                 	    },
1.616     www      9345:                             {   linktext => 'Verify Receipt Number',
1.602     www      9346:                                 url => $url5,
                   9347:                                 permission => 'F',
1.636     wenzelju 9348:                                 icon => 'receipt_number.png',
1.602     www      9349:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9350:                             }
                   9351: 
1.538     schulted 9352:                     ]
                   9353:             });
                   9354: 
1.443     banghart 9355:     # Create the menu
                   9356:     my $Str;
1.445     banghart 9357:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9358:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9359:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9360: 
1.602     www      9361:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9362:     return $Str;    
                   9363: }
                   9364: 
1.598     www      9365: 
                   9366: sub ungraded {
                   9367:     my ($request)=@_;
                   9368:     &submit_options($request);
                   9369: }
                   9370: 
1.599     www      9371: sub submit_options_sequence {
1.608     www      9372:     my ($request,$symb) = @_;
1.599     www      9373:     if (!$symb) {return '';}
1.600     www      9374:     &commonJSfunctions($request);
                   9375:     my $result;
1.599     www      9376: 
1.600     www      9377:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9378:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9379:     $result.=&selectfield(0).
1.601     www      9380:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9381:             <div>
                   9382:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9383:             </div>
                   9384:         </div>
                   9385:   </form>';
                   9386:     return $result;
                   9387: }
                   9388: 
                   9389: sub submit_options_table {
1.608     www      9390:     my ($request,$symb) = @_;
1.600     www      9391:     if (!$symb) {return '';}
1.599     www      9392:     &commonJSfunctions($request);
                   9393:     my $result;
                   9394: 
                   9395:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9396:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9397: 
1.632     www      9398:     $result.=&selectfield(0).
1.601     www      9399:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9400:             <div>
                   9401:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9402:             </div>
                   9403:         </div>
                   9404:   </form>';
                   9405:     return $result;
                   9406: }
1.443     banghart 9407: 
1.621     www      9408: sub submit_options_download {
                   9409:     my ($request,$symb) = @_;
                   9410:     if (!$symb) {return '';}
                   9411: 
                   9412:     &commonJSfunctions($request);
                   9413: 
                   9414:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9415:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9416:     $result.='
                   9417: <h2>
                   9418:   '.&mt('Select Students for Which to Download Submissions').'
                   9419: </h2>'.&selectfield(1).'
                   9420:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9421:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9422:             </div>
                   9423:           </div>
1.600     www      9424: 
                   9425: 
1.621     www      9426:   </form>';
                   9427:     return $result;
                   9428: }
                   9429: 
1.443     banghart 9430: #--- Displays the submissions first page -------
                   9431: sub submit_options {
1.608     www      9432:     my ($request,$symb) = @_;
1.72      ng       9433:     if (!$symb) {return '';}
                   9434: 
1.118     ng       9435:     &commonJSfunctions($request);
1.473     albertel 9436:     my $result;
1.533     bisitz   9437: 
1.72      ng       9438:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9439: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9440:     $result.=&selectfield(1).'
1.601     www      9441:                 <input type="hidden" name="command" value="submission" /> 
                   9442: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9443:             </div>
                   9444:           </div>
                   9445: 
                   9446: 
                   9447:   </form>';
                   9448:     return $result;
                   9449: }
1.533     bisitz   9450: 
1.601     www      9451: sub selectfield {
                   9452:    my ($full)=@_;
1.635     raeburn  9453:    my %options = 
                   9454:           (&Apache::lonlocal::texthash(
                   9455:              'yes'       => 'with submissions',
                   9456:              'queued'    => 'in grading queue',
                   9457:              'graded'    => 'with ungraded submissions',
                   9458:              'incorrect' => 'with incorrect submissions',
                   9459:              'all'       => 'with any status'),
                   9460:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9461:    my $result='<div class="LC_columnSection">
1.537     harmsja  9462:   
1.533     bisitz   9463:     <fieldset>
                   9464:       <legend>
                   9465:        '.&mt('Sections').'
                   9466:       </legend>
1.601     www      9467:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9468:     </fieldset>
1.537     harmsja  9469:   
1.533     bisitz   9470:     <fieldset>
                   9471:       <legend>
                   9472:         '.&mt('Groups').'
                   9473:       </legend>
                   9474:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9475:     </fieldset>
1.537     harmsja  9476:   
1.533     bisitz   9477:     <fieldset>
                   9478:       <legend>
                   9479:         '.&mt('Access Status').'
                   9480:       </legend>
1.601     www      9481:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9482:     </fieldset>';
                   9483:     if ($full) {
                   9484:        $result.='
1.533     bisitz   9485:     <fieldset>
                   9486:       <legend>
                   9487:         '.&mt('Submission Status').'
1.601     www      9488:       </legend>'.
1.635     raeburn  9489:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9490:    '</fieldset>';
                   9491:     }
                   9492:     $result.='</div><br />';
1.44      ng       9493:     return $result;
1.2       albertel 9494: }
                   9495: 
1.285     albertel 9496: sub reset_perm {
                   9497:     undef(%perm);
                   9498: }
                   9499: 
                   9500: sub init_perm {
                   9501:     &reset_perm();
1.300     albertel 9502:     foreach my $test_perm ('vgr','mgr','opa') {
                   9503: 
                   9504: 	my $scope = $env{'request.course.id'};
                   9505: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9506: 
                   9507: 	    $scope .= '/'.$env{'request.course.sec'};
                   9508: 	    if ( $perm{$test_perm}=
                   9509: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9510: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9511: 	    } else {
                   9512: 		delete($perm{$test_perm});
                   9513: 	    }
1.285     albertel 9514: 	}
                   9515:     }
                   9516: }
                   9517: 
1.674     raeburn  9518: sub init_old_essays {
                   9519:     my ($symb,$apath,$adom,$aname) = @_;
                   9520:     if ($symb ne '') {
                   9521:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9522:         if (keys(%essays) > 0) {
                   9523:             $old_essays{$symb} = \%essays;
                   9524:         }
                   9525:     }
                   9526:     return;
                   9527: }
                   9528: 
                   9529: sub reset_old_essays {
                   9530:     undef(%old_essays);
                   9531: }
                   9532: 
1.400     www      9533: sub gather_clicker_ids {
1.408     albertel 9534:     my %clicker_ids;
1.400     www      9535: 
                   9536:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9537: 
                   9538:     # Set up a couple variables.
1.407     albertel 9539:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9540:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9541:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9542: 
1.407     albertel 9543:     foreach my $student (keys(%$classlist)) {
1.438     www      9544:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9545:         my $username = $classlist->{$student}->[$username_idx];
                   9546:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9547:         my $clickers =
1.408     albertel 9548: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9549:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9550:             $id=~s/^[\#0]+//;
1.421     www      9551:             $id=~s/[\-\:]//g;
1.407     albertel 9552:             if (exists($clicker_ids{$id})) {
1.408     albertel 9553: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9554:             } else {
1.408     albertel 9555: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9556:             }
                   9557:         }
                   9558:     }
1.407     albertel 9559:     return %clicker_ids;
1.400     www      9560: }
                   9561: 
1.402     www      9562: sub gather_adv_clicker_ids {
1.408     albertel 9563:     my %clicker_ids;
1.402     www      9564:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9565:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9566:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9567:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9568:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9569:             my ($puname,$pudom)=split(/\:/,$person);
                   9570:             my $clickers =
1.408     albertel 9571: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9572:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9573: 		$id=~s/^[\#0]+//;
1.421     www      9574:                 $id=~s/[\-\:]//g;
1.408     albertel 9575: 		if (exists($clicker_ids{$id})) {
                   9576: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9577: 		} else {
                   9578: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9579: 		}
1.405     www      9580:             }
1.402     www      9581:         }
                   9582:     }
1.407     albertel 9583:     return %clicker_ids;
1.402     www      9584: }
                   9585: 
1.413     www      9586: sub clicker_grading_parameters {
                   9587:     return ('gradingmechanism' => 'scalar',
                   9588:             'upfiletype' => 'scalar',
                   9589:             'specificid' => 'scalar',
                   9590:             'pcorrect' => 'scalar',
                   9591:             'pincorrect' => 'scalar');
                   9592: }
                   9593: 
1.400     www      9594: sub process_clicker {
1.608     www      9595:     my ($r,$symb)=@_;
1.400     www      9596:     if (!$symb) {return '';}
                   9597:     my $result=&checkforfile_js();
1.632     www      9598:     $result.=&Apache::loncommon::start_data_table().
                   9599:              &Apache::loncommon::start_data_table_header_row().
                   9600:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9601:              &Apache::loncommon::end_data_table_header_row().
                   9602:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9603: # Attempt to restore parameters from last session, set defaults if not present
                   9604:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9605:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9606:                                                  \%Saveable_Parameters);
                   9607:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9608:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9609:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9610:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9611: 
                   9612:     my %checked;
1.521     www      9613:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9614:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9615:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9616:        }
                   9617:     }
                   9618: 
1.632     www      9619:     my $upload=&mt("Evaluate File");
1.400     www      9620:     my $type=&mt("Type");
1.402     www      9621:     my $attendance=&mt("Award points just for participation");
                   9622:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9623:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9624:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9625:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9626:     my $pcorrect=&mt("Percentage points for correct solution");
                   9627:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9628:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9629: 						   {'iclicker' => 'i>clicker',
1.666     www      9630:                                                     'interwrite' => 'interwrite PRS',
                   9631:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9632:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9633:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9634: function sanitycheck() {
                   9635: // Accept only integer percentages
                   9636:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9637:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9638: // Find out grading choice
                   9639:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9640:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9641:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9642:       }
                   9643:    }
                   9644: // By default, new choice equals user selection
                   9645:    newgradingchoice=gradingchoice;
                   9646: // Not good to give more points for false answers than correct ones
                   9647:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9648:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9649:    }
                   9650: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9651:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9652:       document.forms.gradesupload.pcorrect.value=100;
                   9653:       document.forms.gradesupload.pincorrect.value=100;
                   9654:    }
                   9655: // If the values are different, cannot be attendance only
                   9656:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9657:        (gradingchoice=='attendance')) {
                   9658:        newgradingchoice='personnel';
                   9659:    }
                   9660: // Change grading choice to new one
                   9661:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9662:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9663:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9664:       } else {
                   9665:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9666:       }
                   9667:    }
                   9668: // Remember the old state
                   9669:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9670: }
1.597     wenzelju 9671: ENDUPFORM
                   9672:     $result.= <<ENDUPFORM;
1.400     www      9673: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9674: <input type="hidden" name="symb" value="$symb" />
                   9675: <input type="hidden" name="command" value="processclickerfile" />
                   9676: <input type="file" name="upfile" size="50" />
                   9677: <br /><label>$type: $selectform</label>
1.632     www      9678: ENDUPFORM
                   9679:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9680:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9681:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9682: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9683: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9684: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9685: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9686: <br />&nbsp;&nbsp;&nbsp;
                   9687: <input type="text" name="givenanswer" size="50" />
1.413     www      9688: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9689: ENDGRADINGFORM
                   9690:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9691:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9692:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9693: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9694: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9695: </form>'
1.632     www      9696: ENDPERCFORM
                   9697:     $result.='</td>'.
                   9698:              &Apache::loncommon::end_data_table_row().
                   9699:              &Apache::loncommon::end_data_table();
1.400     www      9700:     return $result;
                   9701: }
                   9702: 
                   9703: sub process_clicker_file {
1.608     www      9704:     my ($r,$symb)=@_;
1.400     www      9705:     if (!$symb) {return '';}
1.413     www      9706: 
                   9707:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9708:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9709:                                               \%Saveable_Parameters);
1.598     www      9710:     my $result='';
1.404     www      9711:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9712: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9713: 	return $result;
1.404     www      9714:     }
1.522     www      9715:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9716:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9717:         return $result;
1.521     www      9718:     }
1.522     www      9719:     my $foundgiven=0;
1.521     www      9720:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9721:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9722:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9723:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9724:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9725:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9726:         $foundgiven=$#answers+1;
1.521     www      9727:     }
1.407     albertel 9728:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9729:     my %correct_ids;
1.404     www      9730:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9731: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9732:     }
                   9733:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9734: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9735: 	   $correct_id=~tr/a-z/A-Z/;
                   9736: 	   $correct_id=~s/\s//gs;
                   9737: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9738:            $correct_id=~s/[\-\:]//g;
1.414     www      9739:            if ($correct_id) {
                   9740: 	      $correct_ids{$correct_id}='specified';
                   9741:            }
                   9742:         }
1.400     www      9743:     }
1.404     www      9744:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9745: 	$result.=&mt('Score based on attendance only');
1.521     www      9746:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9747:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9748:     } else {
1.408     albertel 9749: 	my $number=0;
1.411     www      9750: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9751: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9752: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9753: 	    if ($correct_ids{$id} eq 'specified') {
                   9754: 		$result.=&mt('specified');
                   9755: 	    } else {
                   9756: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9757: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9758: 	    }
                   9759: 	    $number++;
                   9760: 	}
1.411     www      9761:         $result.="</p>\n";
1.710     bisitz   9762:         if ($number==0) {
                   9763:             $result .=
                   9764:                  &Apache::lonhtmlcommon::confirm_success(
                   9765:                      &mt('No IDs found to determine correct answer'),1);
                   9766:             return $result;
                   9767:         }
1.404     www      9768:     }
1.405     www      9769:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9770:         $result .=
                   9771:             &Apache::lonhtmlcommon::confirm_success(
                   9772:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9773:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9774:         return $result;
1.405     www      9775:     }
1.410     www      9776: 
                   9777: # Were able to get all the info needed, now analyze the file
                   9778: 
1.411     www      9779:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9780:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9781:     $result.=&Apache::loncommon::start_data_table().
                   9782:              &Apache::loncommon::start_data_table_header_row().
                   9783:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9784:              &Apache::loncommon::end_data_table_header_row().
                   9785:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9786: <td>
1.410     www      9787: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9788: <input type="hidden" name="symb" value="$symb" />
                   9789: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9790: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9791: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9792: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9793: ENDHEADER
1.522     www      9794:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9795:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9796:     } 
1.408     albertel 9797:     my %responses;
                   9798:     my @questiontitles;
1.405     www      9799:     my $errormsg='';
                   9800:     my $number=0;
                   9801:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9802: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9803:     }
1.419     www      9804:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9805:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9806:     }
1.666     www      9807:     if ($env{'form.upfiletype'} eq 'turning') {
                   9808:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9809:     }
1.411     www      9810:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9811:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9812:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9813:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9814:              '<br />';
1.522     www      9815:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9816:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9817:        return $result;
1.522     www      9818:     } 
1.414     www      9819: # Remember Question Titles
                   9820: # FIXME: Possibly need delimiter other than ":"
                   9821:     for (my $i=0;$i<$number;$i++) {
                   9822:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9823:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9824:     }
1.411     www      9825:     my $correct_count=0;
                   9826:     my $student_count=0;
                   9827:     my $unknown_count=0;
1.414     www      9828: # Match answers with usernames
                   9829: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9830:     foreach my $id (keys(%responses)) {
1.410     www      9831:        if ($correct_ids{$id}) {
1.414     www      9832:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9833:           $correct_count++;
1.410     www      9834:        } elsif ($clicker_ids{$id}) {
1.437     www      9835:           if ($clicker_ids{$id}=~/\,/) {
                   9836: # More than one user with the same clicker!
1.632     www      9837:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9838:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9839:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9840:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9841:                            "<select name='multi".$id."'>";
                   9842:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9843:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9844:              }
                   9845:              $result.='</select>';
                   9846:              $unknown_count++;
                   9847:           } else {
                   9848: # Good: found one and only one user with the right clicker
                   9849:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9850:              $student_count++;
                   9851:           }
1.410     www      9852:        } else {
1.632     www      9853:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9854:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9855:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9856:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9857:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9858:                    "\n".&mt("Domain").": ".
                   9859:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9860:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9861:           $unknown_count++;
1.410     www      9862:        }
1.405     www      9863:     }
1.412     www      9864:     $result.='<hr />'.
                   9865:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9866:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9867:        if ($correct_count==0) {
1.696     bisitz   9868:           $errormsg.="Found no correct answers for grading!";
1.412     www      9869:        } elsif ($correct_count>1) {
1.414     www      9870:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9871:        }
                   9872:     }
1.428     www      9873:     if ($number<1) {
                   9874:        $errormsg.="Found no questions.";
                   9875:     }
1.412     www      9876:     if ($errormsg) {
                   9877:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9878:     } else {
                   9879:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9880:     }
1.632     www      9881:     $result.='</form></td>'.
                   9882:              &Apache::loncommon::end_data_table_row().
                   9883:              &Apache::loncommon::end_data_table();
1.614     www      9884:     return $result;
1.400     www      9885: }
                   9886: 
1.405     www      9887: sub iclicker_eval {
1.406     www      9888:     my ($questiontitles,$responses)=@_;
1.405     www      9889:     my $number=0;
                   9890:     my $errormsg='';
                   9891:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9892:         my %components=&Apache::loncommon::record_sep($line);
                   9893:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9894: 	if ($entries[0] eq 'Question') {
                   9895: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9896: 		$$questiontitles[$number]=$entries[$i];
                   9897: 		$number++;
                   9898: 	    }
                   9899: 	}
                   9900: 	if ($entries[0]=~/^\#/) {
                   9901: 	    my $id=$entries[0];
                   9902: 	    my @idresponses;
                   9903: 	    $id=~s/^[\#0]+//;
                   9904: 	    for (my $i=0;$i<$number;$i++) {
                   9905: 		my $idx=3+$i*6;
1.644     www      9906:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9907: 		push(@idresponses,$entries[$idx]);
                   9908: 	    }
                   9909: 	    $$responses{$id}=join(',',@idresponses);
                   9910: 	}
1.405     www      9911:     }
                   9912:     return ($errormsg,$number);
                   9913: }
                   9914: 
1.419     www      9915: sub interwrite_eval {
                   9916:     my ($questiontitles,$responses)=@_;
                   9917:     my $number=0;
                   9918:     my $errormsg='';
1.420     www      9919:     my $skipline=1;
                   9920:     my $questionnumber=0;
                   9921:     my %idresponses=();
1.419     www      9922:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9923:         my %components=&Apache::loncommon::record_sep($line);
                   9924:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9925:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9926:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9927:         next if $skipline;
                   9928:         if ($entries[0]!=$questionnumber) {
                   9929:            $questionnumber=$entries[0];
                   9930:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9931:            $number++;
1.419     www      9932:         }
1.420     www      9933:         my $id=$entries[4];
                   9934:         $id=~s/^[\#0]+//;
1.421     www      9935:         $id=~s/^v\d*\://i;
                   9936:         $id=~s/[\-\:]//g;
1.420     www      9937:         $idresponses{$id}[$number]=$entries[6];
                   9938:     }
1.524     raeburn  9939:     foreach my $id (keys(%idresponses)) {
1.420     www      9940:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9941:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9942:     }
                   9943:     return ($errormsg,$number);
                   9944: }
                   9945: 
1.666     www      9946: sub turning_eval {
                   9947:     my ($questiontitles,$responses)=@_;
                   9948:     my $number=0;
                   9949:     my $errormsg='';
                   9950:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9951:         my %components=&Apache::loncommon::record_sep($line);
                   9952:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9953:         if ($#entries>$number) { $number=$#entries; }
                   9954:         my $id=$entries[0];
                   9955:         my @idresponses;
                   9956:         $id=~s/^[\#0]+//;
                   9957:         unless ($id) { next; }
                   9958:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9959:             $entries[$idx]=~s/\,/\;/g;
                   9960:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9961:             push(@idresponses,$entries[$idx]);
                   9962:         }
                   9963:         $$responses{$id}=join(',',@idresponses);
                   9964:     }
                   9965:     for (my $i=1; $i<=$number; $i++) {
                   9966:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9967:     }
                   9968:     return ($errormsg,$number);
                   9969: }
                   9970: 
                   9971: 
1.414     www      9972: sub assign_clicker_grades {
1.608     www      9973:     my ($r,$symb)=@_;
1.414     www      9974:     if (!$symb) {return '';}
1.416     www      9975: # See which part we are saving to
1.582     raeburn  9976:     my $res_error;
                   9977:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9978:     if ($res_error) {
                   9979:         return &navmap_errormsg();
                   9980:     }
1.416     www      9981: # FIXME: This should probably look for the first handgradeable part
                   9982:     my $part=$$partlist[0];
                   9983: # Start screen output
1.632     www      9984:     my $result=&Apache::loncommon::start_data_table().
                   9985:              &Apache::loncommon::start_data_table_header_row().
                   9986:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9987:              &Apache::loncommon::end_data_table_header_row().
                   9988:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9989: # Get correct result
                   9990: # FIXME: Possibly need delimiter other than ":"
                   9991:     my @correct=();
1.415     www      9992:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9993:     my $number=$env{'form.number'};
                   9994:     if ($gradingmechanism ne 'attendance') {
1.414     www      9995:        foreach my $key (keys(%env)) {
                   9996:           if ($key=~/^form\.correct\:/) {
                   9997:              my @input=split(/\,/,$env{$key});
                   9998:              for (my $i=0;$i<=$#input;$i++) {
                   9999:                  if (($correct[$i]) && ($input[$i]) &&
                   10000:                      ($correct[$i] ne $input[$i])) {
                   10001:                     $result.='<br /><span class="LC_warning">'.
                   10002:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10003:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10004:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10005:                     $correct[$i]=$input[$i];
                   10006:                  }
                   10007:              }
                   10008:           }
                   10009:        }
1.415     www      10010:        for (my $i=0;$i<$number;$i++) {
1.644     www      10011:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10012:              $result.='<br /><span class="LC_error">'.
                   10013:                       &mt('No correct result given for question "[_1]"!',
                   10014:                           $env{'form.question:'.$i}).'</span>';
                   10015:           }
                   10016:        }
1.644     www      10017:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10018:     }
                   10019: # Start grading
1.415     www      10020:     my $pcorrect=$env{'form.pcorrect'};
                   10021:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10022:     my $storecount=0;
1.632     www      10023:     my %users=();
1.415     www      10024:     foreach my $key (keys(%env)) {
1.420     www      10025:        my $user='';
1.415     www      10026:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10027:           $user=$1;
                   10028:        }
                   10029:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10030:           my $id=$1;
                   10031:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10032:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10033:           } elsif ($env{'form.multi'.$id}) {
                   10034:              $user=$env{'form.multi'.$id};
1.420     www      10035:           }
                   10036:        }
1.632     www      10037:        if ($user) {
                   10038:           if ($users{$user}) {
                   10039:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10040:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10041:                       '</span><br />';
                   10042:           }
                   10043:           $users{$user}=1; 
1.415     www      10044:           my @answer=split(/\,/,$env{$key});
                   10045:           my $sum=0;
1.522     www      10046:           my $realnumber=$number;
1.415     www      10047:           for (my $i=0;$i<$number;$i++) {
1.576     www      10048:              if  ($correct[$i] eq '-') {
                   10049:                 $realnumber--;
1.644     www      10050:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10051:                 if ($gradingmechanism eq 'attendance') {
                   10052:                    $sum+=$pcorrect;
1.576     www      10053:                 } elsif ($correct[$i] eq '*') {
1.522     www      10054:                    $sum+=$pcorrect;
1.415     www      10055:                 } else {
1.644     www      10056: # We actually grade if correct or not
                   10057:                    my $increment=$pincorrect;
                   10058: # Special case: numerical answer "0"
                   10059:                    if ($correct[$i] eq '0') {
                   10060:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10061:                          $increment=$pcorrect;
                   10062:                       }
                   10063: # General numerical answer, both evaluate to something non-zero
                   10064:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10065:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10066:                          $increment=$pcorrect;
                   10067:                       }
                   10068: # Must be just alphanumeric
                   10069:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10070:                       $increment=$pcorrect;
1.415     www      10071:                    }
1.644     www      10072:                    $sum+=$increment;
1.415     www      10073:                 }
                   10074:              }
                   10075:           }
1.522     www      10076:           my $ave=$sum/(100*$realnumber);
1.416     www      10077: # Store
                   10078:           my ($username,$domain)=split(/\:/,$user);
                   10079:           my %grades=();
                   10080:           $grades{"resource.$part.solved"}='correct_by_override';
                   10081:           $grades{"resource.$part.awarded"}=$ave;
                   10082:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10083:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10084:                                                  $env{'request.course.id'},
                   10085:                                                  $domain,$username);
                   10086:           if ($returncode ne 'ok') {
                   10087:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10088:           } else {
                   10089:              $storecount++;
                   10090:           }
1.415     www      10091:        }
                   10092:     }
                   10093: # We are done
1.549     hauer    10094:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10095:              '</td>'.
                   10096:              &Apache::loncommon::end_data_table_row().
                   10097:              &Apache::loncommon::end_data_table();
1.614     www      10098:     return $result;
1.414     www      10099: }
                   10100: 
1.582     raeburn  10101: sub navmap_errormsg {
                   10102:     return '<div class="LC_error">'.
                   10103:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10104:            &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  10105:            '</div>';
                   10106: }
1.607     droeschl 10107: 
1.609     www      10108: sub startpage {
1.671     raeburn  10109:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10110:     if ($nomenu) {
                   10111:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10112:     } else {
                   10113:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10114:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10115:                                                  {'bread_crumbs' => $crumbs}));
                   10116:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10117:     }
1.613     www      10118:     unless ($nodisplayflag) {
1.671     raeburn  10119:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10120:     }
1.607     droeschl 10121: }
1.582     raeburn  10122: 
1.622     www      10123: sub select_problem {
                   10124:     my ($r)=@_;
1.632     www      10125:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10126:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10127:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10128:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10129: }
                   10130: 
1.1       albertel 10131: sub handler {
1.41      ng       10132:     my $request=$_[0];
1.434     albertel 10133:     &reset_caches();
1.646     raeburn  10134:     if ($request->header_only) {
                   10135:         &Apache::loncommon::content_type($request,'text/html');
                   10136:         $request->send_http_header;
                   10137:         return OK;
                   10138:     }
                   10139:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10140: 
1.664     raeburn  10141: # see what command we need to execute
                   10142: 
                   10143:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10144:     my $command=$commands[0];
                   10145: 
1.646     raeburn  10146:     &init_perm();
                   10147:     if (!$env{'request.course.id'}) {
1.664     raeburn  10148:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10149:                 ($command =~ /^scantronupload/)) {
                   10150:             # Not in a course.
                   10151:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10152:             return HTTP_NOT_ACCEPTABLE;
                   10153:         }
1.646     raeburn  10154:     } elsif (!%perm) {
                   10155:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10156:         return OK;
1.41      ng       10157:     }
1.646     raeburn  10158:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10159:     $request->send_http_header;
1.646     raeburn  10160: 
1.160     albertel 10161:     if ($#commands > 0) {
                   10162: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10163:     }
1.608     www      10164: 
                   10165: # see what the symb is
                   10166: 
                   10167:     my $symb=$env{'form.symb'};
                   10168:     unless ($symb) {
                   10169:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10170:        $symb=&Apache::lonnet::symbread($url);
                   10171:     }
1.646     raeburn  10172:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10173: 
1.513     foxr     10174:     $ssi_error = 0;
1.637     www      10175:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10176: #
1.637     www      10177: # Not called from a resource, but inside a course
1.601     www      10178: #    
1.622     www      10179:         &startpage($request,undef,[],1,1);
                   10180:         &select_problem($request);
1.41      ng       10181:     } else {
1.104     albertel 10182: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10183:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10184:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10185:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10186:                     &choose_task_version_form($symb,$env{'form.student'},
                   10187:                                               $env{'form.userdom'});
                   10188:             }
                   10189:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10190:             if ($versionform) {
                   10191:                 $request->print($versionform);
                   10192:             }
                   10193:             $request->print('<br clear="all" />');
1.611     www      10194: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10195:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10196:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10197:                 &choose_task_version_form($symb,$env{'form.student'},
                   10198:                                           $env{'form.userdom'},
                   10199:                                           $env{'form.inhibitmenu'});
                   10200:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10201:             if ($versionform) {
                   10202:                 $request->print($versionform);
                   10203:             }
                   10204:             $request->print('<br clear="all" />');
                   10205:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10206: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10208:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10209: 	    &pickStudentPage($request,$symb);
1.103     albertel 10210: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10211:             &startpage($request,$symb,
                   10212:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10213:                                        {href=>'',text=>'Select student'},
                   10214:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10215: 	    &displayPage($request,$symb);
1.104     albertel 10216: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10218:                                        {href=>'',text=>'Select student'},
                   10219:                                        {href=>'',text=>'Grade student'},
                   10220:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10221: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10222: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10223:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10224:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10225: 	    &processGroup($request,$symb);
1.104     albertel 10226: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10227:             &startpage($request,$symb);
                   10228: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10229: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10230:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10231: 	    $request->print(&submit_options($request,$symb));
1.598     www      10232:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10233:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10234:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10235:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10236:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10237:             $request->print(&submit_options_table($request,$symb));
1.598     www      10238:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10239:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10240:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10241: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10243: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10244: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10245:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10246:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10247: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10248: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10249:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10250:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10251:                                                                              text=>"Modify grades"},
                   10252:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10253: 	    $request->print(&editgrades($request,$symb));
1.602     www      10254:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10255:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10256:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10257: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10258:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10259:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10260: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10261:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10262:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10263:             $request->print(&process_clicker($request,$symb));
1.400     www      10264:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10265:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10266:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10267:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10268:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10269:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10270:                                        {href=>'', text=>'Process clicker file'},
                   10271:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10272:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10273: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10274:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10275: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10276: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10277:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10278: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10279: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10280:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10281: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10282: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10283: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10284:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10285: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10286: 	    } else {
1.257     albertel 10287: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10288: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10289: 		} else {
1.257     albertel 10290: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10291: 		}
1.627     www      10292:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10293: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10294: 	    }
1.246     albertel 10295: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10296:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10297: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10298: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10299:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10300: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10301:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10302:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10303:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10304: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10305:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10306: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10307: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10308:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10309: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10310:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10311:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10312: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10314:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10315:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10316:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10317: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10319:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10320:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10321: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10322:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10323:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10324:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10326:             $request->print(&checkscantron_results($request,$symb));
                   10327:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10328:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10329:             $request->print(&submit_options_download($request,$symb));
                   10330:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10331:             &startpage($request,$symb,
                   10332:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10333:     {href=>'', text=>'Download submissions'}]);
                   10334:             &submit_download_link($request,$symb);
1.106     albertel 10335: 	} elsif ($command) {
1.620     www      10336:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10337: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10338: 	}
1.2       albertel 10339:     }
1.513     foxr     10340:     if ($ssi_error) {
                   10341: 	&ssi_print_error($request);
                   10342:     }
1.671     raeburn  10343:     if ($env{'form.inhibitmenu'}) {
                   10344:         $request->print(&Apache::loncommon::end_page());
                   10345:     } else {
                   10346:         &Apache::lonquickgrades::endGradeScreen($request);
                   10347:     }
1.434     albertel 10348:     &reset_caches();
1.646     raeburn  10349:     return OK;
1.44      ng       10350: }
                   10351: 
1.1       albertel 10352: 1;
                   10353: 
1.13      albertel 10354: __END__;
1.531     jms      10355: 
                   10356: 
                   10357: =head1 NAME
                   10358: 
                   10359: Apache::grades
                   10360: 
                   10361: =head1 SYNOPSIS
                   10362: 
                   10363: Handles the viewing of grades.
                   10364: 
                   10365: This is part of the LearningOnline Network with CAPA project
                   10366: described at http://www.lon-capa.org.
                   10367: 
                   10368: =head1 OVERVIEW
                   10369: 
                   10370: Do an ssi with retries:
1.715     bisitz   10371: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10372: 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
                   10373: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10374: 
                   10375: At least the logic that drives this has been pulled out into loncommon.
                   10376: 
                   10377: 
                   10378: 
                   10379: ssi_with_retries - Does the server side include of a resource.
                   10380:                      if the ssi call returns an error we'll retry it up to
                   10381:                      the number of times requested by the caller.
1.715     bisitz   10382:                      If we still have a problem, no text is appended to the
1.531     jms      10383:                      output and we set some global variables.
                   10384:                      to indicate to the caller an SSI error occurred.  
                   10385:                      All of this is supposed to deal with the issues described
1.715     bisitz   10386:                      in LON-CAPA BZ 5631 see:
1.531     jms      10387:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10388:                      by informing the user that this happened.
                   10389: 
                   10390: Parameters:
                   10391:   resource   - The resource to include.  This is passed directly, without
                   10392:                interpretation to lonnet::ssi.
                   10393:   form       - The form hash parameters that guide the interpretation of the resource
                   10394:                
                   10395:   retries    - Number of retries allowed before giving up completely.
                   10396: Returns:
                   10397:   On success, returns the rendered resource identified by the resource parameter.
                   10398: Side Effects:
                   10399:   The following global variables can be set:
                   10400:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10401:                               It is up to the caller to initialize this to false
                   10402:                               if desired.
                   10403:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10404:                               of the resource that could not be rendered by the ssi
                   10405:                               call.
                   10406:    ssi_error_message   - The error string fetched from the ssi response
                   10407:                               in the event of an error.
                   10408: 
                   10409: 
                   10410: =head1 HANDLER SUBROUTINE
                   10411: 
                   10412: ssi_with_retries()
                   10413: 
                   10414: =head1 SUBROUTINES
                   10415: 
                   10416: =over
                   10417: 
1.671     raeburn  10418: =head1 Routines to display previous version of a Task for a specific student
                   10419: 
                   10420: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10421: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10422: requires a proctor to check-in the student, a new version of the Task will
                   10423: be created when the student is checked in to the new opportunity.
                   10424: 
                   10425: If a particular student has tried two or more versions of a particular task,
                   10426: the submission screen provides a user with vgr privileges (e.g., a Course
                   10427: Coordinator) the ability to display a previous version worked on by the
                   10428: student.  By default, the current version is displayed. If a previous version
                   10429: has been selected for display, submission data are only shown that pertain
                   10430: to that particular version, and the interface to submit grades is not shown.
                   10431: 
                   10432: =over 4
                   10433: 
                   10434: =item show_previous_task_version()
                   10435: 
                   10436: Displays a specified version of a student's Task, as the student sees it.
                   10437: 
                   10438: Inputs: 2
                   10439:         request - request object
                   10440:         symb    - unique symb for current instance of resource
                   10441: 
                   10442: Output: None.
                   10443: 
                   10444: Side Effects: calls &show_problem() to print version of Task, with
                   10445:               version contained in form item: $env{'form.previousversion'}
                   10446: 
                   10447: =item choose_task_version_form()
                   10448: 
                   10449: Displays a web form used to select which version of a student's view of a
                   10450: Task should be displayed.  Either launches a pop-up window, or replaces
                   10451: content in existing pop-up, or replaces page in main window.
                   10452: 
                   10453: Inputs: 4
                   10454:         symb    - unique symb for current instance of resource
                   10455:         uname   - username of student
                   10456:         udom    - domain of student
                   10457:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10458:                   breadcrumbs etc., are displayed
                   10459: 
                   10460: Output: 4
                   10461:         current   - student's current version
                   10462:         displayed - student's version being displayed
                   10463:         result    - scalar containing HTML for web form used to switch to
                   10464:                     a different version (or a link to close window, if pop-up).
                   10465:         js        - javascript for processing selection in versions web form
                   10466: 
                   10467: Side Effects: None.
                   10468: 
                   10469: =item previous_display_javascript()
                   10470: 
                   10471: Inputs: 2
                   10472:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10473:                   breadcrumbs etc., are displayed.
                   10474:         current - student's current version number.
                   10475: 
                   10476: Output: 1
                   10477:         js      - javascript for processing selection in versions web form.
                   10478: 
                   10479: Side Effects: None.
                   10480: 
                   10481: =back
                   10482: 
                   10483: =head1 Routines to process bubblesheet data.
                   10484: 
                   10485: =over 4
                   10486: 
1.531     jms      10487: =item scantron_get_correction() : 
                   10488: 
                   10489:    Builds the interface screen to interact with the operator to fix a
                   10490:    specific error condition in a specific scanline
                   10491: 
                   10492:  Arguments:
                   10493:     $r           - Apache request object
                   10494:     $i           - number of the current scanline
                   10495:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10496:     $scan_config - hash ref as returned from &get_scantron_config()
                   10497:     $line        - full contents of the current scanline
                   10498:     $error       - error condition, valid values are
                   10499:                    'incorrectCODE', 'duplicateCODE',
                   10500:                    'doublebubble', 'missingbubble',
                   10501:                    'duplicateID', 'incorrectID'
                   10502:     $arg         - extra information needed
                   10503:        For errors:
                   10504:          - duplicateID   - paper number that this studentID was seen before on
                   10505:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10506:                            seen on before
                   10507:          - incorrectCODE - current incorrect CODE 
                   10508:          - doublebubble  - array ref of the bubble lines that have double
                   10509:                            bubble errors
                   10510:          - missingbubble - array ref of the bubble lines that have missing
                   10511:                            bubble errors
                   10512: 
1.691     raeburn  10513:    $randomorder - True if exam folder has randomorder set
                   10514:    $randompick  - True if exam folder has randompick set
                   10515:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10516:                      for current line to question number used for same question
                   10517:                      in "Master Seqence" (as seen by Course Coordinator).
                   10518:    $startline   - Reference to hash where key is question number (0 is first)
                   10519:                   and value is number of first bubble line for current student
                   10520:                   or code-based randompick and/or randomorder.
                   10521: 
                   10522: 
                   10523: 
1.531     jms      10524: =item  scantron_get_maxbubble() : 
                   10525: 
1.582     raeburn  10526:    Arguments:
                   10527:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10528:                       failure to retrieve a navmap object.
                   10529:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10530:        calling routine should trap the error condition and display the warning
                   10531:        found in &navmap_errormsg().
                   10532: 
1.649     raeburn  10533:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10534: 
1.531     jms      10535:    Returns the maximum number of bubble lines that are expected to
                   10536:    occur. Does this by walking the selected sequence rendering the
                   10537:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10538:    for what the current value of the problem counter is.
                   10539: 
                   10540:    Caches the results to $env{'form.scantron_maxbubble'},
                   10541:    $env{'form.scantron.bubble_lines.n'}, 
                   10542:    $env{'form.scantron.first_bubble_line.n'} and
                   10543:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10544:    which are the total number of bubble lines, the number of bubble
1.531     jms      10545:    lines for response n and number of the first bubble line for response n,
                   10546:    and a comma separated list of numbers of bubble lines for sub-questions
                   10547:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10548: 
                   10549: 
                   10550: =item  scantron_validate_missingbubbles() : 
                   10551: 
                   10552:    Validates all scanlines in the selected file to not have any
                   10553:     answers that don't have bubbles that have not been verified
                   10554:     to be bubble free.
                   10555: 
                   10556: =item  scantron_process_students() : 
                   10557: 
1.659     raeburn  10558:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10559: 
                   10560:    The parsed scanline hash is added to %env 
                   10561: 
                   10562:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10563:    foreach resource , with the form data of
                   10564: 
                   10565: 	'submitted'     =>'scantron' 
                   10566: 	'grade_target'  =>'grade',
                   10567: 	'grade_username'=> username of student
                   10568: 	'grade_domain'  => domain of student
                   10569: 	'grade_courseid'=> of course
                   10570: 	'grade_symb'    => symb of resource to grade
                   10571: 
                   10572:     This triggers a grading pass. The problem grading code takes care
                   10573:     of converting the bubbled letter information (now in %env) into a
                   10574:     valid submission.
                   10575: 
                   10576: =item  scantron_upload_scantron_data() :
                   10577: 
1.659     raeburn  10578:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10579: 
                   10580: =item  scantron_upload_scantron_data_save() : 
                   10581: 
                   10582:    Adds a provided bubble information data file to the course if user
                   10583:    has the correct privileges to do so. 
                   10584: 
                   10585: =item  valid_file() :
                   10586: 
                   10587:    Validates that the requested bubble data file exists in the course.
                   10588: 
                   10589: =item  scantron_download_scantron_data() : 
                   10590: 
                   10591:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10592:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10593:    course.
                   10594: 
                   10595: =item  scantron_validate_ID() : 
                   10596: 
                   10597:    Validates all scanlines in the selected file to not have any
1.556     weissno  10598:    invalid or underspecified student/employee IDs
1.531     jms      10599: 
1.582     raeburn  10600: =item navmap_errormsg() :
                   10601: 
                   10602:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10603:    Should be called whenever the request to instantiate a navmap object fails.
                   10604: 
                   10605: =back
1.582     raeburn  10606: 
1.531     jms      10607: =back
                   10608: 
                   10609: =cut

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