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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.716   ! bisitz      4: # $Id: grades.pm,v 1.715 2014/01/29 16:31:20 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.398     albertel 2517: 		'<span class="LC_warning">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 '') {
                   2549:         $request->print("Unable to handle ambiguous references.");
                   2550: 
                   2551:         return '';
                   2552:     }
                   2553:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2554:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2555:     if (!&canview($usec)) {
1.712     bisitz   2556:         $request->print(
                   2557:             '<span class="LC_warning">'.
1.713     bisitz   2558:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2559:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2560:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2561:             '</span>');
1.671     raeburn  2562:         return;
                   2563:     }
                   2564:     my $mode = 'both';
                   2565:     my $isTask = ($symb =~/\.task$/);
                   2566:     if ($isTask) {
                   2567:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2568:             if ($env{'form.fullname'} eq '') {
                   2569:                 $env{'form.fullname'} =
                   2570:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2571:             }
                   2572:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2573:             $request->print("\n\n".
                   2574:                             '<div class="LC_grade_show_user">'.
                   2575:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2576:                             '</h2>'."\n");
                   2577:             &Apache::lonxml::clear_problem_counter();
                   2578:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2579:                             {'previousversion' => $env{'form.previousversion'} }));
                   2580:             $request->print("\n</div>");
                   2581:         }
                   2582:     }
                   2583:     return;
                   2584: }
                   2585: 
                   2586: sub choose_task_version_form {
                   2587:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2588:     my $isTask = ($symb =~/\.task$/);
                   2589:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2590:     if ($isTask) {
                   2591:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2592:                                               $udom,$uname);
                   2593:         if (($record{'resource.0.version'} eq '') ||
                   2594:             ($record{'resource.0.version'} < 2)) {
                   2595:             return ($record{'resource.0.version'},
                   2596:                     $record{'resource.0.version'},$result,$js);
                   2597:         } else {
                   2598:             $current = $record{'resource.0.version'};
                   2599:         }
                   2600:         if ($env{'form.previousversion'}) {
                   2601:             $displayed = $env{'form.previousversion'};
                   2602:             $rowtitle = &mt('Choose another version:')
                   2603:         } else {
                   2604:             $displayed = $current;
                   2605:             $rowtitle = &mt('Show earlier version:');
                   2606:         }
                   2607:         $result = '<div class="LC_left_float">';
                   2608:         my $list;
                   2609:         my $numversions = 0;
                   2610:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2611:             if ($i == $current) {
                   2612:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2613:                     next;
                   2614:                 } else {
                   2615:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2616:                     $numversions ++;
                   2617:                 }
                   2618:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2619:                 unless ($i == $env{'form.previousversion'}) {
                   2620:                     $numversions ++;
                   2621:                 }
                   2622:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2623:             }
                   2624:         }
                   2625:         if ($numversions) {
                   2626:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2627:             $result .=
                   2628:                 '<form name="getprev" method="post" action=""'.
                   2629:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2630:                 &Apache::loncommon::start_data_table().
                   2631:                 &Apache::loncommon::start_data_table_row().
                   2632:                 '<th align="left">'.$rowtitle.'</th>'.
                   2633:                 '<td><select name="version">'.
                   2634:                 '<option>'.&mt('Select').'</option>'.
                   2635:                 $list.
                   2636:                 '</select></td>'.
                   2637:                 &Apache::loncommon::end_data_table_row();
                   2638:             unless ($nomenu) {
                   2639:                 $result .= &Apache::loncommon::start_data_table_row().
                   2640:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2641:                 '<td><span class="LC_nobreak">'.
                   2642:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2643:                 &mt('Yes').'</label>'.
                   2644:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2645:                 '</span></td>'.
                   2646:                 &Apache::loncommon::end_data_table_row();
                   2647:             }
                   2648:             $result .=
                   2649:                 &Apache::loncommon::start_data_table_row().
                   2650:                 '<th align="left">&nbsp;</th>'.
                   2651:                 '<td>'.
                   2652:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2653:                 '</td>'.
                   2654:                 &Apache::loncommon::end_data_table_row().
                   2655:                 &Apache::loncommon::end_data_table().
                   2656:                 '</form>';
                   2657:             $js = &previous_display_javascript($nomenu,$current);
                   2658:         } elsif ($displayed && $nomenu) {
                   2659:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2660:         } else {
                   2661:             $result .= &mt('No previous versions to show for this student');
                   2662:         }
                   2663:         $result .= '</div>';
                   2664:     }
                   2665:     return ($current,$displayed,$result,$js);
                   2666: }
                   2667: 
                   2668: sub previous_display_javascript {
                   2669:     my ($nomenu,$current) = @_;
                   2670:     my $js = <<"JSONE";
                   2671: <script type="text/javascript">
                   2672: // <![CDATA[
                   2673: function previousVersion(uname,udom,symb) {
                   2674:     var current = '$current';
                   2675:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2676:     var prevstr = new RegExp("^\\\\d+\$");
                   2677:     if (!prevstr.test(version)) {
                   2678:         return false;
                   2679:     }
                   2680:     var url = '';
                   2681:     if (version == current) {
                   2682:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2683:     } else {
                   2684:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2685:     }
                   2686: JSONE
                   2687:     if ($nomenu) {
                   2688:         $js .= <<"JSTWO";
                   2689:     document.location.href = url;
                   2690: JSTWO
                   2691:     } else {
                   2692:         $js .= <<"JSTHREE";
                   2693:     var newwin = 0;
                   2694:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2695:         if (document.getprev.prevwin[i].checked == true) {
                   2696:             newwin = document.getprev.prevwin[i].value;
                   2697:         }
                   2698:     }
                   2699:     if (newwin == 1) {
                   2700:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2701:         url = url+'&inhibitmenu=yes';
                   2702:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2703:             previousWin = window.open(url,'',options,1);
                   2704:         } else {
                   2705:             previousWin.location.href = url;
                   2706:         }
                   2707:         previousWin.focus();
                   2708:         return false;
                   2709:     } else {
                   2710:         document.location.href = url;
                   2711:         return false;
                   2712:     }
                   2713: JSTHREE
                   2714:     }
                   2715:     $js .= <<"ENDJS";
                   2716:     return false;
                   2717: }
                   2718: // ]]>
                   2719: </script>
                   2720: ENDJS
                   2721: 
                   2722: }
                   2723: 
1.44      ng       2724: #--- Called from submission routine
1.38      ng       2725: sub processHandGrade {
1.608     www      2726:     my ($request,$symb) = @_;
1.324     albertel 2727:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2728:     my $button = $env{'form.gradeOpt'};
                   2729:     my $ngrade = $env{'form.NCT'};
                   2730:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2731:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2732:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2733: 
1.44      ng       2734:     if ($button eq 'Save & Next') {
                   2735: 	my $ctr = 0;
                   2736: 	while ($ctr < $ngrade) {
1.257     albertel 2737: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2738: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2739: 	    if ($errorflag eq 'no_score') {
                   2740: 		$ctr++;
                   2741: 		next;
                   2742: 	    }
1.104     albertel 2743: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2744: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2745: 		$ctr++;
                   2746: 		next;
                   2747: 	    }
1.257     albertel 2748: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2749: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2750: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2751:             my ($feedurl,$showsymb) =
                   2752: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2753: 	    my $messagetail;
1.62      albertel 2754: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2755: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2756: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2757: 		$subject.=' ['.$restitle.']';
1.44      ng       2758: 		my (@msgnum) = split(/,/,$includemsg);
                   2759: 		foreach (@msgnum) {
1.257     albertel 2760: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2761: 		}
1.80      ng       2762: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2763: 		if ($env{'form.withgrades'.$ctr}) {
                   2764: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2765: 		    $messagetail = " for <a href=\"".
1.605     www      2766: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2767: 		}
                   2768: 		$msgstatus = 
                   2769:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2770: 						     $message.$messagetail,
1.418     albertel 2771:                                                      undef,$feedurl,undef,
1.386     raeburn  2772:                                                      undef,undef,$showsymb,
                   2773:                                                      $restitle);
1.574     bisitz   2774: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2775: 				$msgstatus.'<br />');
1.44      ng       2776: 	    }
1.257     albertel 2777: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2778: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2779: 		foreach my $collabstr (@collabstrs) {
                   2780: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2781: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2782: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2783: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2784: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2785: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2786: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2787: 			    next;
1.418     albertel 2788: 			} elsif ($message ne '') {
                   2789: 			    my ($baseurl,$showsymb) = 
                   2790: 				&get_feedurl_and_symb($symb,$collaborator,
                   2791: 						      $udom);
                   2792: 			    if ($env{'form.withgrades'.$ctr}) {
                   2793: 				$messagetail = " for <a href=\"".
1.605     www      2794:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2795: 			    }
1.418     albertel 2796: 			    $msgstatus = 
                   2797: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2798: 			}
1.44      ng       2799: 		    }
                   2800: 		}
                   2801: 	    }
                   2802: 	    $ctr++;
                   2803: 	}
                   2804:     }
                   2805: 
1.624     www      2806: #    if ($env{'form.handgrade'} eq 'yes') {
                   2807:     if (1) {
1.119     ng       2808: 	# Keywords sorted in alphabatical order
1.257     albertel 2809: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2810: 	my %keyhash = ();
1.257     albertel 2811: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2812: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2813: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2814: 	$env{'form.keywords'} = join(' ',@keywords);
                   2815: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2816: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2817: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2818: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2819: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2820: 
                   2821: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2822: 	# New messages are saved in env for the next student.
1.119     ng       2823: 	# All messages are saved in nohist_handgrade.db
                   2824: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2825: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2826: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2827: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2828: 		$idx++;
                   2829: 	    }
                   2830: 	    $ctr++;
1.41      ng       2831: 	}
1.119     ng       2832: 	$ctr = 0;
                   2833: 	while ($ctr < $ngrade) {
1.257     albertel 2834: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2835: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2836: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2837: 		$idx++;
                   2838: 	    }
                   2839: 	    $ctr++;
1.41      ng       2840: 	}
1.257     albertel 2841: 	$env{'form.savemsgN'} = --$idx;
                   2842: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2843: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2844: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2845:     }
1.44      ng       2846:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2847:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2848:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2849: 	my ($ctr,$total) = (0,0);
                   2850: 	while ($ctr < $ngrade) {
1.257     albertel 2851: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2852: 	    $ctr++;
                   2853: 	}
1.257     albertel 2854: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2855: 	$ctr = 0;
                   2856: 	while ($ctr < $total) {
1.257     albertel 2857: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2858: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2859: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2860: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2861: 	    $ctr++;
                   2862: 	}
                   2863: 	return '';
                   2864:     }
1.36      ng       2865: 
1.44      ng       2866:     # Get the next/previous one or group of students
1.257     albertel 2867:     my $firststu = $env{'form.unamedom0'};
                   2868:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2869:     my $ctr = 2;
1.41      ng       2870:     while ($laststu eq '') {
1.257     albertel 2871: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2872: 	$ctr++;
                   2873: 	$laststu = $firststu if ($ctr > $ngrade);
                   2874:     }
1.44      ng       2875: 
1.41      ng       2876:     my (@parsedlist,@nextlist);
                   2877:     my ($nextflg) = 0;
1.524     raeburn  2878:     foreach my $item (sort 
1.294     albertel 2879: 	     {
                   2880: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2881: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2882: 		 }
                   2883: 		 return $a cmp $b;
                   2884: 	     } (keys(%$fullname))) {
1.605     www      2885: # FIXME: this is fishy, looks like the button label
1.41      ng       2886: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2887: 	    push(@parsedlist,$item);
1.41      ng       2888: 	}
1.524     raeburn  2889: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2890: 	if ($button eq 'Previous') {
1.524     raeburn  2891: 	    last if ($item eq $firststu);
                   2892: 	    push(@parsedlist,$item);
1.41      ng       2893: 	}
                   2894:     }
                   2895:     $ctr = 0;
1.605     www      2896: # FIXME: this is fishy, looks like the button label
1.41      ng       2897:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2898:     my $res_error;
                   2899:     my ($partlist) = &response_type($symb,\$res_error);
                   2900:     if ($res_error) {
                   2901:         $request->print(&navmap_errormsg());
                   2902:         return;
                   2903:     }
1.41      ng       2904:     foreach my $student (@parsedlist) {
1.257     albertel 2905: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2906: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2907: 	
                   2908: 	if ($submitonly eq 'queued') {
                   2909: 	    my %queue_status = 
                   2910: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2911: 							$udom,$uname);
                   2912: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2913: 	}
                   2914: 
1.156     albertel 2915: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2916: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2917: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2918: 	    my $submitted = 0;
1.248     albertel 2919: 	    my $ungraded = 0;
                   2920: 	    my $incorrect = 0;
1.524     raeburn  2921: 	    foreach my $item (keys(%status)) {
                   2922: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2923: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2924: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2925: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2926: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2927: 		    $submitted = 0;
                   2928: 		}
1.41      ng       2929: 	    }
1.156     albertel 2930: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2931: 				     $submitonly eq 'incorrect' ||
                   2932: 				     $submitonly eq 'graded'));
1.248     albertel 2933: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2934: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2935: 	}
1.524     raeburn  2936: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2937: 	last if ($ctr == $ntstu);
1.41      ng       2938: 	$ctr++;
                   2939:     }
1.36      ng       2940: 
1.41      ng       2941:     $ctr = 0;
                   2942:     my $total = scalar(@nextlist)-1;
1.39      ng       2943: 
1.524     raeburn  2944:     foreach (sort(@nextlist)) {
1.41      ng       2945: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2946: 	$env{'form.student'}  = $uname;
                   2947: 	$env{'form.userdom'}  = $udom;
                   2948: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2949: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2950: 	$ctr++;
                   2951:     }
                   2952:     if ($total < 0) {
1.653     raeburn  2953: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2954: 	$request->print($the_end);
                   2955:     }
                   2956:     return '';
1.38      ng       2957: }
1.36      ng       2958: 
1.44      ng       2959: #---- Save the score and award for each student, if changed
1.38      ng       2960: sub saveHandGrade {
1.324     albertel 2961:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2962:     my @version_parts;
1.104     albertel 2963:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2964: 					   $env{'request.course.id'});
1.104     albertel 2965:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2966:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2967:     my @parts_graded;
1.77      ng       2968:     my %newrecord  = ();
                   2969:     my ($pts,$wgt) = ('','');
1.269     raeburn  2970:     my %aggregate = ();
                   2971:     my $aggregateflag = 0;
1.301     albertel 2972:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2973:     foreach my $new_part (@parts) {
1.337     banghart 2974: 	#collaborator ($submi may vary for different parts
1.259     banghart 2975: 	if ($submitter && $new_part ne $part) { next; }
                   2976: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2977: 	if ($dropMenu eq 'excused') {
1.259     banghart 2978: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2979: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2980: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2981: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2982: 		}
1.364     banghart 2983: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2984: 	    }
1.125     ng       2985: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2986: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2987: 	    foreach my $key (keys(%record)) {
1.259     banghart 2988: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2989: 	    }
1.259     banghart 2990: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2991: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2992:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2993: 
                   2994:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2995: 					       [$new_part]);
                   2996:             my $aggtries =$totaltries;
1.269     raeburn  2997:             if ($last_resets{$new_part}) {
1.270     albertel 2998:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2999: 					   $new_part);
1.269     raeburn  3000:             }
1.270     albertel 3001: 
                   3002:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3003:             if ($aggtries > 0) {
1.327     albertel 3004:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3005:                 $aggregateflag = 1;
                   3006:             }
1.125     ng       3007: 	} elsif ($dropMenu eq '') {
1.259     banghart 3008: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3009: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3010: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3011: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3012: 		next;
                   3013: 	    }
1.259     banghart 3014: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3015: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3016: 	    my $partial= $pts/$wgt;
1.259     banghart 3017: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3018: 		#do not update score for part if not changed.
1.346     banghart 3019:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3020: 		next;
1.251     banghart 3021: 	    } else {
1.524     raeburn  3022: 	        push(@parts_graded,$new_part);
1.153     albertel 3023: 	    }
1.259     banghart 3024: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3025: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3026: 	    }
1.259     banghart 3027: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3028: 	    if ($partial == 0) {
1.153     albertel 3029: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3030: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3031: 		}
1.41      ng       3032: 	    } else {
1.153     albertel 3033: 		if ($record{$reckey} ne 'correct_by_override') {
                   3034: 		    $newrecord{$reckey} = 'correct_by_override';
                   3035: 		}
                   3036: 	    }	    
                   3037: 	    if ($submitter && 
1.259     banghart 3038: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3039: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3040: 	    }
1.259     banghart 3041: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3042: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3043: 	}
1.259     banghart 3044: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3045: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3046: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3047: 	        $dropMenu eq 'reset status')
                   3048: 	   {
1.524     raeburn  3049: 	    push(@version_parts,$new_part);
1.259     banghart 3050: 	}
1.41      ng       3051:     }
1.301     albertel 3052:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3053:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3054: 
1.344     albertel 3055:     if (%newrecord) {
                   3056:         if (@version_parts) {
1.364     banghart 3057:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3058:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3059: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3060: 	    foreach my $new_part (@version_parts) {
                   3061: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3062: 				$new_part,\%newrecord);
                   3063: 	    }
1.259     banghart 3064:         }
1.44      ng       3065: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3066: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3067: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3068: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3069:     }
1.269     raeburn  3070:     if ($aggregateflag) {
                   3071:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3072: 			      $cdom,$cnum);
1.269     raeburn  3073:     }
1.301     albertel 3074:     return ('',$pts,$wgt);
1.36      ng       3075: }
1.322     albertel 3076: 
1.380     albertel 3077: sub check_and_remove_from_queue {
                   3078:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3079:     my @ungraded_parts;
                   3080:     foreach my $part (@{$parts}) {
                   3081: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3082: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3083: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3084: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3085: 		) {
                   3086: 	    push(@ungraded_parts, $part);
                   3087: 	}
                   3088:     }
                   3089:     if ( !@ungraded_parts ) {
                   3090: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3091: 					       $cnum,$domain,$stuname);
                   3092:     }
                   3093: }
                   3094: 
1.337     banghart 3095: sub handback_files {
                   3096:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3097:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3098:     my $res_error;
                   3099:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3100:     if ($res_error) {
                   3101:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3102:         return;
                   3103:     }
1.654     raeburn  3104:     my @handedback;
                   3105:     my $file_msg;
1.375     albertel 3106:     my @part_response_id = &flatten_responseType($responseType);
                   3107:     foreach my $part_response_id (@part_response_id) {
                   3108:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3109: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3110:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3111:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3112:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3113:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3114:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3115:                     my ($directory,$answer_file) = 
1.654     raeburn  3116:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3117:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3118: 		        &file_name_version_ext($answer_file);
1.355     banghart 3119: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3120:                     my $getpropath = 1;
1.662     raeburn  3121:                     my ($dir_list,$listerror) = 
                   3122:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3123:                                                  $domain,$stuname,$getpropath);
                   3124: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3125:                     # fix filename
1.355     banghart 3126:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3127:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3128:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3129:             	                                $save_file_name);
1.337     banghart 3130:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3131:                         $request->print('<br /><span class="LC_error">'.
                   3132:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3133:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3134:                                         '</span>');
1.356     banghart 3135:                     } else {
1.360     banghart 3136:                         # mark the file as read only
1.654     raeburn  3137:                         push(@handedback,$save_file_name);
1.367     albertel 3138: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3139: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3140: 			}
                   3141:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3142: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3143:                     }
1.686     bisitz   3144:                     $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 3145:                 }
                   3146:             }
                   3147:         }
1.654     raeburn  3148:     }
                   3149:     if (@handedback > 0) {
                   3150:         $request->print('<br />');
                   3151:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3152:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3153:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3154:         my ($subject,$message);
                   3155:         if (scalar(@handedback) == 1) {
                   3156:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3157:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3158:         } else {
                   3159:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3160:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3161:         }
                   3162:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3163:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3164:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3165:         my ($feedurl,$showsymb) =
                   3166:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3167:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3168:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3169:         my $msgstatus =
                   3170:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3171:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3172:                  $restitle);
                   3173:         if ($msgstatus) {
                   3174:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3175:         }
                   3176:     }
1.338     banghart 3177:     return;
1.337     banghart 3178: }
                   3179: 
1.418     albertel 3180: sub get_feedurl_and_symb {
                   3181:     my ($symb,$uname,$udom) = @_;
                   3182:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3183:     $url = &Apache::lonnet::clutter($url);
                   3184:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3185: 					$symb,$udom,$uname);
                   3186:     if ($encrypturl =~ /^yes$/i) {
                   3187: 	&Apache::lonenc::encrypted(\$url,1);
                   3188: 	&Apache::lonenc::encrypted(\$symb,1);
                   3189:     }
                   3190:     return ($url,$symb);
                   3191: }
                   3192: 
1.313     banghart 3193: sub get_submitted_files {
                   3194:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3195:     my @files;
                   3196:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3197:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3198:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3199:     	    push(@files,$file_url.$file);
                   3200:         }
                   3201:     }
                   3202:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3203:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3204:     }
                   3205:     return (\@files);
                   3206: }
1.322     albertel 3207: 
1.269     raeburn  3208: # ----------- Provides number of tries since last reset.
                   3209: sub get_num_tries {
                   3210:     my ($record,$last_reset,$part) = @_;
                   3211:     my $timestamp = '';
                   3212:     my $num_tries = 0;
                   3213:     if ($$record{'version'}) {
                   3214:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3215:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3216:                 $timestamp = $$record{$version.':timestamp'};
                   3217:                 if ($timestamp > $last_reset) {
                   3218:                     $num_tries ++;
                   3219:                 } else {
                   3220:                     last;
                   3221:                 }
                   3222:             }
                   3223:         }
                   3224:     }
                   3225:     return $num_tries;
                   3226: }
                   3227: 
                   3228: # ----------- Determine decrements required in aggregate totals 
                   3229: sub decrement_aggs {
                   3230:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3231:     my %decrement = (
                   3232:                         attempts => 0,
                   3233:                         users => 0,
                   3234:                         correct => 0
                   3235:                     );
                   3236:     $decrement{'attempts'} = $aggtries;
                   3237:     if ($solvedstatus =~ /^correct/) {
                   3238:         $decrement{'correct'} = 1;
                   3239:     }
                   3240:     if ($aggtries == $totaltries) {
                   3241:         $decrement{'users'} = 1;
                   3242:     }
1.524     raeburn  3243:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3244:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3245:     }
                   3246:     return;
                   3247: }
                   3248: 
                   3249: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3250: sub get_last_resets {
1.270     albertel 3251:     my ($symb,$courseid,$partids) =@_;
                   3252:     my %last_resets;
1.269     raeburn  3253:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3254:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3255:     my @keys;
                   3256:     foreach my $part (@{$partids}) {
                   3257: 	push(@keys,"$symb\0$part\0resettime");
                   3258:     }
                   3259:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3260: 				     $cdom,$cname);
                   3261:     foreach my $part (@{$partids}) {
                   3262: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3263:     }
1.270     albertel 3264:     return %last_resets;
1.269     raeburn  3265: }
                   3266: 
1.251     banghart 3267: # ----------- Handles creating versions for portfolio files as answers
                   3268: sub version_portfiles {
1.343     banghart 3269:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3270:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3271:     my @returned_keys;
1.255     banghart 3272:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3273:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3274:     foreach my $key (keys(%$record)) {
1.259     banghart 3275:         my $new_portfiles;
1.263     banghart 3276:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3277:             my @versioned_portfiles;
1.367     albertel 3278:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3279:             foreach my $file (@portfiles) {
1.306     banghart 3280:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3281:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3282: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3283: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3284:                 my $getpropath = 1;    
1.662     raeburn  3285:                 my ($dir_list,$listerror) = 
                   3286:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3287:                                              $stu_name,$getpropath);
                   3288:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3289:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3290:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3291:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3292:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3293:                         [$directory.$new_answer],
1.306     banghart 3294:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3295:                 }
1.252     banghart 3296:             }
1.343     banghart 3297:             $$record{$key} = join(',',@versioned_portfiles);
                   3298:             push(@returned_keys,$key);
1.251     banghart 3299:         }
                   3300:     } 
1.343     banghart 3301:     return (@returned_keys);   
1.305     banghart 3302: }
                   3303: 
1.307     banghart 3304: sub get_next_version {
1.341     banghart 3305:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3306:     my $version;
1.662     raeburn  3307:     if (ref($dir_list) eq 'ARRAY') {
                   3308:         foreach my $row (@{$dir_list}) {
                   3309:             my ($file) = split(/\&/,$row,2);
                   3310:             my ($file_name,$file_version,$file_ext) =
                   3311: 	        &file_name_version_ext($file);
                   3312:             if (($file_name eq $answer_name) && 
                   3313: 	        ($file_ext eq $answer_ext)) {
                   3314:                      # gets here if filename and extension match, 
                   3315:                      # regardless of version
1.307     banghart 3316:                 if ($file_version ne '') {
1.662     raeburn  3317:                     # a versioned file is found  so save it for later
                   3318:                     if ($file_version > $version) {
                   3319: 		        $version = $file_version;
                   3320: 	            }
                   3321:                 }
1.307     banghart 3322:             }
                   3323:         }
1.662     raeburn  3324:     }
1.307     banghart 3325:     $version ++;
                   3326:     return($version);
                   3327: }
                   3328: 
1.305     banghart 3329: sub version_selected_portfile {
1.306     banghart 3330:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3331:     my ($answer_name,$answer_ver,$answer_ext) =
                   3332:         &file_name_version_ext($file_name);
                   3333:     my $new_answer;
                   3334:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3335:     if($env{'form.copy'} eq '-1') {
                   3336:         $new_answer = 'problem getting file';
                   3337:     } else {
                   3338:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3339:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3340:                             $stu_name,$domain,'copy',
                   3341: 		        '/portfolio'.$directory.$new_answer);
                   3342:     }    
                   3343:     return ($new_answer);
1.251     banghart 3344: }
                   3345: 
1.304     albertel 3346: sub file_name_version_ext {
                   3347:     my ($file)=@_;
                   3348:     my @file_parts = split(/\./, $file);
                   3349:     my ($name,$version,$ext);
                   3350:     if (@file_parts > 1) {
                   3351: 	$ext=pop(@file_parts);
                   3352: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3353: 	    $version=pop(@file_parts);
                   3354: 	}
                   3355: 	$name=join('.',@file_parts);
                   3356:     } else {
                   3357: 	$name=join('.',@file_parts);
                   3358:     }
                   3359:     return($name,$version,$ext);
                   3360: }
                   3361: 
1.44      ng       3362: #--------------------------------------------------------------------------------------
                   3363: #
                   3364: #-------------------------- Next few routines handles grading by section or whole class
                   3365: #
                   3366: #--- Javascript to handle grading by section or whole class
1.42      ng       3367: sub viewgrades_js {
                   3368:     my ($request) = shift;
                   3369: 
1.539     riegler  3370:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3371:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3372:    function writePoint(partid,weight,point) {
1.125     ng       3373: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3374: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3375: 	if (point == "textval") {
1.125     ng       3376: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3377: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3378: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3379: 		var resetbox = false;
                   3380: 		for (var i=0; i<radioButton.length; i++) {
                   3381: 		    if (radioButton[i].checked) {
                   3382: 			textbox.value = i;
                   3383: 			resetbox = true;
                   3384: 		    }
                   3385: 		}
                   3386: 		if (!resetbox) {
                   3387: 		    textbox.value = "";
                   3388: 		}
                   3389: 		return;
                   3390: 	    }
1.109     matthew  3391: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3392: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3393: 				   ") greater than the weight for the part. Accept?");
                   3394: 		if (resp == false) {
                   3395: 		    textbox.value = "";
                   3396: 		    return;
                   3397: 		}
                   3398: 	    }
1.42      ng       3399: 	    for (var i=0; i<radioButton.length; i++) {
                   3400: 		radioButton[i].checked=false;
1.109     matthew  3401: 		if (parseFloat(point) == i) {
1.42      ng       3402: 		    radioButton[i].checked=true;
                   3403: 		}
                   3404: 	    }
1.41      ng       3405: 
1.42      ng       3406: 	} else {
1.125     ng       3407: 	    textbox.value = parseFloat(point);
1.42      ng       3408: 	}
1.41      ng       3409: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3410: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3411: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3412: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3413: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3414: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3415: 	    if (saveval != "correct") {
                   3416: 		scorename.value = point;
1.43      ng       3417: 		if (selname[0].selected != true) {
                   3418: 		    selname[0].selected = true;
                   3419: 		}
1.42      ng       3420: 	    }
                   3421: 	}
1.125     ng       3422: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3423:     }
                   3424: 
                   3425:     function writeRadText(partid,weight) {
1.125     ng       3426: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3427: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3428:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3429: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3430: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3431: 	    for (var i=0; i<radioButton.length; i++) {
                   3432: 		radioButton[i].checked=false;
                   3433: 
                   3434: 	    }
                   3435: 	    textbox.value = "";
                   3436: 
                   3437: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3438: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3439: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3440: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3441: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3442: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3443: 		if ((saveval != "correct") || override) {
1.42      ng       3444: 		    scorename.value = "";
1.125     ng       3445: 		    if (selval[1].selected) {
                   3446: 			selname[1].selected = true;
                   3447: 		    } else {
                   3448: 			selname[2].selected = true;
                   3449: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3450: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3451: 		    }
1.42      ng       3452: 		}
                   3453: 	    }
1.43      ng       3454: 	} else {
                   3455: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3456: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3457: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3458: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3459: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3460: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3461: 		if ((saveval != "correct") || override) {
1.125     ng       3462: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3463: 		    selname[0].selected = true;
                   3464: 		}
                   3465: 	    }
                   3466: 	}	    
1.42      ng       3467:     }
                   3468: 
                   3469:     function changeSelect(partid,user) {
1.125     ng       3470: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3471: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3472: 	var point  = textbox.value;
1.125     ng       3473: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3474: 
1.109     matthew  3475: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3476: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3477: 	    textbox.value = "";
                   3478: 	    return;
                   3479: 	}
1.109     matthew  3480: 	if (parseFloat(point) > parseFloat(weight)) {
                   3481: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3482: 			       ") greater than the weight of the part. Accept?");
                   3483: 	    if (resp == false) {
                   3484: 		textbox.value = "";
                   3485: 		return;
                   3486: 	    }
                   3487: 	}
1.42      ng       3488: 	selval[0].selected = true;
                   3489:     }
                   3490: 
                   3491:     function changeOneScore(partid,user) {
1.125     ng       3492: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3493: 	if (selval[1].selected || selval[2].selected) {
                   3494: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3495: 	    if (selval[2].selected) {
                   3496: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3497: 	    }
1.269     raeburn  3498:         }
1.42      ng       3499:     }
                   3500: 
                   3501:     function resetEntry(numpart) {
                   3502: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3503: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3504: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3505: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3506: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3507: 	    for (var i=0; i<radioButton.length; i++) {
                   3508: 		radioButton[i].checked=false;
                   3509: 
                   3510: 	    }
                   3511: 	    textbox.value = "";
                   3512: 	    selval[0].selected = true;
                   3513: 
                   3514: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3515: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3516: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3517: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3518: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3519: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3520: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3521: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3522: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3523: 		if (saveselval == "excused") {
1.43      ng       3524: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3525: 		} else {
1.43      ng       3526: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3527: 		}
                   3528: 	    }
1.41      ng       3529: 	}
1.42      ng       3530:     }
                   3531: 
1.41      ng       3532: VIEWJAVASCRIPT
1.42      ng       3533: }
                   3534: 
1.44      ng       3535: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3536: sub viewgrades {
1.608     www      3537:     my ($request,$symb) = @_;
1.42      ng       3538:     &viewgrades_js($request);
1.41      ng       3539: 
1.168     albertel 3540:     #need to make sure we have the correct data for later EXT calls, 
                   3541:     #thus invalidate the cache
                   3542:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3543:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3544:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3545:     &Apache::lonnet::clear_EXT_cache_status();
                   3546: 
1.398     albertel 3547:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3548: 
                   3549:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3550:     $result.=&jscriptNform($symb);
1.41      ng       3551: 
1.44      ng       3552:     #beginning of class grading form
1.442     banghart 3553:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3554:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3555: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3556: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3557: 	&build_section_inputs().
1.442     banghart 3558: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3559: 
1.560     raeburn  3560:     my ($common_header,$specific_header);
1.257     albertel 3561:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3562: 	$common_header = &mt('Assign Common Grade to Class');
                   3563:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3564:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3565:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3566: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3567:     } else {
1.560     raeburn  3568:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3569:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3570: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3571:     }
1.560     raeburn  3572:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3573:     #radio buttons/text box for assigning points for a section or class.
                   3574:     #handles different parts of a problem
1.582     raeburn  3575:     my $res_error;
                   3576:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3577:     if ($res_error) {
                   3578:         return &navmap_errormsg();
                   3579:     }
1.42      ng       3580:     my %weight = ();
                   3581:     my $ctsparts = 0;
1.45      ng       3582:     my %seen = ();
1.375     albertel 3583:     my @part_response_id = &flatten_responseType($responseType);
                   3584:     foreach my $part_response_id (@part_response_id) {
                   3585:     	my ($partid,$respid) = @{ $part_response_id };
                   3586: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3587: 	next if $seen{$partid};
                   3588: 	$seen{$partid}++;
1.375     albertel 3589: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3590: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3591: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3592: 
1.324     albertel 3593: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3594: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3595: 	my $ctr = 0;
1.42      ng       3596: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3597: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3598: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3599: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3600: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3601: 	    $ctr++;
                   3602: 	}
1.485     albertel 3603: 	$radio.='</tr></table>';
                   3604: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3605: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3606: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3607: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3608:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3609:             '<select name="SELVAL_'.$partid.'" '.
                   3610:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3611:                 $weight{$partid}.')"> '.
1.401     albertel 3612: 	    '<option selected="selected"> </option>'.
1.485     albertel 3613: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3614: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3615: 	    '</select></td>'.
                   3616:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3617: 	$line.='<input type="hidden" name="partid_'.
                   3618: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3619: 	$line.='<input type="hidden" name="weight_'.
                   3620: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3621: 
                   3622: 	$result.=
                   3623: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3624: 	    '<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 3625: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3626: 	$ctsparts++;
1.41      ng       3627:     }
1.474     albertel 3628:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3629: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3630:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3631: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3632: 
1.44      ng       3633:     #table listing all the students in a section/class
                   3634:     #header of table
1.560     raeburn  3635:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3636:               &Apache::loncommon::start_data_table().
                   3637: 	      &Apache::loncommon::start_data_table_header_row().
                   3638: 	      '<th>'.&mt('No.').'</th>'.
                   3639: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3640:     my $partserror;
                   3641:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3642:     if ($partserror) {
                   3643:         return &navmap_errormsg();
                   3644:     }
1.324     albertel 3645:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3646:     my @partids = ();
1.41      ng       3647:     foreach my $part (@parts) {
                   3648: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3649:         my $narrowtext = &mt('Tries');
                   3650: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3651: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3652: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3653:         push(@partids,$partid);
1.628     www      3654: #
                   3655: # FIXME: Looks like $display looks at English text
                   3656: #
1.324     albertel 3657: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3658: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3659: 	    $result.='<th>'.
1.697     bisitz   3660: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3661: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3662: 	    next;
1.485     albertel 3663: 	    
1.207     albertel 3664: 	} else {
1.485     albertel 3665: 	    if ($display =~ /Problem Status/) {
                   3666: 		my $grade_status_mt = &mt('Grade Status');
                   3667: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3668: 	    }
                   3669: 	    my $part_mt = &mt('Part:');
                   3670: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3671: 	}
1.485     albertel 3672: 
1.474     albertel 3673: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3674:     }
1.474     albertel 3675:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3676: 
1.270     albertel 3677:     my %last_resets = 
                   3678: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3679: 
1.41      ng       3680:     #get info for each student
1.44      ng       3681:     #list all the students - with points and grade status
1.257     albertel 3682:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3683:     my $ctr = 0;
1.294     albertel 3684:     foreach (sort 
                   3685: 	     {
                   3686: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3687: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3688: 		 }
                   3689: 		 return $a cmp $b;
                   3690: 	     } (keys(%$fullname))) {
1.126     ng       3691: 	$ctr++;
1.324     albertel 3692: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3693: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3694:     }
1.474     albertel 3695:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3696:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3697:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3698: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3699:     if (scalar(%$fullname) eq 0) {
                   3700: 	my $colspan=3+scalar(@parts);
1.433     banghart 3701: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3702:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3703: 	$result='<span class="LC_warning">'.
1.485     albertel 3704: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3705: 	        $section_display, $stu_status).
1.433     banghart 3706: 	    '</span>';
1.96      albertel 3707:     }
1.41      ng       3708:     return $result;
                   3709: }
                   3710: 
1.44      ng       3711: #--- call by previous routine to display each student
1.41      ng       3712: sub viewstudentgrade {
1.324     albertel 3713:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3714:     my ($uname,$udom) = split(/:/,$student);
                   3715:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3716:     my %aggregates = (); 
1.474     albertel 3717:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3718: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3719: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3720: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3721: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3722: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3723:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3724:     foreach my $apart (@$parts) {
                   3725: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3726: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3727:         $result.='<td align="center">';
1.269     raeburn  3728:         my ($aggtries,$totaltries);
                   3729:         unless (exists($aggregates{$part})) {
1.270     albertel 3730: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3731: 
                   3732: 	    $aggtries = $totaltries;
1.269     raeburn  3733:             if ($$last_resets{$part}) {  
1.270     albertel 3734:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3735: 					   $part);
                   3736:             }
1.269     raeburn  3737:             $result.='<input type="hidden" name="'.
                   3738:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3739:             $result.='<input type="hidden" name="'.
                   3740:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3741:             $aggregates{$part} = 1;
                   3742:         }
1.41      ng       3743: 	if ($type eq 'awarded') {
1.320     albertel 3744: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3745: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3746: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3747: 	    $result.='<input type="text" name="'.
1.89      albertel 3748: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3749:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3750: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3751: 	} elsif ($type eq 'solved') {
                   3752: 	    my ($status,$foo)=split(/_/,$score,2);
                   3753: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3754: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3755: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3756: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3757: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3758:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3759: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3760: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3761: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3762: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3763: 	} else {
                   3764: 	    $result.='<input type="hidden" name="'.
                   3765: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3766: 		    "\n";
1.233     albertel 3767: 	    $result.='<input type="text" name="'.
1.122     ng       3768: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3769: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3770: 	}
                   3771:     }
1.474     albertel 3772:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3773:     return $result;
1.38      ng       3774: }
                   3775: 
1.44      ng       3776: #--- change scores for all the students in a section/class
                   3777: #    record does not get update if unchanged
1.38      ng       3778: sub editgrades {
1.608     www      3779:     my ($request,$symb) = @_;
1.41      ng       3780: 
1.433     banghart 3781:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3782:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3783:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3784: 
1.477     albertel 3785:     my $result= &Apache::loncommon::start_data_table().
                   3786: 	&Apache::loncommon::start_data_table_header_row().
                   3787: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3788: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3789:     my %scoreptr = (
                   3790: 		    'correct'  =>'correct_by_override',
                   3791: 		    'incorrect'=>'incorrect_by_override',
                   3792: 		    'excused'  =>'excused',
                   3793: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3794:                     'credited' =>'credit_attempted',
1.43      ng       3795: 		    'nothing'  => '',
                   3796: 		    );
1.257     albertel 3797:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3798: 
1.44      ng       3799:     my (@partid);
                   3800:     my %weight = ();
1.54      albertel 3801:     my %columns = ();
1.44      ng       3802:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3803: 
1.582     raeburn  3804:     my $partserror;
                   3805:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3806:     if ($partserror) {
                   3807:         return &navmap_errormsg();
                   3808:     }
1.54      albertel 3809:     my $header;
1.257     albertel 3810:     while ($ctr < $env{'form.totalparts'}) {
                   3811: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3812: 	push(@partid,$partid);
1.257     albertel 3813: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3814: 	$ctr++;
1.54      albertel 3815:     }
1.324     albertel 3816:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3817:     foreach my $partid (@partid) {
1.478     albertel 3818: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3819: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3820: 	$columns{$partid}=2;
                   3821: 	foreach my $stores (@parts) {
                   3822: 	    my ($part,$type) = &split_part_type($stores);
                   3823: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3824: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3825: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3826: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3827:             my $narrowtext = &mt('Tries');
                   3828: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3829: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3830: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3831: 	    $columns{$partid}+=2;
                   3832: 	}
                   3833:     }
                   3834:     foreach my $partid (@partid) {
1.324     albertel 3835: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3836: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3837: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3838: 	    '</th>';
1.54      albertel 3839: 
1.44      ng       3840:     }
1.477     albertel 3841:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3842: 	&Apache::loncommon::start_data_table_header_row().
                   3843: 	$header.
                   3844: 	&Apache::loncommon::end_data_table_header_row();
                   3845:     my @noupdate;
1.126     ng       3846:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3847:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3848: 	my $line;
1.257     albertel 3849: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3850: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3851: 	my %newrecord;
                   3852: 	my $updateflag = 0;
1.281     albertel 3853: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3854: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3855: 	if (!&canmodify($usec)) {
1.126     ng       3856: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3857: 	    push(@noupdate,
1.478     albertel 3858: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3859: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3860: 	    next;
                   3861: 	}
1.269     raeburn  3862:         my %aggregate = ();
                   3863:         my $aggregateflag = 0;
1.281     albertel 3864: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3865: 	foreach (@partid) {
1.257     albertel 3866: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3867: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3868: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3869: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3870: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3871: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3872: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3873: 	    my $score;
                   3874: 	    if ($partial eq '') {
1.257     albertel 3875: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3876: 	    } elsif ($partial > 0) {
                   3877: 		$score = 'correct_by_override';
                   3878: 	    } elsif ($partial == 0) {
                   3879: 		$score = 'incorrect_by_override';
                   3880: 	    }
1.257     albertel 3881: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3882: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3883: 
1.292     albertel 3884: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3885: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3886: 	    if ($dropMenu eq 'reset status' &&
                   3887: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3888: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3889: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3890: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3891: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3892: 		$updateflag = 1;
1.269     raeburn  3893:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3894:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3895:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3896:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3897:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3898:                     $aggregateflag = 1;
                   3899:                 }
1.139     albertel 3900: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3901: 		$updateflag = 1;
                   3902: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3903: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3904: 		$rec_update++;
1.125     ng       3905: 	    }
                   3906: 
1.93      albertel 3907: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3908: 		'<td align="center">'.$awarded.
                   3909: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3910: 
1.54      albertel 3911: 
                   3912: 	    my $partid=$_;
                   3913: 	    foreach my $stores (@parts) {
                   3914: 		my ($part,$type) = &split_part_type($stores);
                   3915: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3916: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3917: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3918: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3919: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3920: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3921: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3922: 		    $updateflag=1;
                   3923: 		}
1.93      albertel 3924: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3925: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3926: 	    }
1.44      ng       3927: 	}
1.477     albertel 3928: 	$line.="\n";
1.301     albertel 3929: 
                   3930: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3931: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3932: 
1.44      ng       3933: 	if ($updateflag) {
                   3934: 	    $count++;
1.257     albertel 3935: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3936: 				    $udom,$uname);
1.301     albertel 3937: 
                   3938: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3939: 					      $cnum,$udom,$uname)) {
                   3940: 		# need to figure out if should be in queue.
                   3941: 		my %record =  
                   3942: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3943: 					     $udom,$uname);
                   3944: 		my $all_graded = 1;
                   3945: 		my $none_graded = 1;
                   3946: 		foreach my $part (@parts) {
                   3947: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3948: 			$all_graded = 0;
                   3949: 		    } else {
                   3950: 			$none_graded = 0;
                   3951: 		    }
                   3952: 		}
                   3953: 
                   3954: 		if ($all_graded || $none_graded) {
                   3955: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3956: 							   $symb,$cdom,$cnum,
                   3957: 							   $udom,$uname);
                   3958: 		}
                   3959: 	    }
                   3960: 
1.477     albertel 3961: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3962: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3963: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3964: 	    $updateCtr++;
1.93      albertel 3965: 	} else {
1.477     albertel 3966: 	    push(@noupdate,
                   3967: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3968: 	    $noupdateCtr++;
1.44      ng       3969: 	}
1.269     raeburn  3970:         if ($aggregateflag) {
                   3971:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3972: 				  $cdom,$cnum);
1.269     raeburn  3973:         }
1.93      albertel 3974:     }
1.477     albertel 3975:     if (@noupdate) {
1.126     ng       3976: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3977: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3978: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3979: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3980: 	    &mt('No Changes Occurred For the Students Below').
                   3981: 	    '</td>'.
1.477     albertel 3982: 	    &Apache::loncommon::end_data_table_row();
                   3983: 	foreach my $line (@noupdate) {
                   3984: 	    $result.=
                   3985: 		&Apache::loncommon::start_data_table_row().
                   3986: 		$line.
                   3987: 		&Apache::loncommon::end_data_table_row();
                   3988: 	}
1.44      ng       3989:     }
1.614     www      3990:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3991:     my $msg = '<p><b>'.
                   3992: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3993: 	    $rec_update,$count).'</b><br />'.
                   3994: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3995: 	'</b></p>';
1.44      ng       3996:     return $title.$msg.$result;
1.5       albertel 3997: }
1.54      albertel 3998: 
                   3999: sub split_part_type {
                   4000:     my ($partstr) = @_;
                   4001:     my ($temp,@allparts)=split(/_/,$partstr);
                   4002:     my $type=pop(@allparts);
1.439     albertel 4003:     my $part=join('_',@allparts);
1.54      albertel 4004:     return ($part,$type);
                   4005: }
                   4006: 
1.44      ng       4007: #------------- end of section for handling grading by section/class ---------
                   4008: #
                   4009: #----------------------------------------------------------------------------
                   4010: 
1.5       albertel 4011: 
1.44      ng       4012: #----------------------------------------------------------------------------
                   4013: #
                   4014: #-------------------------- Next few routines handles grading by csv upload
                   4015: #
                   4016: #--- Javascript to handle csv upload
1.27      albertel 4017: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4018:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4019:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4020:   return(<<ENDPICK);
                   4021:   function verify(vf) {
                   4022:     var foundsomething=0;
                   4023:     var founduname=0;
1.243     albertel 4024:     var foundID=0;
1.27      albertel 4025:     for (i=0;i<=vf.nfields.value;i++) {
                   4026:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4027:       if (i==0 && tw!=0) { foundID=1; }
                   4028:       if (i==1 && tw!=0) { founduname=1; }
                   4029:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4030:     }
1.246     albertel 4031:     if (founduname==0 && foundID==0) {
                   4032: 	alert('$error1');
                   4033: 	return;
1.27      albertel 4034:     }
                   4035:     if (foundsomething==0) {
1.246     albertel 4036: 	alert('$error2');
                   4037: 	return;
1.27      albertel 4038:     }
                   4039:     vf.submit();
                   4040:   }
                   4041:   function flip(vf,tf) {
                   4042:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4043:     var i;
                   4044:     for (i=0;i<=vf.nfields.value;i++) {
                   4045:       //can not pick the same destination field for both name and domain
                   4046:       if (((i ==0)||(i ==1)) && 
                   4047:           ((tf==0)||(tf==1)) && 
                   4048:           (i!=tf) &&
                   4049:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4050:         eval('vf.f'+i+'.selectedIndex=0;')
                   4051:       }
                   4052:     }
                   4053:   }
                   4054: ENDPICK
                   4055: }
                   4056: 
                   4057: sub csvupload_javascript_forward_associate {
1.573     bisitz   4058:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4059:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4060:   return(<<ENDPICK);
                   4061:   function verify(vf) {
                   4062:     var foundsomething=0;
                   4063:     var founduname=0;
1.243     albertel 4064:     var foundID=0;
1.27      albertel 4065:     for (i=0;i<=vf.nfields.value;i++) {
                   4066:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4067:       if (tw==1) { foundID=1; }
                   4068:       if (tw==2) { founduname=1; }
                   4069:       if (tw>3) { foundsomething=1; }
1.27      albertel 4070:     }
1.246     albertel 4071:     if (founduname==0 && foundID==0) {
                   4072: 	alert('$error1');
                   4073: 	return;
1.27      albertel 4074:     }
                   4075:     if (foundsomething==0) {
1.246     albertel 4076: 	alert('$error2');
                   4077: 	return;
1.27      albertel 4078:     }
                   4079:     vf.submit();
                   4080:   }
                   4081:   function flip(vf,tf) {
                   4082:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4083:     var i;
                   4084:     //can not pick the same destination field twice
                   4085:     for (i=0;i<=vf.nfields.value;i++) {
                   4086:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4087:         eval('vf.f'+i+'.selectedIndex=0;')
                   4088:       }
                   4089:     }
                   4090:   }
                   4091: ENDPICK
                   4092: }
                   4093: 
1.26      albertel 4094: sub csvuploadmap_header {
1.324     albertel 4095:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4096:     my $javascript;
1.257     albertel 4097:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4098: 	$javascript=&csvupload_javascript_reverse_associate();
                   4099:     } else {
                   4100: 	$javascript=&csvupload_javascript_forward_associate();
                   4101:     }
1.45      ng       4102: 
1.418     albertel 4103:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4104:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4105:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4106:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4107:     my $reverse=&mt("Reverse Association");
1.41      ng       4108:     $request->print(<<ENDPICK);
1.632     www      4109: <br />
                   4110: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4111: <input type="hidden" name="associate"  value="" />
                   4112: <input type="hidden" name="phase"      value="three" />
                   4113: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4114: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4115: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4116: <input type="hidden" name="upfile_associate" 
1.257     albertel 4117:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4118: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4119: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4120: <hr />
                   4121: ENDPICK
1.597     wenzelju 4122:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4123:     return '';
1.26      albertel 4124: 
                   4125: }
                   4126: 
                   4127: sub csvupload_fields {
1.582     raeburn  4128:     my ($symb,$errorref) = @_;
                   4129:     my (@parts) = &getpartlist($symb,$errorref);
                   4130:     if (ref($errorref)) {
                   4131:         if ($$errorref) {
                   4132:             return;
                   4133:         }
                   4134:     }
                   4135: 
1.556     weissno  4136:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4137: 		['username','Student Username'],
                   4138: 		['domain','Student Domain']);
1.324     albertel 4139:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4140:     foreach my $part (sort(@parts)) {
                   4141: 	my @datum;
                   4142: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4143: 	my $name=$part;
                   4144: 	if  (!$display) { $display = $name; }
                   4145: 	@datum=($name,$display);
1.244     albertel 4146: 	if ($name=~/^stores_(.*)_awarded/) {
                   4147: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4148: 	}
1.41      ng       4149: 	push(@fields,\@datum);
                   4150:     }
                   4151:     return (@fields);
1.26      albertel 4152: }
                   4153: 
                   4154: sub csvuploadmap_footer {
1.41      ng       4155:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4156:     my $buttontext = &mt('Assign Grades');
1.41      ng       4157:     $request->print(<<ENDPICK);
1.26      albertel 4158: </table>
                   4159: <input type="hidden" name="nfields" value="$i" />
                   4160: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4161: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4162: </form>
                   4163: ENDPICK
                   4164: }
                   4165: 
1.283     albertel 4166: sub checkforfile_js {
1.638     www      4167:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4168:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4169:     function checkUpload(formname) {
                   4170: 	if (formname.upfile.value == "") {
1.539     riegler  4171: 	    alert("$alertmsg");
1.86      ng       4172: 	    return false;
                   4173: 	}
                   4174: 	formname.submit();
                   4175:     }
                   4176: CSVFORMJS
1.283     albertel 4177:     return $result;
                   4178: }
                   4179: 
                   4180: sub upcsvScores_form {
1.608     www      4181:     my ($request,$symb) = @_;
1.283     albertel 4182:     if (!$symb) {return '';}
                   4183:     my $result=&checkforfile_js();
1.632     www      4184:     $result.=&Apache::loncommon::start_data_table().
                   4185:              &Apache::loncommon::start_data_table_header_row().
                   4186:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4187:              &Apache::loncommon::end_data_table_header_row().
                   4188:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4189:     my $upload=&mt("Upload Scores");
1.86      ng       4190:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4191:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4192:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4193:     $result.=<<ENDUPFORM;
1.106     albertel 4194: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4195: <input type="hidden" name="symb" value="$symb" />
                   4196: <input type="hidden" name="command" value="csvuploadmap" />
                   4197: $upfile_select
1.589     bisitz   4198: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4199: </form>
                   4200: ENDUPFORM
1.370     www      4201:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4202:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4203:              '</td>'.
                   4204:             &Apache::loncommon::end_data_table_row().
                   4205:             &Apache::loncommon::end_data_table();
1.86      ng       4206:     return $result;
                   4207: }
                   4208: 
                   4209: 
1.26      albertel 4210: sub csvuploadmap {
1.608     www      4211:     my ($request,$symb)= @_;
1.41      ng       4212:     if (!$symb) {return '';}
1.72      ng       4213: 
1.41      ng       4214:     my $datatoken;
1.257     albertel 4215:     if (!$env{'form.datatoken'}) {
1.41      ng       4216: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4217:     } else {
1.257     albertel 4218: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4219: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4220:     }
1.41      ng       4221:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4222:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4223:     my ($i,$keyfields);
                   4224:     if (@records) {
1.582     raeburn  4225:         my $fieldserror;
                   4226: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4227:         if ($fieldserror) {
                   4228:             $request->print(&navmap_errormsg());
                   4229:             return;
                   4230:         }
1.257     albertel 4231: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4232: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4233: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4234: 							  \@fields);
                   4235: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4236: 	    chop($keyfields);
                   4237: 	} else {
                   4238: 	    unshift(@fields,['none','']);
                   4239: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4240: 							    \@fields);
1.311     banghart 4241:             foreach my $rec (@records) {
                   4242:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4243:                 if (%temp) {
                   4244:                     $keyfields=join(',',sort(keys(%temp)));
                   4245:                     last;
                   4246:                 }
                   4247:             }
1.41      ng       4248: 	}
                   4249:     }
                   4250:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4251: 
1.41      ng       4252:     return '';
1.27      albertel 4253: }
                   4254: 
1.246     albertel 4255: sub csvuploadoptions {
1.608     www      4256:     my ($request,$symb)= @_;
1.632     www      4257:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4258:     $request->print(<<ENDPICK);
                   4259: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4260: <input type="hidden" name="command"    value="csvuploadassign" />
                   4261: <p>
                   4262: <label>
                   4263:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4264:    $overwrite
1.246     albertel 4265: </label>
                   4266: </p>
                   4267: ENDPICK
                   4268:     my %fields=&get_fields();
                   4269:     if (!defined($fields{'domain'})) {
1.257     albertel 4270: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4271: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4272:     }
1.257     albertel 4273:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4274: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4275: 	my $cleankey=$1;
                   4276: 	if ($cleankey eq 'command') { next; }
                   4277: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4278: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4279:     }
                   4280:     # FIXME do a check for any duplicated user ids...
                   4281:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4282:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4283: <hr /></form>'."\n");
1.246     albertel 4284:     return '';
                   4285: }
                   4286: 
                   4287: sub get_fields {
                   4288:     my %fields;
1.257     albertel 4289:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4290:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4291: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4292: 	    if ($env{'form.f'.$i} ne 'none') {
                   4293: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4294: 	    }
                   4295: 	} else {
1.257     albertel 4296: 	    if ($env{'form.f'.$i} ne 'none') {
                   4297: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4298: 	    }
                   4299: 	}
1.27      albertel 4300:     }
1.246     albertel 4301:     return %fields;
                   4302: }
                   4303: 
                   4304: sub csvuploadassign {
1.608     www      4305:     my ($request,$symb)= @_;
1.246     albertel 4306:     if (!$symb) {return '';}
1.345     bowersj2 4307:     my $error_msg = '';
1.246     albertel 4308:     &Apache::loncommon::load_tmp_file($request);
                   4309:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4310:     my %fields=&get_fields();
1.257     albertel 4311:     my $courseid=$env{'request.course.id'};
1.97      albertel 4312:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4313:     my @notallowed;
1.41      ng       4314:     my @skipped;
1.657     raeburn  4315:     my @warnings;
1.41      ng       4316:     my $countdone=0;
                   4317:     foreach my $grade (@gradedata) {
                   4318: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4319: 	my $domain;
                   4320: 	if ($entries{$fields{'domain'}}) {
                   4321: 	    $domain=$entries{$fields{'domain'}};
                   4322: 	} else {
1.257     albertel 4323: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4324: 	}
1.243     albertel 4325: 	$domain=~s/\s//g;
1.41      ng       4326: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4327: 	$username=~s/\s//g;
1.243     albertel 4328: 	if (!$username) {
                   4329: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4330: 	    $id=~s/\s//g;
1.243     albertel 4331: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4332: 	    $username=$ids{$id};
                   4333: 	}
1.41      ng       4334: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4335: 	    my $id=$entries{$fields{'ID'}};
                   4336: 	    $id=~s/\s//g;
                   4337: 	    if ($id) {
                   4338: 		push(@skipped,"$id:$domain");
                   4339: 	    } else {
                   4340: 		push(@skipped,"$username:$domain");
                   4341: 	    }
1.41      ng       4342: 	    next;
                   4343: 	}
1.108     albertel 4344: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4345: 	if (!&canmodify($usec)) {
                   4346: 	    push(@notallowed,"$username:$domain");
                   4347: 	    next;
                   4348: 	}
1.244     albertel 4349: 	my %points;
1.41      ng       4350: 	my %grades;
                   4351: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4352: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4353: 		$dest eq 'domain') { next; }
                   4354: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4355: 	    if ($dest=~/stores_(.*)_points/) {
                   4356: 		my $part=$1;
                   4357: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4358: 					      $symb,$domain,$username);
1.345     bowersj2 4359:                 if ($wgt) {
                   4360:                     $entries{$fields{$dest}}=~s/\s//g;
                   4361:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4362:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4363:                                           : 'correct_by_override';
1.638     www      4364:                     if ($pcr>1) {
1.657     raeburn  4365:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4366:                     }
1.345     bowersj2 4367:                     $grades{"resource.$part.awarded"}=$pcr;
                   4368:                     $grades{"resource.$part.solved"}=$award;
                   4369:                     $points{$part}=1;
                   4370:                 } else {
                   4371:                     $error_msg = "<br />" .
                   4372:                         &mt("Some point values were assigned"
                   4373:                             ." for problems with a weight "
                   4374:                             ."of zero. These values were "
                   4375:                             ."ignored.");
                   4376:                 }
1.244     albertel 4377: 	    } else {
                   4378: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4379: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4380: 		my $store_key=$dest;
                   4381: 		$store_key=~s/^stores/resource/;
                   4382: 		$store_key=~s/_/\./g;
                   4383: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4384: 	    }
1.41      ng       4385: 	}
1.508     www      4386: 	if (! %grades) { 
                   4387:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4388:         } else {
                   4389: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4390: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4391: 					   $env{'request.course.id'},
                   4392: 					   $domain,$username);
1.508     www      4393: 	   if ($result eq 'ok') {
1.627     www      4394: # Successfully stored
1.508     www      4395: 	      $request->print('.');
1.627     www      4396: # Remove from grading queue
                   4397:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4398:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4399:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4400:                                              $domain,$username);
                   4401:               $countdone++;
                   4402:            } else {
1.508     www      4403: 	      $request->print("<p><span class=\"LC_error\">".
                   4404:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4405:                                   "$username:$domain",$result)."</span></p>");
                   4406: 	   }
                   4407: 	   $request->rflush();
                   4408:         }
1.41      ng       4409:     }
1.570     www      4410:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4411:     if (@warnings) {
                   4412:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4413:         $request->print(join(', ',@warnings));
                   4414:     }
1.41      ng       4415:     if (@skipped) {
1.571     www      4416: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4417:         $request->print(join(', ',@skipped));
1.106     albertel 4418:     }
                   4419:     if (@notallowed) {
1.571     www      4420: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4421: 	$request->print(join(', ',@notallowed));
1.41      ng       4422:     }
1.106     albertel 4423:     $request->print("<br />\n");
1.345     bowersj2 4424:     return $error_msg;
1.26      albertel 4425: }
1.44      ng       4426: #------------- end of section for handling csv file upload ---------
                   4427: #
                   4428: #-------------------------------------------------------------------
                   4429: #
1.122     ng       4430: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4431: #
                   4432: #--- Select a page/sequence and a student to grade
1.68      ng       4433: sub pickStudentPage {
1.608     www      4434:     my ($request,$symb) = @_;
1.68      ng       4435: 
1.539     riegler  4436:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4437:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4438: 
                   4439: function checkPickOne(formname) {
1.76      ng       4440:     if (radioSelection(formname.student) == null) {
1.539     riegler  4441: 	alert("$alertmsg");
1.68      ng       4442: 	return;
                   4443:     }
1.125     ng       4444:     ptr = pullDownSelection(formname.selectpage);
                   4445:     formname.page.value = formname["page"+ptr].value;
                   4446:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4447:     formname.submit();
                   4448: }
                   4449: 
                   4450: LISTJAVASCRIPT
1.118     ng       4451:     &commonJSfunctions($request);
1.608     www      4452: 
1.257     albertel 4453:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4454:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4455:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4456: 
1.398     albertel 4457:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4458: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4459: 
1.80      ng       4460:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4461:     my $map_error;
                   4462:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4463:     if ($map_error) {
                   4464:         $request->print(&navmap_errormsg());
                   4465:         return; 
                   4466:     }
1.137     albertel 4467:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4468: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4469: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4470: 
                   4471:     # Collection of hidden fields
1.70      ng       4472:     my $ctr=0;
1.68      ng       4473:     foreach (@$titles) {
1.700     bisitz   4474:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4475:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4476:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4477:         $ctr++;
1.68      ng       4478:     }
1.700     bisitz   4479:     $result.='<input type="hidden" name="page" />'."\n".
                   4480:         '<input type="hidden" name="title" />'."\n";
                   4481: 
                   4482:     $result.=&build_section_inputs();
                   4483:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4484:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4485: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4486: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4487: 
1.700     bisitz   4488:     # Show grading options
                   4489:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4490:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4491:     $ctr=0;
                   4492:     foreach (@$titles) {
                   4493: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4494: 	$select.='<option value="'.$ctr.'"'.
                   4495: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4496: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4497: 	$ctr++;
                   4498:     }
1.700     bisitz   4499:     $select.= '</select>';
1.68      ng       4500: 
1.700     bisitz   4501:     $result.=
                   4502:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4503:        .$select
                   4504:        .&Apache::lonhtmlcommon::row_closure();
                   4505: 
                   4506:     $result.=
                   4507:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4508:        .'<label><input type="radio" name="vProb" value="no"'
                   4509:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4510:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4511:            .&mt('yes').'</label>'."\n"
                   4512:        .&Apache::lonhtmlcommon::row_closure();
                   4513: 
                   4514:     $result.=
                   4515:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4516:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4517:            .&mt('none').' </label>'."\n"
                   4518:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4519:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4520:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4521:            .&mt('all submissions with details').' </label>'
                   4522:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4523:     
1.700     bisitz   4524:     $result.=
                   4525:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4526:        .'<input type="text" name="CODE" value="" />'
                   4527:        .&Apache::lonhtmlcommon::row_closure(1)
                   4528:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4529: 
1.700     bisitz   4530:     # Show list of students to select for grading
                   4531:     $result.='<br /><input type="button" '.
1.589     bisitz   4532:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4533: 
1.68      ng       4534:     $request->print($result);
                   4535: 
1.485     albertel 4536:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4537: 	&Apache::loncommon::start_data_table().
                   4538: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4539: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4540: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4541: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4542: 	'<th>'.&nameUserString('header').'</th>'.
                   4543: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4544:  
1.76      ng       4545:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4546:     my $ptr = 1;
1.294     albertel 4547:     foreach my $student (sort 
                   4548: 			 {
                   4549: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4550: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4551: 			     }
                   4552: 			     return $a cmp $b;
                   4553: 			 } (keys(%$fullname))) {
1.68      ng       4554: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4555: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4556:                                   : '</td>');
1.126     ng       4557: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4558: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4559: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4560: 	$studentTable.=
                   4561: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4562:                          : '');
1.68      ng       4563: 	$ptr++;
                   4564:     }
1.484     albertel 4565:     if ($ptr%2 == 0) {
                   4566: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4567: 	    &Apache::loncommon::end_data_table_row();
                   4568:     }
                   4569:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4570:     $studentTable.='<input type="button" '.
1.589     bisitz   4571:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4572: 
                   4573:     $request->print($studentTable);
                   4574: 
                   4575:     return '';
                   4576: }
                   4577: 
                   4578: sub getSymbMap {
1.582     raeburn  4579:     my ($map_error) = @_;
1.132     bowersj2 4580:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4581:     unless (ref($navmap)) {
                   4582:         if (ref($map_error)) {
                   4583:             $$map_error = 'navmap';
                   4584:         }
                   4585:         return;
                   4586:     }
1.68      ng       4587:     my %symbx = ();
                   4588:     my @titles = ();
1.117     bowersj2 4589:     my $minder = 0;
                   4590: 
                   4591:     # Gather every sequence that has problems.
1.240     albertel 4592:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4593: 					       1,0,1);
1.117     bowersj2 4594:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4595: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4596: 	    my $title = $minder.'.'.
                   4597: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4598: 	    push(@titles, $title); # minder in case two titles are identical
                   4599: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4600: 	    $minder++;
1.241     albertel 4601: 	}
1.68      ng       4602:     }
                   4603:     return \@titles,\%symbx;
                   4604: }
                   4605: 
1.72      ng       4606: #
                   4607: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4608: sub displayPage {
1.608     www      4609:     my ($request,$symb) = @_;
1.257     albertel 4610:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4611:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4612:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4613:     my $pageTitle = $env{'form.page'};
1.103     albertel 4614:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4615:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4616:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4617: 
                   4618:     #need to make sure we have the correct data for later EXT calls, 
                   4619:     #thus invalidate the cache
                   4620:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4621:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4622:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4623:     &Apache::lonnet::clear_EXT_cache_status();
                   4624: 
1.103     albertel 4625:     if (!&canview($usec)) {
1.712     bisitz   4626:         $request->print(
                   4627:             '<span class="LC_warning">'.
                   4628:             &mt('Unable to view requested student. ([_1])',
                   4629:                     $env{'form.student'}).
                   4630:             '</span>');
                   4631:         return;
1.103     albertel 4632:     }
1.398     albertel 4633:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4634:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4635: 	'</h3>'."\n";
1.500     albertel 4636:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4637:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4638: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4639:     } else {
                   4640: 	delete($env{'form.CODE'});
                   4641:     }
1.71      ng       4642:     &sub_page_js($request);
                   4643:     $request->print($result);
                   4644: 
1.132     bowersj2 4645:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4646:     unless (ref($navmap)) {
                   4647:         $request->print(&navmap_errormsg());
                   4648:         return;
                   4649:     }
1.257     albertel 4650:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4651:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4652:     if (!$map) {
1.485     albertel 4653: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4654: 	return; 
                   4655:     }
1.68      ng       4656:     my $iterator = $navmap->getIterator($map->map_start(),
                   4657: 					$map->map_finish());
                   4658: 
1.71      ng       4659:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4660: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4661: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4662: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4663: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4664: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4665: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4666: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4667: 
1.382     albertel 4668:     if (defined($env{'form.CODE'})) {
                   4669: 	$studentTable.=
                   4670: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4671:     }
1.381     albertel 4672:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4673: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4674: 
1.594     bisitz   4675:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4676:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4677:         '</span>'."\n".
1.484     albertel 4678: 	&Apache::loncommon::start_data_table().
                   4679: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4680: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4681: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4682: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4683: 
1.329     albertel 4684:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4685:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4686:     $iterator->next(); # skip the first BEGIN_MAP
                   4687:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4688:     while ($depth > 0) {
1.68      ng       4689:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4690:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4691: 
1.385     albertel 4692:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4693: 	    my $parts = $curRes->parts();
1.68      ng       4694:             my $title = $curRes->compTitle();
1.71      ng       4695: 	    my $symbx = $curRes->symb();
1.484     albertel 4696: 	    $studentTable.=
                   4697: 		&Apache::loncommon::start_data_table_row().
                   4698: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4699: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4700: 		                        : '<br />('.&mt('[_1]parts',
                   4701: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4702: 		 ).
                   4703: 		 '</td>';
1.71      ng       4704: 	    $studentTable.='<td valign="top">';
1.382     albertel 4705: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4706: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4707: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4708: 					     undef,'both',\%form);
1.71      ng       4709: 	    } else {
1.382     albertel 4710: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4711: 		$companswer =~ s|<form(.*?)>||g;
                   4712: 		$companswer =~ s|</form>||g;
1.71      ng       4713: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4714: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4715: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4716: #		}
1.116     ng       4717: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4718: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4719: 	    }
                   4720: 
1.257     albertel 4721: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4722: 
1.257     albertel 4723: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4724: 		if ($record{'version'} eq '') {
1.485     albertel 4725: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4726: 		} else {
1.116     ng       4727: 		    my %responseType = ();
                   4728: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4729: 			my @responseIds =$curRes->responseIds($partid);
                   4730: 			my @responseType =$curRes->responseType($partid);
                   4731: 			my %responseIds;
                   4732: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4733: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4734: 			}
                   4735: 			$responseType{$partid} = \%responseIds;
1.116     ng       4736: 		    }
1.148     albertel 4737: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4738: 
1.71      ng       4739: 		}
1.257     albertel 4740: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4741: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4742: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4743: 									$env{'request.course.id'},
1.71      ng       4744: 									'','.submission');
                   4745:  
                   4746: 	    }
1.103     albertel 4747: 	    if (&canmodify($usec)) {
1.585     bisitz   4748:             $studentTable.=&gradeBox_start();
1.103     albertel 4749: 		foreach my $partid (@{$parts}) {
                   4750: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4751: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4752: 		    $question++;
                   4753: 		}
1.585     bisitz   4754:             $studentTable.=&gradeBox_end();
1.196     albertel 4755: 		$prob++;
1.71      ng       4756: 	    }
                   4757: 	    $studentTable.='</td></tr>';
1.68      ng       4758: 
1.103     albertel 4759: 	}
1.68      ng       4760:         $curRes = $iterator->next();
                   4761:     }
                   4762: 
1.589     bisitz   4763:     $studentTable.=
                   4764:         '</table>'."\n".
                   4765:         '<input type="button" value="'.&mt('Save').'" '.
                   4766:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4767:         '</form>'."\n";
1.71      ng       4768:     $request->print($studentTable);
                   4769: 
                   4770:     return '';
1.119     ng       4771: }
                   4772: 
                   4773: sub displaySubByDates {
1.148     albertel 4774:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4775:     my $isCODE=0;
1.335     albertel 4776:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4777:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4778:     my $studentTable=&Apache::loncommon::start_data_table().
                   4779: 	&Apache::loncommon::start_data_table_header_row().
                   4780: 	'<th>'.&mt('Date/Time').'</th>'.
                   4781: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4782:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4783: 	'<th>'.&mt('Submission').'</th>'.
                   4784: 	'<th>'.&mt('Status').'</th>'.
                   4785: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4786:     my ($version);
                   4787:     my %mark;
1.148     albertel 4788:     my %orders;
1.119     ng       4789:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4790:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4791: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4792:     }
1.335     albertel 4793: 
                   4794:     my $interaction;
1.525     raeburn  4795:     my $no_increment = 1;
1.640     raeburn  4796:     my %lastrndseed;
1.119     ng       4797:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4798: 	my $timestamp = 
                   4799: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4800: 	if (exists($$record{$version.':resource.0.version'})) {
                   4801: 	    $interaction = $$record{$version.':resource.0.version'};
                   4802: 	}
1.671     raeburn  4803:         if ($isTask && $env{'form.previousversion'}) {
                   4804:             next unless ($interaction == $env{'form.previousversion'});
                   4805:         }
1.335     albertel 4806: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4807: 		             : "$version:resource");
1.467     albertel 4808: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4809: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4810: 	if ($isCODE) {
                   4811: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4812: 	}
1.671     raeburn  4813:         if ($isTask) {
                   4814:             $studentTable.='<td>'.$interaction.'</td>';
                   4815:         }
1.119     ng       4816: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4817: 	my @displaySub = ();
                   4818: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4819:             my ($hidden,$type);
                   4820:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4821:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4822:                 $hidden = 1;
                   4823:             }
1.335     albertel 4824: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4825: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4826: 	    
1.122     ng       4827: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4828: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4829: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4830: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4831: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4832:                     
1.335     albertel 4833: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4834: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4835:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4836:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4837:                                    .' <span class="LC_internal_info">'
1.625     www      4838:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4839:                                    .'</span>'
                   4840:                                    .' <b>';
1.596     raeburn  4841:                     if ($hidden) {
                   4842:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4843:                     } else {
1.640     raeburn  4844:                         my ($trial,$rndseed,$newvariation);
                   4845:                         if ($type eq 'randomizetry') {
                   4846:                             $trial = $$record{"$where.$partid.tries"};
                   4847:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4848:                         }
1.596     raeburn  4849: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4850: 			    $displaySub[0].=&mt('Trial not counted');
                   4851: 		        } else {
                   4852: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4853: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4854:                             if ($rndseed || $lastrndseed{$partid}) {
                   4855:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4856:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4857:                                 }
                   4858:                             }
                   4859:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4860: 		        }
                   4861: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4862:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4863: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4864: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4865: 			    $orders{$partid}->{$responseId}=
                   4866: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4867:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4868: 		        }
1.640     raeburn  4869: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4870: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4871: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4872:                     }
1.147     albertel 4873: 		}
                   4874: 	    }
1.335     albertel 4875: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4876: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4877: 				    $$record{"$where.$partid.checkedin"},
                   4878: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4879: 					'<br />';
1.335     albertel 4880: 	    }
                   4881: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4882: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4883: 		    lc($$record{"$where.$partid.award"}).' '.
                   4884: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4885: 		    '<br />';
                   4886: 	    }
1.335     albertel 4887: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4888: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4889: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4890: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4891: 		$displaySub[2].=
                   4892: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4893: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4894: 	    }
                   4895: 	}
                   4896: 	# needed because old essay regrader has not parts info
                   4897: 	if (exists $$record{"$version:resource.regrader"}) {
                   4898: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4899: 	}
                   4900: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4901: 	if ($displaySub[2]) {
1.467     albertel 4902: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4903: 	}
1.467     albertel 4904: 	$studentTable.='&nbsp;</td>'.
                   4905: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4906:     }
1.467     albertel 4907:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4908:     return $studentTable;
1.71      ng       4909: }
                   4910: 
                   4911: sub updateGradeByPage {
1.608     www      4912:     my ($request,$symb) = @_;
1.71      ng       4913: 
1.257     albertel 4914:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4915:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4916:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4917:     my $pageTitle = $env{'form.page'};
1.103     albertel 4918:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4919:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4920:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4921:     if (!&canmodify($usec)) {
1.526     raeburn  4922: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4923: 	return;
                   4924:     }
1.398     albertel 4925:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4926:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4927: 	'</h3>'."\n";
1.70      ng       4928: 
1.68      ng       4929:     $request->print($result);
                   4930: 
1.582     raeburn  4931: 
1.132     bowersj2 4932:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4933:     unless (ref($navmap)) {
                   4934:         $request->print(&navmap_errormsg());
                   4935:         return;
                   4936:     }
1.257     albertel 4937:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4938:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4939:     if (!$map) {
1.527     raeburn  4940: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4941: 	return; 
                   4942:     }
1.71      ng       4943:     my $iterator = $navmap->getIterator($map->map_start(),
                   4944: 					$map->map_finish());
1.70      ng       4945: 
1.484     albertel 4946:     my $studentTable=
                   4947: 	&Apache::loncommon::start_data_table().
                   4948: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4949: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4950: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4951: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4952: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4953: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4954: 
                   4955:     $iterator->next(); # skip the first BEGIN_MAP
                   4956:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4957:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4958:     while ($depth > 0) {
1.71      ng       4959:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4960:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4961: 
1.385     albertel 4962:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4963: 	    my $parts = $curRes->parts();
1.71      ng       4964:             my $title = $curRes->compTitle();
                   4965: 	    my $symbx = $curRes->symb();
1.484     albertel 4966: 	    $studentTable.=
                   4967: 		&Apache::loncommon::start_data_table_row().
                   4968: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4969: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4970:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4971: 		.')').'</td>';
1.71      ng       4972: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4973: 
                   4974: 	    my %newrecord=();
                   4975: 	    my @displayPts=();
1.269     raeburn  4976:             my %aggregate = ();
                   4977:             my $aggregateflag = 0;
1.71      ng       4978: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4979: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4980: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4981: 
1.257     albertel 4982: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4983: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4984: 		my $partial = $newpts/$wgt;
                   4985: 		my $score;
                   4986: 		if ($partial > 0) {
                   4987: 		    $score = 'correct_by_override';
1.125     ng       4988: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4989: 		    $score = 'incorrect_by_override';
                   4990: 		}
1.257     albertel 4991: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4992: 		if ($dropMenu eq 'excused') {
1.71      ng       4993: 		    $partial = '';
                   4994: 		    $score = 'excused';
1.125     ng       4995: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4996: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4997: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4998: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4999: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5000: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5001: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5002: 		    $changeflag++;
                   5003: 		    $newpts = '';
1.269     raeburn  5004:                     
                   5005:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5006:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5007:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5008:                     if ($aggtries > 0) {
                   5009:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5010:                         $aggregateflag = 1;
                   5011:                     }
1.71      ng       5012: 		}
1.324     albertel 5013: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5014: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5015: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5016: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5017: 		    '&nbsp;<br />';
1.526     raeburn  5018: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5019: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5020: 		    '&nbsp;<br />';
1.71      ng       5021: 		$question++;
1.380     albertel 5022: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5023: 
1.71      ng       5024: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5025: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5026: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5027: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5028: 
                   5029: 		$changeflag++;
                   5030: 	    }
                   5031: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5032: 		my %record = 
                   5033: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5034: 					     $udom,$uname);
                   5035: 
                   5036: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5037: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5038: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5039: 		    $newrecord{'resource.CODE'} = '';
                   5040: 		}
1.257     albertel 5041: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5042: 					$udom,$uname);
1.382     albertel 5043: 		%record = &Apache::lonnet::restore($symbx,
                   5044: 						   $env{'request.course.id'},
                   5045: 						   $udom,$uname);
1.380     albertel 5046: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5047: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5048: 	    }
1.380     albertel 5049: 	    
1.269     raeburn  5050:             if ($aggregateflag) {
                   5051:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5052:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5053:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5054:             }
1.125     ng       5055: 
1.71      ng       5056: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5057: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5058: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5059: 
1.196     albertel 5060: 	    $prob++;
1.68      ng       5061: 	}
1.71      ng       5062:         $curRes = $iterator->next();
1.68      ng       5063:     }
1.98      albertel 5064: 
1.484     albertel 5065:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5066:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5067: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5068: 		  $changeflag));
1.76      ng       5069:     $request->print($grademsg.$studentTable);
1.68      ng       5070: 
1.70      ng       5071:     return '';
                   5072: }
                   5073: 
1.72      ng       5074: #-------- end of section for handling grading by page/sequence ---------
                   5075: #
                   5076: #-------------------------------------------------------------------
                   5077: 
1.581     www      5078: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5079: #
                   5080: #------ start of section for handling grading by page/sequence ---------
                   5081: 
1.423     albertel 5082: =pod
                   5083: 
                   5084: =head1 Bubble sheet grading routines
                   5085: 
1.424     albertel 5086:   For this documentation:
                   5087: 
                   5088:    'scanline' refers to the full line of characters
                   5089:    from the file that we are parsing that represents one entire sheet
                   5090: 
                   5091:    'bubble line' refers to the data
1.659     raeburn  5092:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5093: 
                   5094: 
1.659     raeburn  5095: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5096: into a course. When a user wants to grade, they select a
1.659     raeburn  5097: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5098: one of the predefined configurations for what each scanline looks
                   5099: like.
                   5100: 
                   5101: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5102: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5103: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5104: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5105: invalid student/employee ID
1.424     albertel 5106: 
                   5107: If the CODE option is used that determines the randomization of the
1.556     weissno  5108: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5109: username:domain.
                   5110: 
                   5111: During the validation phase the instructor can choose to skip scanlines. 
                   5112: 
1.659     raeburn  5113: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5114: 
                   5115:   scantron_original_filename (unmodified original file)
                   5116:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5117:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5118: 
                   5119: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5120: correction information that isn't representable in the bubblesheet
1.424     albertel 5121: file (see &scantron_getfile() for more information)
                   5122: 
                   5123: After all scanlines are either valid, marked as valid or skipped, then
                   5124: foreach line foreach problem in the picked sequence, an ssi request is
                   5125: made that simulates a user submitting their selected letter(s) against
                   5126: the homework problem.
1.423     albertel 5127: 
                   5128: =over 4
                   5129: 
                   5130: 
                   5131: 
                   5132: =item defaultFormData
                   5133: 
                   5134:   Returns html hidden inputs used to hold context/default values.
                   5135: 
                   5136:  Arguments:
                   5137:   $symb - $symb of the current resource 
                   5138: 
                   5139: =cut
1.422     foxr     5140: 
1.81      albertel 5141: sub defaultFormData {
1.324     albertel 5142:     my ($symb)=@_;
1.613     www      5143:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5144: }
                   5145: 
1.447     foxr     5146: 
1.423     albertel 5147: =pod 
                   5148: 
                   5149: =item getSequenceDropDown
                   5150: 
                   5151:    Return html dropdown of possible sequences to grade
                   5152:  
                   5153:  Arguments:
1.582     raeburn  5154:    $symb - $symb of the current resource
                   5155:    $map_error - ref to scalar which will container error if
                   5156:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5157: 
                   5158: =cut
1.422     foxr     5159: 
1.75      albertel 5160: sub getSequenceDropDown {
1.582     raeburn  5161:     my ($symb,$map_error)=@_;
1.75      albertel 5162:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5163:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5164:     if (ref($map_error)) {
                   5165:         return if ($$map_error);
                   5166:     }
1.137     albertel 5167:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5168:     my $ctr=0;
                   5169:     foreach (@$titles) {
                   5170: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5171: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5172: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5173: 	    '>'.$showtitle.'</option>'."\n";
                   5174: 	$ctr++;
                   5175:     }
                   5176:     $result.= '</select>';
                   5177:     return $result;
                   5178: }
                   5179: 
1.495     albertel 5180: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5181:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5182: 
                   5183: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5184: 
1.509     raeburn  5185: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5186:                                    # matchresponse or rankresponse, where 
                   5187:                                    # an individual response can have multiple 
                   5188:                                    # lines
1.503     raeburn  5189: 
                   5190: my %responsetype_per_response;     # responsetype for each response
                   5191: 
1.691     raeburn  5192: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5193:                                    # numbered response. Needed when randomorder
                   5194:                                    # or randompick are in use. Key is ID, value 
                   5195:                                    # is response number.
                   5196: 
1.495     albertel 5197: # Save and restore the bubble lines array to the form env.
                   5198: 
                   5199: 
                   5200: sub save_bubble_lines {
                   5201:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5202: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5203: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5204: 	    $first_bubble_line{$line};
1.503     raeburn  5205:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5206:             $subdivided_bubble_lines{$line};
                   5207:         $env{"form.scantron.responsetype.$line"} =
                   5208:             $responsetype_per_response{$line};
1.495     albertel 5209:     }
1.691     raeburn  5210:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5211:         my $line = $masterseq_id_responsenum{$resid};
                   5212:         $env{"form.scantron.residpart.$line"} = $resid;
                   5213:     }
1.495     albertel 5214: }
                   5215: 
                   5216: 
                   5217: sub restore_bubble_lines {
                   5218:     my $line = 0;
                   5219:     %bubble_lines_per_response = ();
1.691     raeburn  5220:     %masterseq_id_responsenum = ();
1.495     albertel 5221:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5222: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5223: 	$bubble_lines_per_response{$line} = $value;
                   5224: 	$first_bubble_line{$line}  =
                   5225: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5226:         $subdivided_bubble_lines{$line} =
                   5227:             $env{"form.scantron.sub_bubblelines.$line"};
                   5228:         $responsetype_per_response{$line} =
                   5229:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5230:         my $id = $env{"form.scantron.residpart.$line"};
                   5231:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5232: 	$line++;
                   5233:     }
                   5234: }
                   5235: 
1.423     albertel 5236: =pod 
                   5237: 
                   5238: =item scantron_filenames
                   5239: 
                   5240:    Returns a list of the scantron files in the current course 
                   5241: 
                   5242: =cut
1.422     foxr     5243: 
1.202     albertel 5244: sub scantron_filenames {
1.257     albertel 5245:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5246:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5247:     my $getpropath = 1;
1.662     raeburn  5248:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5249:                                                         $cname,$getpropath);
1.202     albertel 5250:     my @possiblenames;
1.662     raeburn  5251:     if (ref($dirlist) eq 'ARRAY') {
                   5252:         foreach my $filename (sort(@{$dirlist})) {
                   5253: 	    ($filename)=split(/&/,$filename);
                   5254: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5255: 	    $filename=~s/^scantron_orig_//;
                   5256: 	    push(@possiblenames,$filename);
                   5257:         }
1.202     albertel 5258:     }
                   5259:     return @possiblenames;
                   5260: }
                   5261: 
1.423     albertel 5262: =pod 
                   5263: 
                   5264: =item scantron_uploads
                   5265: 
                   5266:    Returns  html drop-down list of scantron files in current course.
                   5267: 
                   5268:  Arguments:
                   5269:    $file2grade - filename to set as selected in the dropdown
                   5270: 
                   5271: =cut
1.422     foxr     5272: 
1.202     albertel 5273: sub scantron_uploads {
1.209     ng       5274:     my ($file2grade) = @_;
1.202     albertel 5275:     my $result=	'<select name="scantron_selectfile">';
                   5276:     $result.="<option></option>";
                   5277:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5278: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5279:     }
                   5280:     $result.="</select>";
                   5281:     return $result;
                   5282: }
                   5283: 
1.423     albertel 5284: =pod 
                   5285: 
                   5286: =item scantron_scantab
                   5287: 
                   5288:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5289:   file.
                   5290: 
                   5291: =cut
1.422     foxr     5292: 
1.82      albertel 5293: sub scantron_scantab {
                   5294:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5295:     $result.='<option></option>'."\n";
1.518     raeburn  5296:     my @lines = &get_scantronformat_file();
                   5297:     if (@lines > 0) {
                   5298:         foreach my $line (@lines) {
                   5299:             next if (($line =~ /^\#/) || ($line eq ''));
                   5300: 	    my ($name,$descrip)=split(/:/,$line);
                   5301: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5302:         }
1.82      albertel 5303:     }
                   5304:     $result.='</select>'."\n";
1.518     raeburn  5305:     return $result;
                   5306: }
                   5307: 
                   5308: =pod
                   5309: 
                   5310: =item get_scantronformat_file
                   5311: 
                   5312:   Returns an array containing lines from the scantron format file for
                   5313:   the domain of the course.
                   5314: 
                   5315:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5316:   lines are from this file.
                   5317: 
                   5318:   Otherwise, if a default.tab has been published in RES space by the 
                   5319:   domainconfig user, lines are from this file.
                   5320: 
                   5321:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5322:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5323: 
1.518     raeburn  5324: =cut
                   5325: 
                   5326: sub get_scantronformat_file {
                   5327:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5328:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5329:     my $gottab = 0;
                   5330:     my @lines;
                   5331:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5332:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5333:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5334:             if ($formatfile ne '-1') {
                   5335:                 @lines = split("\n",$formatfile,-1);
                   5336:                 $gottab = 1;
                   5337:             }
                   5338:         }
                   5339:     }
                   5340:     if (!$gottab) {
                   5341:         my $confname = $cdom.'-domainconfig';
                   5342:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5343:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5344:         if ($formatfile ne '-1') {
                   5345:             @lines = split("\n",$formatfile,-1);
                   5346:             $gottab = 1;
                   5347:         }
                   5348:     }
                   5349:     if (!$gottab) {
1.519     raeburn  5350:         my @domains = &Apache::lonnet::current_machine_domains();
                   5351:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5352:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5353:             @lines = <$fh>;
                   5354:             close($fh);
                   5355:         } else {
                   5356:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5357:             @lines = <$fh>;
                   5358:             close($fh);
                   5359:         }
1.518     raeburn  5360:     }
                   5361:     return @lines;
1.82      albertel 5362: }
                   5363: 
1.423     albertel 5364: =pod 
                   5365: 
                   5366: =item scantron_CODElist
                   5367: 
                   5368:   Returns html drop down of the saved CODE lists from current course,
                   5369:   generated from earlier printings.
                   5370: 
                   5371: =cut
1.422     foxr     5372: 
1.186     albertel 5373: sub scantron_CODElist {
1.257     albertel 5374:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5375:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5376:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5377:     my $namechoice='<option></option>';
1.225     albertel 5378:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5379: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5380: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5381: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5382:     }
                   5383:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5384:     return $namechoice;
                   5385: }
                   5386: 
1.423     albertel 5387: =pod 
                   5388: 
                   5389: =item scantron_CODEunique
                   5390: 
                   5391:   Returns the html for "Each CODE to be used once" radio.
                   5392: 
                   5393: =cut
1.422     foxr     5394: 
1.186     albertel 5395: sub scantron_CODEunique {
1.532     bisitz   5396:     my $result='<span class="LC_nobreak">
1.272     albertel 5397:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5398:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5399:                 </span>
1.532     bisitz   5400:                 <span class="LC_nobreak">
1.272     albertel 5401:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5402:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5403:                 </span>';
1.186     albertel 5404:     return $result;
                   5405: }
1.423     albertel 5406: 
                   5407: =pod 
                   5408: 
                   5409: =item scantron_selectphase
                   5410: 
1.659     raeburn  5411:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5412:   Allows for - starting a grading run.
1.424     albertel 5413:              - downloading existing scan data (original, corrected
1.423     albertel 5414:                                                 or skipped info)
                   5415: 
                   5416:              - uploading new scan data
                   5417: 
                   5418:  Arguments:
                   5419:   $r          - The Apache request object
                   5420:   $file2grade - name of the file that contain the scanned data to score
                   5421: 
                   5422: =cut
1.186     albertel 5423: 
1.75      albertel 5424: sub scantron_selectphase {
1.608     www      5425:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5426:     if (!$symb) {return '';}
1.582     raeburn  5427:     my $map_error;
                   5428:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5429:     if ($map_error) {
                   5430:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5431:         return;
                   5432:     }
1.324     albertel 5433:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5434:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5435:     my $format_selector=&scantron_scantab();
1.186     albertel 5436:     my $CODE_selector=&scantron_CODElist();
                   5437:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5438:     my $result;
1.422     foxr     5439: 
1.513     foxr     5440:     $ssi_error = 0;
                   5441: 
1.606     wenzelju 5442:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5443:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5444: 
                   5445: 	# Chunk of form to prompt for a scantron file upload.
                   5446: 
                   5447:         $r->print('
                   5448:     <br />
                   5449:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5450:        '.&Apache::loncommon::start_data_table_header_row().'
                   5451:             <th>
                   5452:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5453:             </th>
                   5454:        '.&Apache::loncommon::end_data_table_header_row().'
                   5455:        '.&Apache::loncommon::start_data_table_row().'
                   5456:             <td>
                   5457: ');
1.608     www      5458:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5459:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5460:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5461:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5462:     function checkUpload(formname) {
                   5463: 	if (formname.upfile.value == "") {
                   5464: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5465: 	    return false;
                   5466: 	}
                   5467: 	formname.submit();
                   5468:     }'));
                   5469:     $r->print('
                   5470:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5471:                 '.$default_form_data.'
                   5472:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5473:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5474:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5475:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5476:                 <br />
                   5477:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5478:               </form>
                   5479: ');
                   5480: 
                   5481:         $r->print('
                   5482:             </td>
                   5483:        '.&Apache::loncommon::end_data_table_row().'
                   5484:        '.&Apache::loncommon::end_data_table().'
                   5485: ');
                   5486:     }
                   5487: 
1.422     foxr     5488:     # Chunk of form to prompt for a file to grade and how:
                   5489: 
1.489     albertel 5490:     $result.= '
                   5491:     <br />
                   5492:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5493:     <input type="hidden" name="command" value="scantron_warning" />
                   5494:     '.$default_form_data.'
                   5495:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5496:        '.&Apache::loncommon::start_data_table_header_row().'
                   5497:             <th colspan="2">
1.492     albertel 5498:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5499:             </th>
                   5500:        '.&Apache::loncommon::end_data_table_header_row().'
                   5501:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5502:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5503:        '.&Apache::loncommon::end_data_table_row().'
                   5504:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5505:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5506:        '.&Apache::loncommon::end_data_table_row().'
                   5507:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5508:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5509:        '.&Apache::loncommon::end_data_table_row().'
                   5510:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5511:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5512:        '.&Apache::loncommon::end_data_table_row().'
                   5513:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5514:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5515:        '.&Apache::loncommon::end_data_table_row().'
                   5516:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5517: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5518:             <td>
1.492     albertel 5519: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5520:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5521:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5522: 	    </td>
1.489     albertel 5523:        '.&Apache::loncommon::end_data_table_row().'
                   5524:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5525:             <td colspan="2">
1.572     www      5526:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5527:             </td>
1.489     albertel 5528:        '.&Apache::loncommon::end_data_table_row().'
                   5529:     '.&Apache::loncommon::end_data_table().'
                   5530:     </form>
                   5531: ';
1.162     albertel 5532:    
                   5533:     $r->print($result);
                   5534: 
1.422     foxr     5535: 
                   5536: 
                   5537:     # Chunk of the form that prompts to view a scoring office file,
                   5538:     # corrected file, skipped records in a file.
                   5539: 
1.489     albertel 5540:     $r->print('
                   5541:    <br />
                   5542:    <form action="/adm/grades" name="scantron_download">
                   5543:      '.$default_form_data.'
                   5544:      <input type="hidden" name="command" value="scantron_download" />
                   5545:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5546:        '.&Apache::loncommon::start_data_table_header_row().'
                   5547:               <th>
1.492     albertel 5548:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5549:               </th>
                   5550:        '.&Apache::loncommon::end_data_table_header_row().'
                   5551:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5552:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5553:                 <br />
1.492     albertel 5554:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5555:        '.&Apache::loncommon::end_data_table_row().'
                   5556:      '.&Apache::loncommon::end_data_table().'
                   5557:    </form>
                   5558:    <br />
                   5559: ');
1.162     albertel 5560: 
1.457     banghart 5561:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5562: 
1.694     bisitz   5563:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5564:              $default_form_data."\n".
                   5565:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5566:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5567:              '<th colspan="2">
1.572     www      5568:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5569:              '</th>'."\n".
                   5570:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5571:               &Apache::loncommon::start_data_table_row()."\n".
                   5572:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5573:               '<td> '.$sequence_selector.' </td>'.
                   5574:               &Apache::loncommon::end_data_table_row()."\n".
                   5575:               &Apache::loncommon::start_data_table_row()."\n".
                   5576:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5577:               '<td> '.$file_selector.' </td>'."\n".
                   5578:               &Apache::loncommon::end_data_table_row()."\n".
                   5579:               &Apache::loncommon::start_data_table_row()."\n".
                   5580:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5581:               '<td> '.$format_selector.' </td>'."\n".
                   5582:               &Apache::loncommon::end_data_table_row()."\n".
                   5583:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5584:               '<td> '.&mt('Options').' </td>'."\n".
                   5585:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5586:               &Apache::loncommon::end_data_table_row()."\n".
                   5587:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5588:               '<td colspan="2">'."\n".
                   5589:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5590:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5591:               '</td>'."\n".
                   5592:               &Apache::loncommon::end_data_table_row()."\n".
                   5593:               &Apache::loncommon::end_data_table()."\n".
                   5594:               '</form><br />');
                   5595:     return;
1.75      albertel 5596: }
                   5597: 
1.423     albertel 5598: =pod
                   5599: 
                   5600: =item get_scantron_config
                   5601: 
1.711     bisitz   5602:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5603:    hash of configuration file fields.
                   5604: 
                   5605:  Arguments:
                   5606:     which - the name of the configuration to parse from the file.
                   5607: 
                   5608: 
                   5609:  Returns:
                   5610:             If the named configuration is not in the file, an empty
                   5611:             hash is returned.
                   5612:     a hash with the fields
                   5613:       name         - internal name for the this configuration setup
                   5614:       description  - text to display to operator that describes this config
                   5615:       CODElocation - if 0 or the string 'none'
                   5616:                           - no CODE exists for this config
                   5617:                      if -1 || the string 'letter'
                   5618:                           - a CODE exists for this config and is
                   5619:                             a string of letters
                   5620:                      Unsupported value (but planned for future support)
                   5621:                           if a positive integer
                   5622:                                - The CODE exists as the first n items from
                   5623:                                  the question section of the form
                   5624:                           if the string 'number'
                   5625:                                - The CODE exists for this config and is
                   5626:                                  a string of numbers
                   5627:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5628:                      the CODE starts
                   5629:       CODElength  - length of the CODE
1.573     bisitz   5630:       IDstart     - column where the student/employee ID starts
1.556     weissno  5631:       IDlength    - length of the student/employee ID info
1.423     albertel 5632:       Qstart      - column where the information from the bubbled
                   5633:                     'questions' start
                   5634:       Qlength     - number of columns comprising a single bubble line from
                   5635:                     the sheet. (usually either 1 or 10)
1.424     albertel 5636:       Qon         - either a single character representing the character used
1.423     albertel 5637:                     to signal a bubble was chosen in the positional setup, or
                   5638:                     the string 'letter' if the letter of the chosen bubble is
                   5639:                     in the final, or 'number' if a number representing the
                   5640:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5641:       Qoff        - the character used to represent that a bubble was
                   5642:                     left blank
1.423     albertel 5643:       PaperID     - if the scanning process generates a unique number for each
                   5644:                     sheet scanned the column that this ID number starts in
                   5645:       PaperIDlength - number of columns that comprise the unique ID number
                   5646:                       for the sheet of paper
1.424     albertel 5647:       FirstName   - column that the first name starts in
1.423     albertel 5648:       FirstNameLength - number of columns that the first name spans
                   5649:  
                   5650:       LastName    - column that the last name starts in
                   5651:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5652:       BubblesPerRow - number of bubbles available in each row used to 
                   5653:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5654: 
1.423     albertel 5655: =cut
1.422     foxr     5656: 
1.82      albertel 5657: sub get_scantron_config {
                   5658:     my ($which) = @_;
1.518     raeburn  5659:     my @lines = &get_scantronformat_file();
1.82      albertel 5660:     my %config;
1.157     albertel 5661:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5662:     foreach my $line (@lines) {
1.82      albertel 5663: 	my ($name,$descrip)=split(/:/,$line);
                   5664: 	if ($name ne $which ) { next; }
                   5665: 	chomp($line);
                   5666: 	my @config=split(/:/,$line);
                   5667: 	$config{'name'}=$config[0];
                   5668: 	$config{'description'}=$config[1];
                   5669: 	$config{'CODElocation'}=$config[2];
                   5670: 	$config{'CODEstart'}=$config[3];
                   5671: 	$config{'CODElength'}=$config[4];
                   5672: 	$config{'IDstart'}=$config[5];
                   5673: 	$config{'IDlength'}=$config[6];
                   5674: 	$config{'Qstart'}=$config[7];
1.497     foxr     5675:  	$config{'Qlength'}=$config[8];
1.82      albertel 5676: 	$config{'Qoff'}=$config[9];
                   5677: 	$config{'Qon'}=$config[10];
1.157     albertel 5678: 	$config{'PaperID'}=$config[11];
                   5679: 	$config{'PaperIDlength'}=$config[12];
                   5680: 	$config{'FirstName'}=$config[13];
                   5681: 	$config{'FirstNamelength'}=$config[14];
                   5682: 	$config{'LastName'}=$config[15];
                   5683: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5684:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5685: 	last;
                   5686:     }
                   5687:     return %config;
                   5688: }
                   5689: 
1.423     albertel 5690: =pod 
                   5691: 
                   5692: =item username_to_idmap
                   5693: 
1.556     weissno  5694:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5695:     student username:domain.
                   5696: 
                   5697:   Arguments:
                   5698: 
                   5699:     $classlist - reference to the class list hash. This is a hash
                   5700:                  keyed by student name:domain  whose elements are references
1.424     albertel 5701:                  to arrays containing various chunks of information
1.423     albertel 5702:                  about the student. (See loncoursedata for more info).
                   5703: 
                   5704:   Returns
                   5705:     %idmap - the constructed hash
                   5706: 
                   5707: =cut
                   5708: 
1.82      albertel 5709: sub username_to_idmap {
                   5710:     my ($classlist)= @_;
                   5711:     my %idmap;
                   5712:     foreach my $student (keys(%$classlist)) {
                   5713: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5714: 	    $student;
                   5715:     }
                   5716:     return %idmap;
                   5717: }
1.423     albertel 5718: 
                   5719: =pod
                   5720: 
1.424     albertel 5721: =item scantron_fixup_scanline
1.423     albertel 5722: 
                   5723:    Process a requested correction to a scanline.
                   5724: 
                   5725:   Arguments:
                   5726:     $scantron_config   - hash from &get_scantron_config()
                   5727:     $scan_data         - hash of correction information 
                   5728:                           (see &scantron_getfile())
                   5729:     $line              - existing scanline
                   5730:     $whichline         - line number of the passed in scanline
                   5731:     $field             - type of change to process 
                   5732:                          (either 
1.573     bisitz   5733:                           'ID'     -> correct the student/employee ID
1.423     albertel 5734:                           'CODE'   -> correct the CODE
                   5735:                           'answer' -> fixup the submitted answers)
                   5736:     
                   5737:    $args               - hash of additional info,
                   5738:                           - 'ID' 
                   5739:                                'newid' -> studentID to use in replacement
1.424     albertel 5740:                                           of existing one
1.423     albertel 5741:                           - 'CODE' 
                   5742:                                'CODE_ignore_dup' - set to true if duplicates
                   5743:                                                    should be ignored.
                   5744: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5745:                                         if the existing unfound code should
1.423     albertel 5746:                                         be used as is
                   5747:                           - 'answer'
                   5748:                                'response' - new answer or 'none' if blank
                   5749:                                'question' - the bubble line to change
1.503     raeburn  5750:                                'questionnum' - the question identifier,
                   5751:                                                may include subquestion. 
1.423     albertel 5752: 
                   5753:   Returns:
                   5754:     $line - the modified scanline
                   5755: 
                   5756:   Side effects: 
                   5757:     $scan_data - may be updated
                   5758: 
                   5759: =cut
                   5760: 
1.82      albertel 5761: 
1.157     albertel 5762: sub scantron_fixup_scanline {
                   5763:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5764:     if ($field eq 'ID') {
                   5765: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5766: 	    return ($line,1,'New value too large');
1.157     albertel 5767: 	}
                   5768: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5769: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5770: 				     $args->{'newid'});
                   5771: 	}
                   5772: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5773: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5774: 	if ($args->{'newid'}=~/^\s*$/) {
                   5775: 	    &scan_data($scan_data,"$whichline.user",
                   5776: 		       $args->{'username'}.':'.$args->{'domain'});
                   5777: 	}
1.186     albertel 5778:     } elsif ($field eq 'CODE') {
1.192     albertel 5779: 	if ($args->{'CODE_ignore_dup'}) {
                   5780: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5781: 	}
                   5782: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5783: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5784: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5785: 		return ($line,1,'New CODE value too large');
                   5786: 	    }
                   5787: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5788: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5789: 	    }
                   5790: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5791: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5792: 	}
1.157     albertel 5793:     } elsif ($field eq 'answer') {
1.497     foxr     5794: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5795: 	my $off=$scantron_config->{'Qoff'};
                   5796: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5797: 	my $answer=${off}x$length;
                   5798: 	if ($args->{'response'} eq 'none') {
                   5799: 	    &scan_data($scan_data,
1.503     raeburn  5800: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5801: 	} else {
                   5802: 	    if ($on eq 'letter') {
                   5803: 		my @alphabet=('A'..'Z');
                   5804: 		$answer=$alphabet[$args->{'response'}];
                   5805: 	    } elsif ($on eq 'number') {
                   5806: 		$answer=$args->{'response'}+1;
                   5807: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5808: 	    } else {
1.497     foxr     5809: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5810: 	    }
1.497     foxr     5811: 	    &scan_data($scan_data,
1.503     raeburn  5812: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5813: 	}
1.497     foxr     5814: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5815: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5816:     }
                   5817:     return $line;
                   5818: }
1.423     albertel 5819: 
                   5820: =pod
                   5821: 
                   5822: =item scan_data
                   5823: 
                   5824:     Edit or look up  an item in the scan_data hash.
                   5825: 
                   5826:   Arguments:
                   5827:     $scan_data  - The hash (see scantron_getfile)
                   5828:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5829:                   scantronfilename_key).
1.423     albertel 5830:     $data        - New value of the hash entry.
                   5831:     $delete      - If true, the entry is removed from the hash.
                   5832: 
                   5833:   Returns:
                   5834:     The new value of the hash table field (undefined if deleted).
                   5835: 
                   5836: =cut
                   5837: 
                   5838: 
1.157     albertel 5839: sub scan_data {
                   5840:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5841:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5842:     if (defined($value)) {
                   5843: 	$scan_data->{$filename.'_'.$key} = $value;
                   5844:     }
                   5845:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5846:     return $scan_data->{$filename.'_'.$key};
                   5847: }
1.423     albertel 5848: 
1.495     albertel 5849: # ----- These first few routines are general use routines.----
                   5850: 
                   5851: # Return the number of occurences of a pattern in a string.
                   5852: 
                   5853: sub occurence_count {
                   5854:     my ($string, $pattern) = @_;
                   5855: 
                   5856:     my @matches = ($string =~ /$pattern/g);
                   5857: 
                   5858:     return scalar(@matches);
                   5859: }
                   5860: 
                   5861: 
                   5862: # Take a string known to have digits and convert all the
                   5863: # digits into letters in the range J,A..I.
                   5864: 
                   5865: sub digits_to_letters {
                   5866:     my ($input) = @_;
                   5867: 
                   5868:     my @alphabet = ('J', 'A'..'I');
                   5869: 
                   5870:     my @input    = split(//, $input);
                   5871:     my $output ='';
                   5872:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5873: 	if ($input[$i] =~ /\d/) {
                   5874: 	    $output .= $alphabet[$input[$i]];
                   5875: 	} else {
                   5876: 	    $output .= $input[$i];
                   5877: 	}
                   5878:     }
                   5879:     return $output;
                   5880: }
                   5881: 
1.423     albertel 5882: =pod 
                   5883: 
                   5884: =item scantron_parse_scanline
                   5885: 
1.711     bisitz   5886:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5887: 
                   5888:  Arguments:
1.711     bisitz   5889:     line             - The text of the bubblesheet file line to process
1.423     albertel 5890:     whichline        - Line number
1.711     bisitz   5891:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5892:     scan_data        - Hash of extra information about the scanline
                   5893:                        (see scantron_getfile for more information)
                   5894:     just_header      - True if should not process question answers but only
                   5895:                        the stuff to the left of the answers.
1.691     raeburn  5896:     randomorder      - True if randomorder in use
                   5897:     randompick       - True if randompick in use
                   5898:     sequence         - Exam folder URL
                   5899:     master_seq       - Ref to array containing symbs in exam folder
                   5900:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5901:                        (corresponding values are resource objects)
                   5902:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5903:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5904:                        are refs to an array of resource objects, ordered
                   5905:                        according to order used for CODE, when randomorder
                   5906:                        and or randompick are in use.
                   5907:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5908:                        for current line to question number used for same question
                   5909:                         in "Master Sequence" (as seen by Course Coordinator).
                   5910:     startline        - Ref to hash where key is question number (0 is first)
                   5911:                        and value is number of first bubble line for current 
                   5912:                        student or code-based randompick and/or randomorder.
                   5913:     totalref         - Ref of scalar used to score total number of bubble
                   5914:                        lines needed for responses in a scan line (used when
                   5915:                        randompick in use. 
                   5916:     
1.423     albertel 5917:  Returns:
                   5918:    Hash containing the result of parsing the scanline
                   5919: 
                   5920:    Keys are all proceeded by the string 'scantron.'
                   5921: 
                   5922:        CODE    - the CODE in use for this scanline
                   5923:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5924:                  by the operator
                   5925:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5926:                             CODEs were selected, but the usage has been
                   5927:                             forced by the operator
1.556     weissno  5928:        ID  - student/employee ID
1.423     albertel 5929:        PaperID - if used, the ID number printed on the sheet when the 
                   5930:                  paper was scanned
                   5931:        FirstName - first name from the sheet
                   5932:        LastName  - last name from the sheet
                   5933: 
                   5934:      if just_header was not true these key may also exist
                   5935: 
1.447     foxr     5936:        missingerror - a list of bubble ranges that are considered to be answers
                   5937:                       to a single question that don't have any bubbles filled in.
                   5938:                       Of the form questionnumber:firstbubblenumber:count.
                   5939:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5940:                       to a single question that have more than one bubble filled in.
                   5941:                       Of the form questionnumber::firstbubblenumber:count
                   5942:    
                   5943:                 In the above, count is the number of bubble responses in the
                   5944:                 input line needed to represent the possible answers to the question.
                   5945:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5946:                 per line would have count = 2.
                   5947: 
1.423     albertel 5948:        maxquest     - the number of the last bubble line that was parsed
                   5949: 
                   5950:        (<number> starts at 1)
                   5951:        <number>.answer - zero or more letters representing the selected
                   5952:                          letters from the scanline for the bubble line 
                   5953:                          <number>.
                   5954:                          if blank there was either no bubble or there where
                   5955:                          multiple bubbles, (consult the keys missingerror and
                   5956:                          doubleerror if this is an error condition)
                   5957: 
                   5958: =cut
                   5959: 
1.82      albertel 5960: sub scantron_parse_scanline {
1.691     raeburn  5961:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5962:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5963:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5964: 
1.82      albertel 5965:     my %record;
1.691     raeburn  5966:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 5967:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5968: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5969: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5970: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5971: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5972: 	    $record{'scantron.CODE'}=substr($data,
                   5973: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5974: 					    $$scantron_config{'CODElength'});
1.191     albertel 5975: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5976: 		$record{'scantron.useCODE'}=1;
                   5977: 	    }
1.192     albertel 5978: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5979: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5980: 	    }
1.82      albertel 5981: 	} else {
                   5982: 	    #FIXME interpret first N questions
                   5983: 	}
                   5984:     }
1.83      albertel 5985:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5986: 				  $$scantron_config{'IDlength'});
1.157     albertel 5987:     $record{'scantron.PaperID'}=
                   5988: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5989: 	       $$scantron_config{'PaperIDlength'});
                   5990:     $record{'scantron.FirstName'}=
                   5991: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5992: 	       $$scantron_config{'FirstNamelength'});
                   5993:     $record{'scantron.LastName'}=
                   5994: 	substr($data,$$scantron_config{'LastName'}-1,
                   5995: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5996:     if ($just_header) { return \%record; }
1.194     albertel 5997: 
1.82      albertel 5998:     my @alphabet=('A'..'Z');
                   5999:     my $questnum=0;
1.447     foxr     6000:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6001: 
1.691     raeburn  6002:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6003:     if ($randompick || $randomorder) {
                   6004:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6005:                                          $master_seq,$symb_to_resource,
                   6006:                                          $partids_by_symb,$orderedforcode,
                   6007:                                          $respnumlookup,$startline);
                   6008:         if ($total) {
                   6009:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6010:         }
                   6011:         if (ref($totalref)) {
                   6012:             $$totalref = $total;
                   6013:         }
                   6014:     }
                   6015:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6016:     chomp($questions);		# Get rid of any trailing \n.
                   6017:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6018:     while (length($questions)) {
1.691     raeburn  6019:         my $answers_needed;
                   6020:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6021:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6022:         } else {
                   6023: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6024:         }
1.503     raeburn  6025:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6026:                              || 1;
                   6027:         $questnum++;
                   6028:         my $quest_id = $questnum;
                   6029:         my $currentquest = substr($questions,0,$answer_length);
                   6030:         $questions       = substr($questions,$answer_length);
                   6031:         if (length($currentquest) < $answer_length) { next; }
                   6032: 
1.691     raeburn  6033:         my $subdivided;
                   6034:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6035:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6036:         } else {
                   6037:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6038:         }
                   6039:         if ($subdivided =~ /,/) {
1.503     raeburn  6040:             my $subquestnum = 1;
                   6041:             my $subquestions = $currentquest;
1.691     raeburn  6042:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6043:             foreach my $subans (@subanswers_needed) {
                   6044:                 my $subans_length =
                   6045:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6046:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6047:                 $subquestions   = substr($subquestions,$subans_length);
                   6048:                 $quest_id = "$questnum.$subquestnum";
                   6049:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6050:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6051:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6052:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6053:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6054:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6055:                 } else {
                   6056:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6057:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6058:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6059:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6060:                 }
                   6061:                 $subquestnum ++;
                   6062:             }
                   6063:         } else {
                   6064:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6065:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6066:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6067:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6068:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6069:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6070:             } else {
                   6071:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6072:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6073:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6074:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6075:             }
                   6076:         }
                   6077:     }
                   6078:     $record{'scantron.maxquest'}=$questnum;
                   6079:     return \%record;
                   6080: }
1.447     foxr     6081: 
1.691     raeburn  6082: sub get_master_seq {
                   6083:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6084:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6085:                    (ref($symb_to_resource) eq 'HASH'));
                   6086:     my $resource_error;
                   6087:     foreach my $resource (@{$resources}) {
                   6088:         my $ressymb;
                   6089:         if (ref($resource)) {
                   6090:             $ressymb = $resource->symb();
                   6091:             push(@{$master_seq},$ressymb);
                   6092:             $symb_to_resource->{$ressymb} = $resource;
                   6093:         } else {
                   6094:             $resource_error = 1;
                   6095:             last;
                   6096:         }
                   6097:     }
                   6098:     return $resource_error;
                   6099: }
                   6100: 
                   6101: sub get_respnum_lookups {
                   6102:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6103:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6104:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6105:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6106:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6107:                    (ref($startline) eq 'HASH'));
                   6108:     my ($user,$scancode);
                   6109:     if ((exists($record->{'scantron.CODE'})) &&
                   6110:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6111:         $scancode = $record->{'scantron.CODE'};
                   6112:     } else {
                   6113:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6114:     }
                   6115:     my @mapresources =
                   6116:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6117:                      $orderedforcode);
                   6118:     my $total = 0;
                   6119:     my $count = 0;
                   6120:     foreach my $resource (@mapresources) {
                   6121:         my $id = $resource->id();
                   6122:         my $symb = $resource->symb();
                   6123:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6124:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6125:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6126:                 if ($respnum ne '') {
                   6127:                     $respnumlookup->{$count} = $respnum;
                   6128:                     $startline->{$count} = $total;
                   6129:                     $total += $bubble_lines_per_response{$respnum};
                   6130:                     $count ++;
                   6131:                 }
                   6132:             }
                   6133:         }
                   6134:     }
                   6135:     return $total;
                   6136: }
                   6137: 
1.503     raeburn  6138: sub scantron_validator_lettnum {
                   6139:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6140:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6141:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6142: 
                   6143:     # Qon 'letter' implies for each slot in currquest we have:
                   6144:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6145:     #    about anything else (esp. a value of Qoff) for missing
                   6146:     #    bubbles.
                   6147:     #
                   6148:     # Qon 'number' implies each slot gives a digit that indexes the
                   6149:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6150:     #    and * or ? for double bubbles on a single line.
                   6151:     #
1.447     foxr     6152: 
1.503     raeburn  6153:     my $matchon;
                   6154:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6155:         $matchon = '[A-Z]';
                   6156:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6157:         $matchon = '\d';
                   6158:     }
                   6159:     my $occurrences = 0;
1.691     raeburn  6160:     my $responsenum = $questnum-1;
                   6161:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6162:        $responsenum = $respnumlookup->{$questnum-1} 
                   6163:     }
                   6164:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6165:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6166:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6167:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6168:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6169:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6170:         my @singlelines = split('',$currquest);
                   6171:         foreach my $entry (@singlelines) {
                   6172:             $occurrences = &occurence_count($entry,$matchon);
                   6173:             if ($occurrences > 1) {
                   6174:                 last;
                   6175:             }
1.691     raeburn  6176:         }
1.503     raeburn  6177:     } else {
                   6178:         $occurrences = &occurence_count($currquest,$matchon); 
                   6179:     }
                   6180:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6181:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6182:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6183:             my $bubble = substr($currquest,$ans,1);
                   6184:             if ($bubble =~ /$matchon/ ) {
                   6185:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6186:                     if ($bubble == 0) {
                   6187:                         $bubble = 10; 
                   6188:                     }
                   6189:                     $record->{"scantron.$ansnum.answer"} = 
                   6190:                         $alphabet->[$bubble-1];
                   6191:                 } else {
                   6192:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6193:                 }
                   6194:             } else {
                   6195:                 $record->{"scantron.$ansnum.answer"}='';
                   6196:             }
                   6197:             $ansnum++;
                   6198:         }
                   6199:     } elsif (!defined($currquest)
                   6200:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6201:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6202:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6203:             $record->{"scantron.$ansnum.answer"}='';
                   6204:             $ansnum++;
                   6205:         }
                   6206:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6207:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6208:         }
                   6209:     } else {
                   6210:         if ($$scantron_config{'Qon'} eq 'number') {
                   6211:             $currquest = &digits_to_letters($currquest);            
                   6212:         }
                   6213:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6214:             my $bubble = substr($currquest,$ans,1);
                   6215:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6216:             $ansnum++;
                   6217:         }
                   6218:     }
                   6219:     return $ansnum;
                   6220: }
1.447     foxr     6221: 
1.503     raeburn  6222: sub scantron_validator_positional {
                   6223:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6224:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6225:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6226: 
1.503     raeburn  6227:     # Otherwise there's a positional notation;
                   6228:     # each bubble line requires Qlength items, and there are filled in
                   6229:     # bubbles for each case where there 'Qon' characters.
                   6230:     #
1.447     foxr     6231: 
1.503     raeburn  6232:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6233: 
1.503     raeburn  6234:     # If the split only gives us one element.. the full length of the
                   6235:     # answer string, no bubbles are filled in:
1.447     foxr     6236: 
1.507     raeburn  6237:     if ($answers_needed eq '') {
                   6238:         return;
                   6239:     }
                   6240: 
1.503     raeburn  6241:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6242:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6243:             $record->{"scantron.$ansnum.answer"}='';
                   6244:             $ansnum++;
                   6245:         }
                   6246:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6247:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6248:         }
                   6249:     } elsif (scalar(@array) == 2) {
                   6250:         my $location = length($array[0]);
                   6251:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6252:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6253:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6254:             if ($ans eq $line_num) {
                   6255:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6256:             } else {
                   6257:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6258:             }
                   6259:             $ansnum++;
                   6260:          }
                   6261:     } else {
                   6262:         #  If there's more than one instance of a bubble character
                   6263:         #  That's a double bubble; with positional notation we can
                   6264:         #  record all the bubbles filled in as well as the
                   6265:         #  fact this response consists of multiple bubbles.
                   6266:         #
1.691     raeburn  6267:         my $responsenum = $questnum-1;
                   6268:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6269:             $responsenum = $respnumlookup->{$questnum-1}
                   6270:         }
                   6271:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6272:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6273:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6274:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6275:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6276:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6277:             my $doubleerror = 0;
                   6278:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6279:                    (!$doubleerror)) {
                   6280:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6281:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6282:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6283:                if (length(@currarray) > 2) {
                   6284:                    $doubleerror = 1;
                   6285:                } 
                   6286:             }
                   6287:             if ($doubleerror) {
                   6288:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6289:             }
                   6290:         } else {
                   6291:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6292:         }
                   6293:         my $item = $ansnum;
                   6294:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6295:             $record->{"scantron.$item.answer"} = '';
                   6296:             $item ++;
                   6297:         }
1.447     foxr     6298: 
1.503     raeburn  6299:         my @ans=@array;
                   6300:         my $i=0;
                   6301:         my $increment = 0;
                   6302:         while ($#ans) {
                   6303:             $i+=length($ans[0]) + $increment;
                   6304:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6305:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6306:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6307:             shift(@ans);
                   6308:             $increment = 1;
                   6309:         }
                   6310:         $ansnum += $answers_needed;
1.82      albertel 6311:     }
1.503     raeburn  6312:     return $ansnum;
1.82      albertel 6313: }
                   6314: 
1.423     albertel 6315: =pod
                   6316: 
                   6317: =item scantron_add_delay
                   6318: 
                   6319:    Adds an error message that occurred during the grading phase to a
                   6320:    queue of messages to be shown after grading pass is complete
                   6321: 
                   6322:  Arguments:
1.424     albertel 6323:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6324:    $scanline    - the scanline that caused the error
                   6325:    $errormesage - the error message
                   6326:    $errorcode   - a numeric code for the error
                   6327: 
                   6328:  Side Effects:
1.424     albertel 6329:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6330: 
                   6331: =cut
                   6332: 
1.82      albertel 6333: sub scantron_add_delay {
1.140     albertel 6334:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6335:     push(@$delayqueue,
                   6336: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6337: 	  'ecode' => $errorcode }
                   6338: 	 );
1.82      albertel 6339: }
                   6340: 
1.423     albertel 6341: =pod
                   6342: 
                   6343: =item scantron_find_student
                   6344: 
1.424     albertel 6345:    Finds the username for the current scanline
                   6346: 
                   6347:   Arguments:
                   6348:    $scantron_record - hash result from scantron_parse_scanline
                   6349:    $scan_data       - hash of correction information 
                   6350:                       (see &scantron_getfile() form more information)
                   6351:    $idmap           - hash from &username_to_idmap()
                   6352:    $line            - number of current scanline
                   6353:  
                   6354:   Returns:
                   6355:    Either 'username:domain' or undef if unknown
                   6356: 
1.423     albertel 6357: =cut
                   6358: 
1.82      albertel 6359: sub scantron_find_student {
1.157     albertel 6360:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6361:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6362:     if ($scanID =~ /^\s*$/) {
                   6363:  	return &scan_data($scan_data,"$line.user");
                   6364:     }
1.83      albertel 6365:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6366:  	if (lc($id) eq lc($scanID)) {
                   6367:  	    return $$idmap{$id};
                   6368:  	}
1.83      albertel 6369:     }
                   6370:     return undef;
                   6371: }
                   6372: 
1.423     albertel 6373: =pod
                   6374: 
                   6375: =item scantron_filter
                   6376: 
1.424     albertel 6377:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6378:    hidden resources was selected
                   6379: 
1.423     albertel 6380: =cut
                   6381: 
1.83      albertel 6382: sub scantron_filter {
                   6383:     my ($curres)=@_;
1.331     albertel 6384: 
                   6385:     if (ref($curres) && $curres->is_problem()) {
                   6386: 	# if the user has asked to not have either hidden
                   6387: 	# or 'randomout' controlled resources to be graded
                   6388: 	# don't include them
                   6389: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6390: 	    && $curres->randomout) {
                   6391: 	    return 0;
                   6392: 	}
1.83      albertel 6393: 	return 1;
                   6394:     }
                   6395:     return 0;
1.82      albertel 6396: }
                   6397: 
1.423     albertel 6398: =pod
                   6399: 
                   6400: =item scantron_process_corrections
                   6401: 
1.424     albertel 6402:    Gets correction information out of submitted form data and corrects
                   6403:    the scanline
                   6404: 
1.423     albertel 6405: =cut
                   6406: 
1.157     albertel 6407: sub scantron_process_corrections {
                   6408:     my ($r) = @_;
1.257     albertel 6409:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6410:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6411:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6412:     my $which=$env{'form.scantron_line'};
1.200     albertel 6413:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6414:     my ($skip,$err,$errmsg);
1.257     albertel 6415:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6416: 	$skip=1;
1.257     albertel 6417:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6418: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6419: 	    $env{'form.scantron_domain'};
1.157     albertel 6420: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6421: 	($line,$err,$errmsg)=
                   6422: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6423: 				     'ID',{'newid'=>$newid,
1.257     albertel 6424: 				    'username'=>$env{'form.scantron_username'},
                   6425: 				    'domain'=>$env{'form.scantron_domain'}});
                   6426:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6427: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6428: 	my $newCODE;
1.192     albertel 6429: 	my %args;
1.190     albertel 6430: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6431: 	    $newCODE='use_unfound';
1.190     albertel 6432: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6433: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6434: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6435: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6436: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6437: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6438: 	}
1.257     albertel 6439: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6440: 	    $args{'CODE_ignore_dup'}=1;
                   6441: 	}
                   6442: 	$args{'CODE'}=$newCODE;
1.186     albertel 6443: 	($line,$err,$errmsg)=
                   6444: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6445: 				     'CODE',\%args);
1.257     albertel 6446:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6447: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6448: 	    ($line,$err,$errmsg)=
                   6449: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6450: 					 $which,'answer',
                   6451: 					 { 'question'=>$question,
1.503     raeburn  6452: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6453:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6454: 	    if ($err) { last; }
                   6455: 	}
                   6456:     }
                   6457:     if ($err) {
1.703     bisitz   6458:         $r->print(
                   6459:             '<p class="LC_error">'
                   6460:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6461:                 $errmsg)
1.704     raeburn  6462:            .'</p>');
1.157     albertel 6463:     } else {
1.200     albertel 6464: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6465: 	&scantron_putfile($scanlines,$scan_data);
                   6466:     }
                   6467: }
                   6468: 
1.423     albertel 6469: =pod
                   6470: 
                   6471: =item reset_skipping_status
                   6472: 
1.424     albertel 6473:    Forgets the current set of remember skipped scanlines (and thus
                   6474:    reverts back to considering all lines in the
                   6475:    scantron_skipped_<filename> file)
                   6476: 
1.423     albertel 6477: =cut
                   6478: 
1.200     albertel 6479: sub reset_skipping_status {
                   6480:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6481:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6482:     &scantron_putfile(undef,$scan_data);
                   6483: }
                   6484: 
1.423     albertel 6485: =pod
                   6486: 
                   6487: =item start_skipping
                   6488: 
1.424     albertel 6489:    Marks a scanline to be skipped. 
                   6490: 
1.423     albertel 6491: =cut
                   6492: 
1.376     albertel 6493: sub start_skipping {
1.200     albertel 6494:     my ($scan_data,$i)=@_;
                   6495:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6496:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6497: 	$remembered{$i}=2;
                   6498:     } else {
                   6499: 	$remembered{$i}=1;
                   6500:     }
1.200     albertel 6501:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6502: }
                   6503: 
1.423     albertel 6504: =pod
                   6505: 
                   6506: =item should_be_skipped
                   6507: 
1.424     albertel 6508:    Checks whether a scanline should be skipped.
                   6509: 
1.423     albertel 6510: =cut
                   6511: 
1.200     albertel 6512: sub should_be_skipped {
1.376     albertel 6513:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6514:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6515: 	# not redoing old skips
1.376     albertel 6516: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6517: 	return 0;
                   6518:     }
                   6519:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6520: 
                   6521:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6522: 	return 0;
                   6523:     }
1.200     albertel 6524:     return 1;
                   6525: }
                   6526: 
1.423     albertel 6527: =pod
                   6528: 
                   6529: =item remember_current_skipped
                   6530: 
1.424     albertel 6531:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6532:    file and remembers them into scan_data for later use.
                   6533: 
1.423     albertel 6534: =cut
                   6535: 
1.200     albertel 6536: sub remember_current_skipped {
                   6537:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6538:     my %to_remember;
                   6539:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6540: 	if ($scanlines->{'skipped'}[$i]) {
                   6541: 	    $to_remember{$i}=1;
                   6542: 	}
                   6543:     }
1.376     albertel 6544: 
1.200     albertel 6545:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6546:     &scantron_putfile(undef,$scan_data);
                   6547: }
                   6548: 
1.423     albertel 6549: =pod
                   6550: 
                   6551: =item check_for_error
                   6552: 
1.424     albertel 6553:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6554:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6555:     something went wrong.
                   6556: 
1.423     albertel 6557: =cut
                   6558: 
1.200     albertel 6559: sub check_for_error {
                   6560:     my ($r,$result)=@_;
                   6561:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6562: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6563:     }
                   6564: }
1.157     albertel 6565: 
1.423     albertel 6566: =pod
                   6567: 
                   6568: =item scantron_warning_screen
                   6569: 
1.424     albertel 6570:    Interstitial screen to make sure the operator has selected the
                   6571:    correct options before we start the validation phase.
                   6572: 
1.423     albertel 6573: =cut
                   6574: 
1.203     albertel 6575: sub scantron_warning_screen {
1.650     raeburn  6576:     my ($button_text,$symb)=@_;
1.257     albertel 6577:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6578:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6579:     my $CODElist;
1.284     albertel 6580:     if ($scantron_config{'CODElocation'} &&
                   6581: 	$scantron_config{'CODEstart'} &&
                   6582: 	$scantron_config{'CODElength'}) {
                   6583: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6584: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6585: 	$CODElist=
1.492     albertel 6586: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6587: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6588:     }
1.663     raeburn  6589:     my $lastbubblepoints;
                   6590:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6591:         $lastbubblepoints =
                   6592:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6593:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6594:     }
1.492     albertel 6595:     return ('
1.203     albertel 6596: <p>
1.492     albertel 6597: <span class="LC_warning">
1.705     raeburn  6598: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6599: </p>
                   6600: <table>
1.492     albertel 6601: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6602: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6603: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6604: </table>
1.680     raeburn  6605: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6606: '.&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 6607: 
                   6608: <br />
1.492     albertel 6609: ');
1.203     albertel 6610: }
                   6611: 
1.423     albertel 6612: =pod
                   6613: 
                   6614: =item scantron_do_warning
                   6615: 
1.424     albertel 6616:    Check if the operator has picked something for all required
                   6617:    fields. Error out if something is missing.
                   6618: 
1.423     albertel 6619: =cut
                   6620: 
1.203     albertel 6621: sub scantron_do_warning {
1.608     www      6622:     my ($r,$symb)=@_;
1.203     albertel 6623:     if (!$symb) {return '';}
1.324     albertel 6624:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6625:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6626:     if ( $env{'form.selectpage'} eq '' ||
                   6627: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6628: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6629: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6630: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6631: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6632: 	} 
1.257     albertel 6633: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6634: 	    $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 6635: 	} 
1.257     albertel 6636: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6637: 	    $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 6638: 	} 
                   6639:     } else {
1.650     raeburn  6640: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6641:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6642: 	$r->print('
1.663     raeburn  6643: '.$warning.$bubbledbyhand.'
1.492     albertel 6644: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6645: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6646: ');
1.237     albertel 6647:     }
1.614     www      6648:     $r->print("</form><br />");
1.203     albertel 6649:     return '';
                   6650: }
                   6651: 
1.423     albertel 6652: =pod
                   6653: 
                   6654: =item scantron_form_start
                   6655: 
1.424     albertel 6656:     html hidden input for remembering all selected grading options
                   6657: 
1.423     albertel 6658: =cut
                   6659: 
1.203     albertel 6660: sub scantron_form_start {
                   6661:     my ($max_bubble)=@_;
                   6662:     my $result= <<SCANTRONFORM;
                   6663: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6664:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6665:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6666:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6667:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6668:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6669:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6670:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6671:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6672:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6673: SCANTRONFORM
1.447     foxr     6674: 
                   6675:   my $line = 0;
                   6676:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6677:        my $chunk =
                   6678: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6679:        $chunk .=
                   6680: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6681:        $chunk .= 
                   6682:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6683:        $chunk .=
                   6684:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6685:        $chunk .=
                   6686:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6687:        $result .= $chunk;
                   6688:        $line++;
1.691     raeburn  6689:     }
1.203     albertel 6690:     return $result;
                   6691: }
                   6692: 
1.423     albertel 6693: =pod
                   6694: 
                   6695: =item scantron_validate_file
                   6696: 
1.659     raeburn  6697:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6698: 
                   6699:     Also processes any necessary information resets that need to
                   6700:     occur before validation begins (ignore previous corrections,
                   6701:     restarting the skipped records processing)
                   6702: 
1.423     albertel 6703: =cut
                   6704: 
1.157     albertel 6705: sub scantron_validate_file {
1.608     www      6706:     my ($r,$symb) = @_;
1.157     albertel 6707:     if (!$symb) {return '';}
1.324     albertel 6708:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6709:     
1.703     bisitz   6710:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6711:     # them when doing the corrections reset
1.257     albertel 6712:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6713: 	&reset_skipping_status();
                   6714:     }
1.257     albertel 6715:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6716: 	&remember_current_skipped();
1.257     albertel 6717: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6718:     }
                   6719: 
1.257     albertel 6720:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6721: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6722: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6723: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6724: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6725:     }
1.200     albertel 6726: 
1.257     albertel 6727:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6728: 	&scantron_process_corrections($r);
                   6729:     }
1.503     raeburn  6730:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6731:     #get the student pick code ready
                   6732:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6733:     my $nav_error;
1.649     raeburn  6734:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6735:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6736:     if ($nav_error) {
                   6737:         $r->print(&navmap_errormsg());
                   6738:         return '';
                   6739:     }
1.203     albertel 6740:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6741:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6742:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6743:     }
1.157     albertel 6744:     $r->print($result);
                   6745:     
1.334     albertel 6746:     my @validate_phases=( 'sequence',
                   6747: 			  'ID',
1.157     albertel 6748: 			  'CODE',
                   6749: 			  'doublebubble',
                   6750: 			  'missingbubbles');
1.257     albertel 6751:     if (!$env{'form.validatepass'}) {
                   6752: 	$env{'form.validatepass'} = 0;
1.157     albertel 6753:     }
1.257     albertel 6754:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6755: 
1.448     foxr     6756: 
1.157     albertel 6757:     my $stop=0;
                   6758:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6759: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6760: 	$r->rflush();
1.691     raeburn  6761:      
1.157     albertel 6762: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6763: 	{
                   6764: 	    no strict 'refs';
                   6765: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6766: 	}
                   6767:     }
                   6768:     if (!$stop) {
1.650     raeburn  6769: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6770: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6771:                   $warning.
                   6772:                   &mt('Perform verification for each student after storage of submissions?').
                   6773:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6774:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6775:                   ('&nbsp;'x3).'<label>'.
                   6776:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6777:                   '</label></span><br />'.
                   6778:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6779:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6780:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6781:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6782:     } else {
                   6783: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6784: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6785:     }
                   6786:     if ($stop) {
1.334     albertel 6787: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6788: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6789: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6790: 
1.650     raeburn  6791: 	    $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 6792: 	} else {
1.503     raeburn  6793:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6794: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6795:             } else {
1.539     riegler  6796:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6797:             }
1.492     albertel 6798: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6799: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6800: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6801: 	}
1.157     albertel 6802:     }
1.614     www      6803:     $r->print(" </form><br />");
1.157     albertel 6804:     return '';
                   6805: }
                   6806: 
1.423     albertel 6807: 
                   6808: =pod
                   6809: 
                   6810: =item scantron_remove_file
                   6811: 
1.659     raeburn  6812:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6813:    scantron_original_<filename> is never removed
                   6814: 
                   6815: 
1.423     albertel 6816: =cut
                   6817: 
1.200     albertel 6818: sub scantron_remove_file {
1.192     albertel 6819:     my ($which)=@_;
1.257     albertel 6820:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6821:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6822:     my $file='scantron_';
1.200     albertel 6823:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6824: 	$file.=$which.'_';
1.192     albertel 6825:     } else {
                   6826: 	return 'refused';
                   6827:     }
1.257     albertel 6828:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6829:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6830: }
                   6831: 
1.423     albertel 6832: 
                   6833: =pod
                   6834: 
                   6835: =item scantron_remove_scan_data
                   6836: 
1.659     raeburn  6837:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6838:    data file.  (In the case that both the are doing skipped records we need
                   6839:    to remember the old skipped lines for the time being so that element
                   6840:    persists for a while.)
                   6841: 
1.423     albertel 6842: =cut
                   6843: 
1.200     albertel 6844: sub scantron_remove_scan_data {
1.257     albertel 6845:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6846:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6847:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6848:     my @todelete;
1.257     albertel 6849:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6850:     foreach my $key (@keys) {
                   6851: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6852: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6853: 		$key=~/remember_skipping/) {
                   6854: 		next;
                   6855: 	    }
1.192     albertel 6856: 	    push(@todelete,$key);
                   6857: 	}
                   6858:     }
1.200     albertel 6859:     my $result;
1.192     albertel 6860:     if (@todelete) {
1.491     albertel 6861: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6862: 				       \@todelete,$cdom,$cname);
                   6863:     } else {
                   6864: 	$result = 'ok';
1.192     albertel 6865:     }
                   6866:     return $result;
                   6867: }
                   6868: 
1.423     albertel 6869: 
                   6870: =pod
                   6871: 
                   6872: =item scantron_getfile
                   6873: 
1.659     raeburn  6874:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6875:     the scan_data hash
                   6876:   
                   6877:   Arguments:
                   6878:     None
                   6879: 
                   6880:   Returns:
                   6881:     2 hash references
                   6882: 
                   6883:      - first one has 
                   6884:          orig      -
                   6885:          corrected -
                   6886:          skipped   -  each of which points to an array ref of the specified
                   6887:                       file broken up into individual lines
                   6888:          count     - number of scanlines
                   6889:  
                   6890:      - second is the scan_data hash possible keys are
1.425     albertel 6891:        ($number refers to scanline numbered $number and thus the key affects
                   6892:         only that scanline
                   6893:         $bubline refers to the specific bubble line element and the aspects
                   6894:         refers to that specific bubble line element)
                   6895: 
                   6896:        $number.user - username:domain to use
                   6897:        $number.CODE_ignore_dup 
                   6898:                     - ignore the duplicate CODE error 
                   6899:        $number.useCODE
                   6900:                     - use the CODE in the scanline as is
                   6901:        $number.no_bubble.$bubline
                   6902:                     - it is valid that there is no bubbled in bubble
                   6903:                       at $number $bubline
                   6904:        remember_skipping
                   6905:                     - a frozen hash containing keys of $number and values
                   6906:                       of either 
                   6907:                         1 - we are on a 'do skipped records pass' and plan
                   6908:                             on processing this line
                   6909:                         2 - we are on a 'do skipped records pass' and this
                   6910:                             scanline has been marked to skip yet again
1.424     albertel 6911: 
1.423     albertel 6912: =cut
                   6913: 
1.157     albertel 6914: sub scantron_getfile {
1.200     albertel 6915:     #FIXME really would prefer a scantron directory
1.257     albertel 6916:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6918:     my $lines;
                   6919:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6920: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6921:     my %scanlines;
                   6922:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6923:     my $temp=$scanlines{'orig'};
                   6924:     $scanlines{'count'}=$#$temp;
                   6925: 
                   6926:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6927: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6928:     if ($lines eq '-1') {
                   6929: 	$scanlines{'corrected'}=[];
                   6930:     } else {
                   6931: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6932:     }
                   6933:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6934: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6935:     if ($lines eq '-1') {
                   6936: 	$scanlines{'skipped'}=[];
                   6937:     } else {
                   6938: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6939:     }
1.175     albertel 6940:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6941:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6942:     my %scan_data = @tmp;
                   6943:     return (\%scanlines,\%scan_data);
                   6944: }
                   6945: 
1.423     albertel 6946: =pod
                   6947: 
                   6948: =item lonnet_putfile
                   6949: 
1.424     albertel 6950:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6951: 
                   6952:  Arguments:
                   6953:    $contents - data to store
                   6954:    $filename - filename to store $contents into
                   6955: 
                   6956:  Returns:
                   6957:    result value from &Apache::lonnet::finishuserfileupload
                   6958: 
1.423     albertel 6959: =cut
                   6960: 
1.157     albertel 6961: sub lonnet_putfile {
                   6962:     my ($contents,$filename)=@_;
1.257     albertel 6963:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6964:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6965:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6966:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6967: 
                   6968: }
                   6969: 
1.423     albertel 6970: =pod
                   6971: 
                   6972: =item scantron_putfile
                   6973: 
1.659     raeburn  6974:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6975:     scan_data hash. (Does not modify the original version only the
                   6976:     corrected and skipped versions.
                   6977: 
                   6978:  Arguments:
                   6979:     $scanlines - hash ref that looks like the first return value from
                   6980:                  &scantron_getfile()
                   6981:     $scan_data - hash ref that looks like the second return value from
                   6982:                  &scantron_getfile()
                   6983: 
1.423     albertel 6984: =cut
                   6985: 
1.157     albertel 6986: sub scantron_putfile {
                   6987:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6988:     #FIXME really would prefer a scantron directory
1.257     albertel 6989:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6990:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6991:     if ($scanlines) {
                   6992: 	my $prefix='scantron_';
1.157     albertel 6993: # no need to update orig, shouldn't change
                   6994: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6995: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6996: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6997: 			$prefix.'corrected_'.
1.257     albertel 6998: 			$env{'form.scantron_selectfile'});
1.200     albertel 6999: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7000: 			$prefix.'skipped_'.
1.257     albertel 7001: 			$env{'form.scantron_selectfile'});
1.200     albertel 7002:     }
1.175     albertel 7003:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7004: }
                   7005: 
1.423     albertel 7006: =pod
                   7007: 
                   7008: =item scantron_get_line
                   7009: 
1.424     albertel 7010:    Returns the correct version of the scanline
                   7011: 
                   7012:  Arguments:
                   7013:     $scanlines - hash ref that looks like the first return value from
                   7014:                  &scantron_getfile()
                   7015:     $scan_data - hash ref that looks like the second return value from
                   7016:                  &scantron_getfile()
                   7017:     $i         - number of the requested line (starts at 0)
                   7018: 
                   7019:  Returns:
                   7020:    A scanline, (either the original or the corrected one if it
                   7021:    exists), or undef if the requested scanline should be
                   7022:    skipped. (Either because it's an skipped scanline, or it's an
                   7023:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7024:    pass.
                   7025: 
1.423     albertel 7026: =cut
                   7027: 
1.157     albertel 7028: sub scantron_get_line {
1.200     albertel 7029:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7030:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7031:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7032:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7033:     return $scanlines->{'orig'}[$i]; 
                   7034: }
                   7035: 
1.423     albertel 7036: =pod
                   7037: 
                   7038: =item scantron_todo_count
                   7039: 
1.424     albertel 7040:     Counts the number of scanlines that need processing.
                   7041: 
                   7042:  Arguments:
                   7043:     $scanlines - hash ref that looks like the first return value from
                   7044:                  &scantron_getfile()
                   7045:     $scan_data - hash ref that looks like the second return value from
                   7046:                  &scantron_getfile()
                   7047: 
                   7048:  Returns:
                   7049:     $count - number of scanlines to process
                   7050: 
1.423     albertel 7051: =cut
                   7052: 
1.200     albertel 7053: sub get_todo_count {
                   7054:     my ($scanlines,$scan_data)=@_;
                   7055:     my $count=0;
                   7056:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7057: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7058: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7059: 	$count++;
                   7060:     }
                   7061:     return $count;
                   7062: }
                   7063: 
1.423     albertel 7064: =pod
                   7065: 
                   7066: =item scantron_put_line
                   7067: 
1.659     raeburn  7068:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7069:     data file.
                   7070: 
                   7071:  Arguments:
                   7072:     $scanlines - hash ref that looks like the first return value from
                   7073:                  &scantron_getfile()
                   7074:     $scan_data - hash ref that looks like the second return value from
                   7075:                  &scantron_getfile()
                   7076:     $i         - line number to update
                   7077:     $newline   - contents of the updated scanline
                   7078:     $skip      - if true make the line for skipping and update the
                   7079:                  'skipped' file
                   7080: 
1.423     albertel 7081: =cut
                   7082: 
1.157     albertel 7083: sub scantron_put_line {
1.200     albertel 7084:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7085:     if ($skip) {
                   7086: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7087: 	&start_skipping($scan_data,$i);
1.157     albertel 7088: 	return;
                   7089:     }
                   7090:     $scanlines->{'corrected'}[$i]=$newline;
                   7091: }
                   7092: 
1.423     albertel 7093: =pod
                   7094: 
                   7095: =item scantron_clear_skip
                   7096: 
1.424     albertel 7097:    Remove a line from the 'skipped' file
                   7098: 
                   7099:  Arguments:
                   7100:     $scanlines - hash ref that looks like the first return value from
                   7101:                  &scantron_getfile()
                   7102:     $scan_data - hash ref that looks like the second return value from
                   7103:                  &scantron_getfile()
                   7104:     $i         - line number to update
                   7105: 
1.423     albertel 7106: =cut
                   7107: 
1.376     albertel 7108: sub scantron_clear_skip {
                   7109:     my ($scanlines,$scan_data,$i)=@_;
                   7110:     if (exists($scanlines->{'skipped'}[$i])) {
                   7111: 	undef($scanlines->{'skipped'}[$i]);
                   7112: 	return 1;
                   7113:     }
                   7114:     return 0;
                   7115: }
                   7116: 
1.423     albertel 7117: =pod
                   7118: 
                   7119: =item scantron_filter_not_exam
                   7120: 
1.424     albertel 7121:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7122:    filter out resources that are not marked as 'exam' mode
                   7123: 
1.423     albertel 7124: =cut
                   7125: 
1.334     albertel 7126: sub scantron_filter_not_exam {
                   7127:     my ($curres)=@_;
                   7128:     
                   7129:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7130: 	# if the user has asked to not have either hidden
                   7131: 	# or 'randomout' controlled resources to be graded
                   7132: 	# don't include them
                   7133: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7134: 	    && $curres->randomout) {
                   7135: 	    return 0;
                   7136: 	}
                   7137: 	return 1;
                   7138:     }
                   7139:     return 0;
                   7140: }
                   7141: 
1.423     albertel 7142: =pod
                   7143: 
                   7144: =item scantron_validate_sequence
                   7145: 
1.424     albertel 7146:     Validates the selected sequence, checking for resource that are
                   7147:     not set to exam mode.
                   7148: 
1.423     albertel 7149: =cut
                   7150: 
1.334     albertel 7151: sub scantron_validate_sequence {
                   7152:     my ($r,$currentphase) = @_;
                   7153: 
                   7154:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7155:     unless (ref($navmap)) {
                   7156:         $r->print(&navmap_errormsg());
                   7157:         return (1,$currentphase);
                   7158:     }
1.334     albertel 7159:     my (undef,undef,$sequence)=
                   7160: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7161: 
                   7162:     my $map=$navmap->getResourceByUrl($sequence);
                   7163: 
                   7164:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7165:                                     value="ignore" />');
                   7166:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7167: 	my @resources=
                   7168: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7169: 	if (@resources) {
1.675     bisitz   7170: 	    $r->print(
                   7171:                 '<p class="LC_warning">'
                   7172:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7173:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7174:                    .' work correctly.')
                   7175:                .'</p>'
                   7176:             );
1.334     albertel 7177: 	    return (1,$currentphase);
                   7178: 	}
                   7179:     }
                   7180: 
                   7181:     return (0,$currentphase+1);
                   7182: }
                   7183: 
1.423     albertel 7184: 
                   7185: 
1.157     albertel 7186: sub scantron_validate_ID {
                   7187:     my ($r,$currentphase) = @_;
                   7188:     
                   7189:     #get student info
                   7190:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7191:     my %idmap=&username_to_idmap($classlist);
                   7192: 
                   7193:     #get scantron line setup
1.257     albertel 7194:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7195:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7196: 
                   7197:     my $nav_error;
1.649     raeburn  7198:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7199:     if ($nav_error) {
                   7200:         $r->print(&navmap_errormsg());
                   7201:         return(1,$currentphase);
                   7202:     }
1.157     albertel 7203: 
                   7204:     my %found=('ids'=>{},'usernames'=>{});
                   7205:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7206: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7207: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7208: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7209: 						 $scan_data);
                   7210: 	my $id=$$scan_record{'scantron.ID'};
                   7211: 	my $found;
                   7212: 	foreach my $checkid (keys(%idmap)) {
                   7213: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7214: 	}
                   7215: 	if ($found) {
                   7216: 	    my $username=$idmap{$found};
                   7217: 	    if ($found{'ids'}{$found}) {
                   7218: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7219: 					 $line,'duplicateID',$found);
1.194     albertel 7220: 		return(1,$currentphase);
1.157     albertel 7221: 	    } elsif ($found{'usernames'}{$username}) {
                   7222: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7223: 					 $line,'duplicateID',$username);
1.194     albertel 7224: 		return(1,$currentphase);
1.157     albertel 7225: 	    }
1.186     albertel 7226: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7227: 	    $found{'ids'}{$found}++;
                   7228: 	    $found{'usernames'}{$username}++;
                   7229: 	} else {
                   7230: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7231: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7232: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7233: 		    &scantron_get_correction($r,$i,$scan_record,
                   7234: 					     \%scantron_config,
                   7235: 					     $line,'duplicateID',$username);
1.194     albertel 7236: 		    return(1,$currentphase);
1.157     albertel 7237: 		} elsif (!defined($username)) {
                   7238: 		    &scantron_get_correction($r,$i,$scan_record,
                   7239: 					     \%scantron_config,
                   7240: 					     $line,'incorrectID');
1.194     albertel 7241: 		    return(1,$currentphase);
1.157     albertel 7242: 		}
                   7243: 		$found{'usernames'}{$username}++;
                   7244: 	    } else {
                   7245: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7246: 					 $line,'incorrectID');
1.194     albertel 7247: 		return(1,$currentphase);
1.157     albertel 7248: 	    }
                   7249: 	}
                   7250:     }
                   7251: 
                   7252:     return (0,$currentphase+1);
                   7253: }
                   7254: 
1.423     albertel 7255: 
1.157     albertel 7256: sub scantron_get_correction {
1.691     raeburn  7257:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7258:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7259: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7260: #to show both the current line and the previous one and allow skipping
                   7261: #the previous one or the current one
                   7262: 
1.333     albertel 7263:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7264:         $r->print(
                   7265:             '<p class="LC_warning">'
                   7266:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7267:                 "<b>$error</b>",
                   7268:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7269:            ."</p> \n");
1.157     albertel 7270:     } else {
1.658     bisitz   7271:         $r->print(
                   7272:             '<p class="LC_warning">'
                   7273:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7274:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7275:            ."</p> \n");
                   7276:     }
                   7277:     my $message =
                   7278:         '<p>'
                   7279:        .&mt('The ID on the form is [_1]',
                   7280:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7281:        .'<br />'
1.665     raeburn  7282:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7283:             $$scan_record{'scantron.LastName'},
                   7284:             $$scan_record{'scantron.FirstName'})
                   7285:        .'</p>';
1.242     albertel 7286: 
1.157     albertel 7287:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7288:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7289:                            # Array populated for doublebubble or
                   7290:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7291:                            # to validate radio button checking   
                   7292: 
1.157     albertel 7293:     if ($error =~ /ID$/) {
1.186     albertel 7294: 	if ($error eq 'incorrectID') {
1.658     bisitz   7295:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7296: 		      "</p>\n");
1.157     albertel 7297: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7298:             $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 7299: 	}
1.242     albertel 7300: 	$r->print($message);
1.492     albertel 7301: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7302: 	$r->print("\n<ul><li> ");
                   7303: 	#FIXME it would be nice if this sent back the user ID and
                   7304: 	#could do partial userID matches
                   7305: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7306: 				       'scantron_username','scantron_domain'));
                   7307: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7308: 	$r->print("\n:\n".
1.257     albertel 7309: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7310: 
                   7311: 	$r->print('</li>');
1.186     albertel 7312:     } elsif ($error =~ /CODE$/) {
                   7313: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7314: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7315: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7316: 	    $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 7317: 	}
1.658     bisitz   7318: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7319: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7320:                  ."</p>\n");
1.242     albertel 7321: 	$r->print($message);
1.658     bisitz   7322: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7323: 	$r->print("\n<br /> ");
1.194     albertel 7324: 	my $i=0;
1.273     albertel 7325: 	if ($error eq 'incorrectCODE' 
                   7326: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7327: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7328: 	    if ($closest > 0) {
                   7329: 		foreach my $testcode (@{$closest}) {
                   7330: 		    my $checked='';
1.569     bisitz   7331: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7332: 		    $r->print("
                   7333:    <label>
1.569     bisitz   7334:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7335:        ".&mt("Use the similar CODE [_1] instead.",
                   7336: 	    "<b><tt>".$testcode."</tt></b>")."
                   7337:     </label>
                   7338:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7339: 		    $r->print("\n<br />");
                   7340: 		    $i++;
                   7341: 		}
1.194     albertel 7342: 	    }
                   7343: 	}
1.273     albertel 7344: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7345: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7346: 	    $r->print("
                   7347:     <label>
1.569     bisitz   7348:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7349:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7350: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7351:     </label>");
1.273     albertel 7352: 	    $r->print("\n<br />");
                   7353: 	}
1.194     albertel 7354: 
1.597     wenzelju 7355: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7356: function change_radio(field) {
1.190     albertel 7357:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7358:     var i;
                   7359:     for (i=0;i<slct.length;i++) {
                   7360:         if (slct[i].value==field) { slct[i].checked=true; }
                   7361:     }
                   7362: }
                   7363: ENDSCRIPT
1.187     albertel 7364: 	my $href="/adm/pickcode?".
1.359     www      7365: 	   "form=".&escape("scantronupload").
                   7366: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7367: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7368: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7369: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7370: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7371: 	    $r->print("
                   7372:     <label>
                   7373:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7374:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7375: 	     "<a target='_blank' href='$href'>","</a>")."
                   7376:     </label> 
1.558     bisitz   7377:     ".&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 7378: 	    $r->print("\n<br />");
                   7379: 	}
1.492     albertel 7380: 	$r->print("
                   7381:     <label>
                   7382:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7383:        ".&mt("Use [_1] as the CODE.",
                   7384: 	     "</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 7385: 	$r->print("\n<br /><br />");
1.157     albertel 7386:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7387: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7388: 
                   7389: 	# The form field scantron_questions is acutally a list of line numbers.
                   7390: 	# represented by this form so:
                   7391: 
1.691     raeburn  7392: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7393:                                                 $respnumlookup,$startline);
1.497     foxr     7394: 
1.157     albertel 7395: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7396: 		  $line_list.'" />');
1.242     albertel 7397: 	$r->print($message);
1.492     albertel 7398: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7399: 	foreach my $question (@{$arg}) {
1.503     raeburn  7400: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7401:                                                    $scan_record, $error,
                   7402:                                                    $randomorder,$randompick,
                   7403:                                                    $respnumlookup,$startline);
1.524     raeburn  7404:             push(@lines_to_correct,@linenums);
1.157     albertel 7405: 	}
1.503     raeburn  7406:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7407:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7408: 	$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 7409: 	$r->print($message);
1.492     albertel 7410: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7411: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7412: 
1.503     raeburn  7413: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7414: 	# a list of question numbers. Therefore:
                   7415: 	#
1.691     raeburn  7416: 
                   7417: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7418:                                                 $respnumlookup,$startline);
1.497     foxr     7419: 
1.157     albertel 7420: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7421: 		  $line_list.'" />');
1.157     albertel 7422: 	foreach my $question (@{$arg}) {
1.503     raeburn  7423: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7424:                                                    $scan_record, $error,
                   7425:                                                    $randomorder,$randompick,
                   7426:                                                    $respnumlookup,$startline);
1.524     raeburn  7427:             push(@lines_to_correct,@linenums);
1.157     albertel 7428: 	}
1.503     raeburn  7429:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7430:     } else {
                   7431: 	$r->print("\n<ul>");
                   7432:     }
                   7433:     $r->print("\n</li></ul>");
1.497     foxr     7434: }
                   7435: 
1.503     raeburn  7436: sub verify_bubbles_checked {
                   7437:     my (@ansnums) = @_;
                   7438:     my $ansnumstr = join('","',@ansnums);
                   7439:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7440:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7441: function verify_bubble_radio(form) {
                   7442:     var ansnumArray = new Array ("$ansnumstr");
                   7443:     var need_bubble_count = 0;
                   7444:     for (var i=0; i<ansnumArray.length; i++) {
                   7445:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7446:             var bubble_picked = 0; 
                   7447:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7448:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7449:                     bubble_picked = 1;
                   7450:                 }
                   7451:             }
                   7452:             if (bubble_picked == 0) {
                   7453:                 need_bubble_count ++;
                   7454:             }
                   7455:         }
                   7456:     }
                   7457:     if (need_bubble_count) {
                   7458:         alert("$warning");
                   7459:         return;
                   7460:     }
                   7461:     form.submit(); 
                   7462: }
                   7463: ENDSCRIPT
                   7464:     return $output;
                   7465: }
                   7466: 
1.497     foxr     7467: =pod
                   7468: 
                   7469: =item  questions_to_line_list
1.157     albertel 7470: 
1.497     foxr     7471: Converts a list of questions into a string of comma separated
                   7472: line numbers in the answer sheet used by the questions.  This is
                   7473: used to fill in the scantron_questions form field.
                   7474: 
                   7475:   Arguments:
                   7476:      questions    - Reference to an array of questions.
1.691     raeburn  7477:      randomorder  - True if randomorder in use.
                   7478:      randompick   - True if randompick in use.
                   7479:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7480:                      for current line to question number used for same question
                   7481:                      in "Master Seqence" (as seen by Course Coordinator).
                   7482:      startline    - Reference to hash where key is question number (0 is first)
                   7483:                     and key is number of first bubble line for current student
                   7484:                     or code-based randompick and/or randomorder.
1.693     raeburn  7485: 
1.497     foxr     7486: =cut
                   7487: 
                   7488: 
                   7489: sub questions_to_line_list {
1.691     raeburn  7490:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7491:     my @lines;
                   7492: 
1.503     raeburn  7493:     foreach my $item (@{$questions}) {
                   7494:         my $question = $item;
                   7495:         my ($first,$count,$last);
                   7496:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7497:             $question = $1;
                   7498:             my $subquestion = $2;
1.691     raeburn  7499:             my $responsenum = $question-1;
                   7500:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7501:                 $responsenum = $respnumlookup->{$question-1};
                   7502:                 if (ref($startline) eq 'HASH') {
                   7503:                     $first = $startline->{$question-1} + 1;
                   7504:                 }
                   7505:             } else {
                   7506:                 $first = $first_bubble_line{$responsenum} + 1;
                   7507:             }
                   7508:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7509:             my $subcount = 1;
                   7510:             while ($subcount<$subquestion) {
                   7511:                 $first += $subans[$subcount-1];
                   7512:                 $subcount ++;
                   7513:             }
                   7514:             $count = $subans[$subquestion-1];
                   7515:         } else {
1.691     raeburn  7516:             my $responsenum = $question-1;
                   7517:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7518:                 $responsenum = $respnumlookup->{$question-1};
                   7519:                 if (ref($startline) eq 'HASH') {
                   7520:                     $first = $startline->{$question-1} + 1;
                   7521:                 }
                   7522:             } else {
                   7523:                 $first = $first_bubble_line{$responsenum} + 1;
                   7524:             }
                   7525: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7526:         }
1.506     raeburn  7527:         $last = $first+$count-1;
1.503     raeburn  7528:         push(@lines, ($first..$last));
1.497     foxr     7529:     }
                   7530:     return join(',', @lines);
                   7531: }
                   7532: 
                   7533: =pod 
                   7534: 
                   7535: =item prompt_for_corrections
                   7536: 
                   7537: Prompts for a potentially multiline correction to the
                   7538: user's bubbling (factors out common code from scantron_get_correction
                   7539: for multi and missing bubble cases).
                   7540: 
                   7541:  Arguments:
                   7542:    $r           - Apache request object.
                   7543:    $question    - The question number to prompt for.
                   7544:    $scan_config - The scantron file configuration hash.
                   7545:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7546:    $error       - Type of error
1.691     raeburn  7547:    $randomorder - True if randomorder in use.
                   7548:    $randompick  - True if randompick in use.
                   7549:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7550:                     for current line to question number used for same question
                   7551:                     in "Master Seqence" (as seen by Course Coordinator).
                   7552:    $startline   - Reference to hash where key is question number (0 is first)
                   7553:                   and value is number of first bubble line for current student
                   7554:                   or code-based randompick and/or randomorder.
                   7555: 
1.497     foxr     7556: 
                   7557:  Implicit inputs:
                   7558:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7559:                                   Numbered from 0 (but question numbers are from
                   7560:                                   1.
                   7561:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7562:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7563:                                   type problems render as separate sub-questions, 
1.503     raeburn  7564:                                   in exam mode. This hash contains a 
                   7565:                                   comma-separated list of the lines per 
                   7566:                                   sub-question.
1.510     raeburn  7567:    %responsetype_per_response   - essayresponse, formularesponse,
                   7568:                                   stringresponse, imageresponse, reactionresponse,
                   7569:                                   and organicresponse type problem parts can have
1.503     raeburn  7570:                                   multiple lines per response if the weight
                   7571:                                   assigned exceeds 10.  In this case, only
                   7572:                                   one bubble per line is permitted, but more 
                   7573:                                   than one line might contain bubbles, e.g.
                   7574:                                   bubbling of: line 1 - J, line 2 - J, 
                   7575:                                   line 3 - B would assign 22 points.  
1.497     foxr     7576: 
                   7577: =cut
                   7578: 
                   7579: sub prompt_for_corrections {
1.691     raeburn  7580:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7581:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7582:     my ($current_line,$lines);
                   7583:     my @linenums;
                   7584:     my $questionnum = $question;
1.691     raeburn  7585:     my ($first,$responsenum);
1.503     raeburn  7586:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7587:         $question = $1;
                   7588:         my $subquestion = $2;
1.691     raeburn  7589:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7590:             $responsenum = $respnumlookup->{$question-1};
                   7591:             if (ref($startline) eq 'HASH') {
                   7592:                 $first = $startline->{$question-1};
                   7593:             }
                   7594:         } else {
                   7595:             $responsenum = $question-1;
1.714     raeburn  7596:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7597:         }
                   7598:         $current_line = $first + 1 ;
                   7599:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7600:         my $subcount = 1;
                   7601:         while ($subcount<$subquestion) {
                   7602:             $current_line += $subans[$subcount-1];
                   7603:             $subcount ++;
                   7604:         }
                   7605:         $lines = $subans[$subquestion-1];
                   7606:     } else {
1.691     raeburn  7607:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7608:             $responsenum = $respnumlookup->{$question-1};
                   7609:             if (ref($startline) eq 'HASH') { 
                   7610:                 $first = $startline->{$question-1};
                   7611:             }
                   7612:         } else {
                   7613:             $responsenum = $question-1;
                   7614:             $first = $first_bubble_line{$responsenum};
                   7615:         }
                   7616:         $current_line = $first + 1;
                   7617:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7618:     }
1.497     foxr     7619:     if ($lines > 1) {
1.503     raeburn  7620:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7621:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7622:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7623:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7624:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7625:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7626:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7627:             $r->print(
                   7628:                 &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)
                   7629:                .'<br /><br />'
                   7630:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7631:                .'<br />'
                   7632:                .&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.')
                   7633:                .'<br />'
                   7634:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7635:                .'<br /><br />'
                   7636:             );
1.503     raeburn  7637:         } else {
                   7638:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7639:         }
1.497     foxr     7640:     }
                   7641:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7642:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7643: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7644: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7645:         push(@linenums,$current_line);
1.497     foxr     7646: 	$current_line++;
                   7647:     }
                   7648:     if ($lines > 1) {
                   7649: 	$r->print("<hr /><br />");
                   7650:     }
1.503     raeburn  7651:     return @linenums;
1.157     albertel 7652: }
1.423     albertel 7653: 
                   7654: =pod
                   7655: 
                   7656: =item scantron_bubble_selector
                   7657:   
                   7658:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7659:    possibly showing the existing the selected bubbles if known
1.423     albertel 7660: 
                   7661:  Arguments:
                   7662:     $r           - Apache request object
                   7663:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7664:     $line        - Number of the line being displayed.
1.503     raeburn  7665:     $questionnum - Question number (may include subquestion)
                   7666:     $error       - Type of error.
1.497     foxr     7667:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7668: 
                   7669: =cut
                   7670: 
1.157     albertel 7671: sub scantron_bubble_selector {
1.503     raeburn  7672:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7673:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7674: 
                   7675:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7676:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7677:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7678:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7679:             $max=$$scan_config{'BubblesPerRow'};
                   7680:             if (($scmode eq 'number') && ($max > 10)) {
                   7681:                 $max = 10;
                   7682:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7683:                 $max = 26;
                   7684:             }
                   7685:         } else {
                   7686:             $max = 10;
                   7687:         }
                   7688:     }
1.274     albertel 7689: 
1.157     albertel 7690:     my @alphabet=('A'..'Z');
1.503     raeburn  7691:     $r->print(&Apache::loncommon::start_data_table().
                   7692:               &Apache::loncommon::start_data_table_row());
                   7693:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7694:     for (my $i=0;$i<$max+1;$i++) {
                   7695: 	$r->print("\n".'<td align="center">');
                   7696: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7697: 	else { $r->print('&nbsp;'); }
                   7698: 	$r->print('</td>');
                   7699:     }
1.503     raeburn  7700:     $r->print(&Apache::loncommon::end_data_table_row().
                   7701:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7702:     for (my $i=0;$i<$max;$i++) {
                   7703: 	$r->print("\n".
                   7704: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7705: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7706:     }
1.503     raeburn  7707:     my $nobub_checked = ' ';
                   7708:     if ($error eq 'missingbubble') {
                   7709:         $nobub_checked = ' checked = "checked" ';
                   7710:     }
                   7711:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7712: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7713:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7714:               $line.'" value="'.$questionnum.'" /></td>');
                   7715:     $r->print(&Apache::loncommon::end_data_table_row().
                   7716:               &Apache::loncommon::end_data_table());
1.157     albertel 7717: }
                   7718: 
1.423     albertel 7719: =pod
                   7720: 
                   7721: =item num_matches
                   7722: 
1.424     albertel 7723:    Counts the number of characters that are the same between the two arguments.
                   7724: 
                   7725:  Arguments:
                   7726:    $orig - CODE from the scanline
                   7727:    $code - CODE to match against
                   7728: 
                   7729:  Returns:
                   7730:    $count - integer count of the number of same characters between the
                   7731:             two arguments
                   7732: 
1.423     albertel 7733: =cut
                   7734: 
1.194     albertel 7735: sub num_matches {
                   7736:     my ($orig,$code) = @_;
                   7737:     my @code=split(//,$code);
                   7738:     my @orig=split(//,$orig);
                   7739:     my $same=0;
                   7740:     for (my $i=0;$i<scalar(@code);$i++) {
                   7741: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7742:     }
                   7743:     return $same;
                   7744: }
                   7745: 
1.423     albertel 7746: =pod
                   7747: 
                   7748: =item scantron_get_closely_matching_CODEs
                   7749: 
1.424     albertel 7750:    Cycles through all CODEs and finds the set that has the greatest
                   7751:    number of same characters as the provided CODE
                   7752: 
                   7753:  Arguments:
                   7754:    $allcodes - hash ref returned by &get_codes()
                   7755:    $CODE     - CODE from the current scanline
                   7756: 
                   7757:  Returns:
                   7758:    2 element list
                   7759:     - first elements is number of how closely matching the best fit is 
                   7760:       (5 means best set has 5 matching characters)
                   7761:     - second element is an arrary ref containing the set of valid CODEs
                   7762:       that best fit the passed in CODE
                   7763: 
1.423     albertel 7764: =cut
                   7765: 
1.194     albertel 7766: sub scantron_get_closely_matching_CODEs {
                   7767:     my ($allcodes,$CODE)=@_;
                   7768:     my @CODEs;
                   7769:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7770: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7771:     }
                   7772: 
                   7773:     return ($#CODEs,$CODEs[-1]);
                   7774: }
                   7775: 
1.423     albertel 7776: =pod
                   7777: 
                   7778: =item get_codes
                   7779: 
1.424     albertel 7780:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7781:    set of remembered CODEs.
                   7782: 
                   7783:  Arguments:
                   7784:   $old_name - name of the set of remembered CODEs
                   7785:   $cdom     - domain of the course
                   7786:   $cnum     - internal course name
                   7787: 
                   7788:  Returns:
                   7789:   %allcodes - keys are the valid CODEs, values are all 1
                   7790: 
1.423     albertel 7791: =cut
                   7792: 
1.194     albertel 7793: sub get_codes {
1.280     foxr     7794:     my ($old_name, $cdom, $cnum) = @_;
                   7795:     if (!$old_name) {
                   7796: 	$old_name=$env{'form.scantron_CODElist'};
                   7797:     }
                   7798:     if (!$cdom) {
                   7799: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7800:     }
                   7801:     if (!$cnum) {
                   7802: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7803:     }
1.278     albertel 7804:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7805: 				    $cdom,$cnum);
                   7806:     my %allcodes;
                   7807:     if ($result{"type\0$old_name"} eq 'number') {
                   7808: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7809:     } else {
                   7810: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7811:     }
1.194     albertel 7812:     return %allcodes;
                   7813: }
                   7814: 
1.423     albertel 7815: =pod
                   7816: 
                   7817: =item scantron_validate_CODE
                   7818: 
1.424     albertel 7819:    Validates all scanlines in the selected file to not have any
                   7820:    invalid or underspecified CODEs and that none of the codes are
                   7821:    duplicated if this was requested.
                   7822: 
1.423     albertel 7823: =cut
                   7824: 
1.157     albertel 7825: sub scantron_validate_CODE {
                   7826:     my ($r,$currentphase) = @_;
1.257     albertel 7827:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7828:     if ($scantron_config{'CODElocation'} &&
                   7829: 	$scantron_config{'CODEstart'} &&
                   7830: 	$scantron_config{'CODElength'}) {
1.257     albertel 7831: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7832: 	    &FIXME_blow_up()
                   7833: 	}
                   7834:     } else {
                   7835: 	return (0,$currentphase+1);
                   7836:     }
                   7837:     
                   7838:     my %usedCODEs;
                   7839: 
1.194     albertel 7840:     my %allcodes=&get_codes();
1.186     albertel 7841: 
1.582     raeburn  7842:     my $nav_error;
1.649     raeburn  7843:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7844:     if ($nav_error) {
                   7845:         $r->print(&navmap_errormsg());
                   7846:         return(1,$currentphase);
                   7847:     }
1.447     foxr     7848: 
1.186     albertel 7849:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7850:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7851: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7852: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7853: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7854: 						 $scan_data);
                   7855: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7856: 	my $error=0;
1.224     albertel 7857: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7858: 	    &scantron_get_correction($r,$i,$scan_record,
                   7859: 				     \%scantron_config,
                   7860: 				     $line,'incorrectCODE',\%allcodes);
                   7861: 	    return(1,$currentphase);
                   7862: 	}
1.221     albertel 7863: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7864: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7865: 	    &scantron_get_correction($r,$i,$scan_record,
                   7866: 				     \%scantron_config,
1.194     albertel 7867: 				     $line,'incorrectCODE',\%allcodes);
                   7868: 	    return(1,$currentphase);
1.186     albertel 7869: 	}
1.214     albertel 7870: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7871: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7872: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7873: 	    &scantron_get_correction($r,$i,$scan_record,
                   7874: 				     \%scantron_config,
1.194     albertel 7875: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7876: 	    return(1,$currentphase);
1.186     albertel 7877: 	}
1.524     raeburn  7878: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7879:     }
1.157     albertel 7880:     return (0,$currentphase+1);
                   7881: }
                   7882: 
1.423     albertel 7883: =pod
                   7884: 
                   7885: =item scantron_validate_doublebubble
                   7886: 
1.424     albertel 7887:    Validates all scanlines in the selected file to not have any
                   7888:    bubble lines with multiple bubbles marked.
                   7889: 
1.423     albertel 7890: =cut
                   7891: 
1.157     albertel 7892: sub scantron_validate_doublebubble {
                   7893:     my ($r,$currentphase) = @_;
                   7894:     #get student info
                   7895:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7896:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7897:     my (undef,undef,$sequence)=
                   7898:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7899: 
                   7900:     #get scantron line setup
1.257     albertel 7901:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7902:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7903: 
                   7904:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7905:     unless (ref($navmap)) {
                   7906:         $r->print(&navmap_errormsg());
                   7907:         return(1,$currentphase);
                   7908:     }
                   7909:     my $map=$navmap->getResourceByUrl($sequence);
                   7910:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7911:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7912:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7913:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7914: 
1.583     raeburn  7915:     my $nav_error;
1.691     raeburn  7916:     if (ref($map)) {
                   7917:         $randomorder = $map->randomorder();
                   7918:         $randompick = $map->randompick();
                   7919:         if ($randomorder || $randompick) {
                   7920:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7921:             if ($nav_error) {
                   7922:                 $r->print(&navmap_errormsg());
                   7923:                 return(1,$currentphase);
                   7924:             }
                   7925:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7926:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7927:         }
                   7928:     } else {
                   7929:         $r->print(&navmap_errormsg());
                   7930:         return(1,$currentphase);
                   7931:     }
                   7932: 
1.649     raeburn  7933:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7934:     if ($nav_error) {
                   7935:         $r->print(&navmap_errormsg());
                   7936:         return(1,$currentphase);
                   7937:     }
1.447     foxr     7938: 
1.157     albertel 7939:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7940: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7941: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7942: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7943: 						 $scan_data,undef,\%idmap,$randomorder,
                   7944:                                                  $randompick,$sequence,\@master_seq,
                   7945:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7946:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7947: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7948: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7949: 				 'doublebubble',
1.691     raeburn  7950: 				 $$scan_record{'scantron.doubleerror'},
                   7951:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7952:     	return (1,$currentphase);
                   7953:     }
                   7954:     return (0,$currentphase+1);
                   7955: }
                   7956: 
1.423     albertel 7957: 
1.503     raeburn  7958: sub scantron_get_maxbubble {
1.649     raeburn  7959:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7960:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7961: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7962: 	&restore_bubble_lines();
1.257     albertel 7963: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7964:     }
1.330     albertel 7965: 
1.447     foxr     7966:     my (undef, undef, $sequence) =
1.257     albertel 7967: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7968: 
1.447     foxr     7969:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7970:     unless (ref($navmap)) {
                   7971:         if (ref($nav_error)) {
                   7972:             $$nav_error = 1;
                   7973:         }
1.591     raeburn  7974:         return;
1.582     raeburn  7975:     }
1.191     albertel 7976:     my $map=$navmap->getResourceByUrl($sequence);
                   7977:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7978:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7979: 
                   7980:     &Apache::lonxml::clear_problem_counter();
                   7981: 
1.557     raeburn  7982:     my $uname       = $env{'user.name'};
                   7983:     my $udom        = $env{'user.domain'};
1.435     foxr     7984:     my $cid         = $env{'request.course.id'};
                   7985:     my $total_lines = 0;
                   7986:     %bubble_lines_per_response = ();
1.447     foxr     7987:     %first_bubble_line         = ();
1.503     raeburn  7988:     %subdivided_bubble_lines   = ();
                   7989:     %responsetype_per_response = ();
1.691     raeburn  7990:     %masterseq_id_responsenum  = ();
1.554     raeburn  7991: 
1.447     foxr     7992:     my $response_number = 0;
                   7993:     my $bubble_line     = 0;
1.191     albertel 7994:     foreach my $resource (@resources) {
1.691     raeburn  7995:         my $resid = $resource->id(); 
1.672     raeburn  7996:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7997:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  7998:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7999: 	    foreach my $part_id (@{$parts}) {
                   8000:                 my $lines;
                   8001: 
                   8002: 	        # TODO - make this a persistent hash not an array.
                   8003: 
                   8004:                 # optionresponse, matchresponse and rankresponse type items 
                   8005:                 # render as separate sub-questions in exam mode.
                   8006:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8007:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8008:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8009:                     my ($numbub,$numshown);
                   8010:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8011:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8012:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8013:                         }
                   8014:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8015:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8016:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8017:                         }
                   8018:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8019:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8020:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8021:                         }
                   8022:                     }
                   8023:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8024:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8025:                     }
1.649     raeburn  8026:                     my $bubbles_per_row =
                   8027:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8028:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8029:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8030:                         $inner_bubble_lines++;
                   8031:                     }
                   8032:                     for (my $i=0; $i<$numshown; $i++) {
                   8033:                         $subdivided_bubble_lines{$response_number} .= 
                   8034:                             $inner_bubble_lines.',';
                   8035:                     }
                   8036:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8037:                     $lines = $numshown * $inner_bubble_lines;
                   8038:                 } else {
                   8039:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8040:                 }
1.542     raeburn  8041: 
                   8042:                 $first_bubble_line{$response_number} = $bubble_line;
                   8043: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8044:                 $responsetype_per_response{$response_number} = 
                   8045:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8046:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8047: 	        $response_number++;
                   8048: 
                   8049: 	        $bubble_line +=  $lines;
                   8050: 	        $total_lines +=  $lines;
                   8051: 	    }
                   8052:         }
                   8053:     }
1.552     raeburn  8054:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8055: 
                   8056:     &save_bubble_lines();
                   8057:     $env{'form.scantron_maxbubble'} =
                   8058: 	$total_lines;
                   8059:     return $env{'form.scantron_maxbubble'};
                   8060: }
1.523     raeburn  8061: 
1.649     raeburn  8062: sub bubblesheet_bubbles_per_row {
                   8063:     my ($scantron_config) = @_;
                   8064:     my $bubbles_per_row;
                   8065:     if (ref($scantron_config) eq 'HASH') {
                   8066:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8067:     }
                   8068:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8069:         $bubbles_per_row = 10;
                   8070:     }
                   8071:     return $bubbles_per_row;
                   8072: }
                   8073: 
1.157     albertel 8074: sub scantron_validate_missingbubbles {
                   8075:     my ($r,$currentphase) = @_;
                   8076:     #get student info
                   8077:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8078:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8079:     my (undef,undef,$sequence)=
                   8080:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8081: 
                   8082:     #get scantron line setup
1.257     albertel 8083:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8084:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8085: 
                   8086:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8087:     unless (ref($navmap)) {
                   8088:         $r->print(&navmap_errormsg());
                   8089:         return(1,$currentphase);
                   8090:     }
                   8091: 
                   8092:     my $map=$navmap->getResourceByUrl($sequence);
                   8093:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8094:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8095:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8096:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8097: 
1.582     raeburn  8098:     my $nav_error;
1.691     raeburn  8099:     if (ref($map)) {
                   8100:         $randomorder = $map->randomorder();
                   8101:         $randompick = $map->randompick();
                   8102:         if ($randomorder || $randompick) {
                   8103:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8104:             if ($nav_error) {
                   8105:                 $r->print(&navmap_errormsg());
                   8106:                 return(1,$currentphase);
                   8107:             }
                   8108:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8109:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8110:         }
                   8111:     } else {
                   8112:         $r->print(&navmap_errormsg());
                   8113:         return(1,$currentphase);
                   8114:     }
                   8115: 
                   8116: 
1.649     raeburn  8117:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8118:     if ($nav_error) {
1.691     raeburn  8119:         $r->print(&navmap_errormsg());
1.693     raeburn  8120:         return(1,$currentphase);
1.582     raeburn  8121:     }
1.691     raeburn  8122: 
1.157     albertel 8123:     if (!$max_bubble) { $max_bubble=2**31; }
                   8124:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8125: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8126: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8127: 	my $scan_record =
                   8128:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8129: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8130:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8131:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8132: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8133: 	my @to_correct;
1.470     foxr     8134: 	
                   8135: 	# Probably here's where the error is...
                   8136: 
1.157     albertel 8137: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8138:             my $lastbubble;
                   8139:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8140:                my $question = $1;
                   8141:                my $subquestion = $2;
1.691     raeburn  8142:                my ($first,$responsenum);
                   8143:                if ($randomorder || $randompick) {
                   8144:                    $responsenum = $respnumlookup{$question-1};
                   8145:                    $first = $startline{$question-1};
                   8146:                } else {
                   8147:                    $responsenum = $question-1; 
                   8148:                    $first = $first_bubble_line{$responsenum};
                   8149:                }
                   8150:                if (!defined($first)) { next; }
                   8151:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8152:                my $subcount = 1;
                   8153:                while ($subcount<$subquestion) {
                   8154:                    $first += $subans[$subcount-1];
                   8155:                    $subcount ++;
                   8156:                }
                   8157:                my $count = $subans[$subquestion-1];
                   8158:                $lastbubble = $first + $count;
                   8159:             } else {
1.691     raeburn  8160:                my ($first,$responsenum);
                   8161:                if ($randomorder || $randompick) {
                   8162:                    $responsenum = $respnumlookup{$missing-1};
                   8163:                    $first = $startline{$missing-1};
                   8164:                } else {
                   8165:                    $responsenum = $missing-1;
                   8166:                    $first = $first_bubble_line{$responsenum};
                   8167:                }
                   8168:                if (!defined($first)) { next; }
                   8169:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8170:             }
                   8171:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8172: 	    push(@to_correct,$missing);
                   8173: 	}
                   8174: 	if (@to_correct) {
                   8175: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8176: 				     $line,'missingbubble',\@to_correct,
                   8177:                                      $randomorder,$randompick,\%respnumlookup,
                   8178:                                      \%startline);
1.157     albertel 8179: 	    return (1,$currentphase);
                   8180: 	}
                   8181: 
                   8182:     }
                   8183:     return (0,$currentphase+1);
                   8184: }
                   8185: 
1.663     raeburn  8186: sub hand_bubble_option {
                   8187:     my (undef, undef, $sequence) =
                   8188:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8189:     return if ($sequence eq '');
                   8190:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8191:     unless (ref($navmap)) {
                   8192:         return;
                   8193:     }
                   8194:     my $needs_hand_bubbles;
                   8195:     my $map=$navmap->getResourceByUrl($sequence);
                   8196:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8197:     foreach my $res (@resources) {
                   8198:         if (ref($res)) {
                   8199:             if ($res->is_problem()) {
                   8200:                 my $partlist = $res->parts();
                   8201:                 foreach my $part (@{ $partlist }) {
                   8202:                     my @types = $res->responseType($part);
                   8203:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8204:                         $needs_hand_bubbles = 1;
                   8205:                         last;
                   8206:                     }
                   8207:                 }
                   8208:             }
                   8209:         }
                   8210:     }
                   8211:     if ($needs_hand_bubbles) {
                   8212:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8213:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8214:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8215:                &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 />').
                   8216:                '<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;'.
                   8217:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8218:     }
                   8219:     return;
                   8220: }
1.423     albertel 8221: 
1.82      albertel 8222: sub scantron_process_students {
1.608     www      8223:     my ($r,$symb) = @_;
1.513     foxr     8224: 
1.257     albertel 8225:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8226:     if (!$symb) {
                   8227: 	return '';
                   8228:     }
1.324     albertel 8229:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8230: 
1.257     albertel 8231:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8232:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8233:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8234:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8235:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8236:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8237:     unless (ref($navmap)) {
                   8238:         $r->print(&navmap_errormsg());
                   8239:         return '';
1.691     raeburn  8240:     }
1.83      albertel 8241:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8242:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8243:         %grader_randomlists_by_symb);
1.677     raeburn  8244:     if (ref($map)) {
                   8245:         $randomorder = $map->randomorder();
1.689     raeburn  8246:         $randompick = $map->randompick();
1.691     raeburn  8247:     } else {
                   8248:         $r->print(&navmap_errormsg());
                   8249:         return '';
1.677     raeburn  8250:     }
1.691     raeburn  8251:     my $nav_error;
1.83      albertel 8252:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8253:     if ($randomorder || $randompick) {
                   8254:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8255:         if ($nav_error) {
                   8256:             $r->print(&navmap_errormsg());
                   8257:             return '';
                   8258:         }
                   8259:     }
1.557     raeburn  8260:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8261:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8262: 
1.554     raeburn  8263:     my ($uname,$udom);
1.82      albertel 8264:     my $result= <<SCANTRONFORM;
1.81      albertel 8265: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8266:   <input type="hidden" name="command" value="scantron_configphase" />
                   8267:   $default_form_data
                   8268: SCANTRONFORM
1.82      albertel 8269:     $r->print($result);
                   8270: 
                   8271:     my @delayqueue;
1.542     raeburn  8272:     my (%completedstudents,%scandata);
1.140     albertel 8273:     
1.520     www      8274:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8275:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8276:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8277:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8278:     $r->print('<br />');
1.140     albertel 8279:     my $start=&Time::HiRes::time();
1.158     albertel 8280:     my $i=-1;
1.542     raeburn  8281:     my $started;
1.447     foxr     8282: 
1.649     raeburn  8283:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8284:     if ($nav_error) {
                   8285:         $r->print(&navmap_errormsg());
                   8286:         return '';
                   8287:     }
                   8288: 
1.513     foxr     8289:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8290:     # the user and return.
                   8291: 
                   8292:     if ($ssi_error) {
                   8293: 	$r->print("</form>");
                   8294: 	&ssi_print_error($r);
1.520     www      8295:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8296: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8297:     }
1.447     foxr     8298: 
1.542     raeburn  8299:     my %lettdig = &letter_to_digits();
                   8300:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8301:     my %orderedforcode;
1.542     raeburn  8302: 
1.157     albertel 8303:     while ($i<$scanlines->{'count'}) {
                   8304:  	($uname,$udom)=('','');
                   8305:  	$i++;
1.200     albertel 8306:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8307:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8308: 	if ($started) {
1.667     www      8309: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8310: 	}
                   8311: 	$started=1;
1.691     raeburn  8312:         my %respnumlookup = ();
                   8313:         my %startline = ();
                   8314:         my $total;
1.157     albertel 8315:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8316:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8317:                                                  $randompick,$sequence,\@master_seq,
                   8318:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8319:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8320:                                                  \$total);
1.157     albertel 8321:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8322:  					      \%idmap,$i)) {
                   8323:   	    &scantron_add_delay(\@delayqueue,$line,
                   8324:  				'Unable to find a student that matches',1);
                   8325:  	    next;
                   8326:   	}
                   8327:  	if (exists $completedstudents{$uname}) {
                   8328:  	    &scantron_add_delay(\@delayqueue,$line,
                   8329:  				'Student '.$uname.' has multiple sheets',2);
                   8330:  	    next;
                   8331:  	}
1.677     raeburn  8332:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8333:         my $user = $uname.':'.$usec;
1.157     albertel 8334:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8335: 
1.677     raeburn  8336:         my $scancode;
                   8337:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8338:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8339:             $scancode = $scan_record->{'scantron.CODE'};
                   8340:         } else {
                   8341:             $scancode = '';
                   8342:         }
                   8343: 
                   8344:         my @mapresources = @resources;
1.689     raeburn  8345:         if ($randomorder || $randompick) {
1.678     raeburn  8346:             @mapresources = 
1.691     raeburn  8347:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8348:                              \%orderedforcode);
1.677     raeburn  8349:         }
1.586     raeburn  8350:         my (%partids_by_symb,$res_error);
1.677     raeburn  8351:         foreach my $resource (@mapresources) {
1.586     raeburn  8352:             my $ressymb;
                   8353:             if (ref($resource)) {
                   8354:                 $ressymb = $resource->symb();
                   8355:             } else {
                   8356:                 $res_error = 1;
                   8357:                 last;
                   8358:             }
1.557     raeburn  8359:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8360:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8361:                 my ($analysis,$parts) =
1.672     raeburn  8362:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8363:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8364:                 $partids_by_symb{$ressymb} = $parts;
                   8365:             } else {
                   8366:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8367:             }
1.554     raeburn  8368:         }
                   8369: 
1.586     raeburn  8370:         if ($res_error) {
                   8371:             &scantron_add_delay(\@delayqueue,$line,
                   8372:                                 'An error occurred while grading student '.$uname,2);
                   8373:             next;
                   8374:         }
                   8375: 
1.330     albertel 8376: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8377:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8378: 
                   8379: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8380: 	    &scantron_putfile($scanlines,$scan_data);
                   8381: 	}
1.161     albertel 8382: 	
1.542     raeburn  8383:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8384:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8385:                                    $bubbles_per_row,$randomorder,$randompick,
                   8386:                                    \%respnumlookup,\%startline) 
                   8387:             eq 'ssi_error') {
1.542     raeburn  8388:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8389:             $r->print("</form>");
                   8390:             &ssi_print_error($r);
                   8391:             &Apache::lonnet::remove_lock($lock);
                   8392:             return '';      # Why return ''?  Beats me.
                   8393:         }
1.513     foxr     8394: 
1.692     raeburn  8395:         if (($scancode) && ($randomorder || $randompick)) {
                   8396:             my $parmresult =
                   8397:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8398:                                                        '0_examcode',2,$scancode,
                   8399:                                                        'string_examcode',$uname,
                   8400:                                                        $udom);
                   8401:         }
1.140     albertel 8402: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8403:         if ($env{'form.verifyrecord'}) {
                   8404:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8405:             if ($randompick) {
                   8406:                 if ($total) {
                   8407:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8408:                 }
                   8409:             }
                   8410: 
1.542     raeburn  8411:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8412:             chomp($studentdata);
                   8413:             $studentdata =~ s/\r$//;
                   8414:             my $studentrecord = '';
                   8415:             my $counter = -1;
1.677     raeburn  8416:             foreach my $resource (@mapresources) {
1.554     raeburn  8417:                 my $ressymb = $resource->symb();
1.542     raeburn  8418:                 ($counter,my $recording) =
                   8419:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8420:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8421:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8422:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8423:                 $studentrecord .= $recording;
                   8424:             }
                   8425:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8426:                 &Apache::lonxml::clear_problem_counter();
                   8427:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8428:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8429:                                            $bubbles_per_row,$randomorder,$randompick,
                   8430:                                            \%respnumlookup,\%startline) 
                   8431:                     eq 'ssi_error') {
1.554     raeburn  8432:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8433:                     $r->print("</form>");
                   8434:                     &ssi_print_error($r);
                   8435:                     &Apache::lonnet::remove_lock($lock);
                   8436:                     delete($completedstudents{$uname});
                   8437:                     return '';
                   8438:                 }
1.542     raeburn  8439:                 $counter = -1;
                   8440:                 $studentrecord = '';
1.677     raeburn  8441:                 foreach my $resource (@mapresources) {
1.554     raeburn  8442:                     my $ressymb = $resource->symb();
1.542     raeburn  8443:                     ($counter,my $recording) =
                   8444:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8445:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8446:                                                  \%scantron_config,\%lettdig,$numletts,
                   8447:                                                  $randomorder,$randompick,\%respnumlookup,
                   8448:                                                  \%startline);
1.542     raeburn  8449:                     $studentrecord .= $recording;
                   8450:                 }
                   8451:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8452:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8453:                     if ($scancode eq '') {
1.658     bisitz   8454:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8455:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8456:                     } else {
1.658     bisitz   8457:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8458:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8459:                     }
                   8460:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8461:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8462:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8463:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8464:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8465:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8466:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8467:                               &Apache::loncommon::end_data_table_row().
                   8468:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8469:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8470:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8471:                               &Apache::loncommon::end_data_table_row().
                   8472:                               &Apache::loncommon::end_data_table().'</p>');
                   8473:                 } else {
                   8474:                     $r->print('<br /><span class="LC_warning">'.
                   8475:                              &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 />'.
                   8476:                              &mt("As a consequence, this user's submission history records two tries.").
                   8477:                                  '</span><br />');
                   8478:                 }
                   8479:             }
                   8480:         }
1.543     raeburn  8481:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8482:     } continue {
1.330     albertel 8483: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8484: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8485:     }
1.140     albertel 8486:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8487:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8488: #    my $lasttime = &Time::HiRes::time()-$start;
                   8489: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8490: 
1.200     albertel 8491:     $r->print("</form>");
1.157     albertel 8492:     return '';
1.75      albertel 8493: }
1.157     albertel 8494: 
1.557     raeburn  8495: sub graders_resources_pass {
1.649     raeburn  8496:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8497:         $bubbles_per_row) = @_;
1.557     raeburn  8498:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8499:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8500:         foreach my $resource (@{$resources}) {
                   8501:             my $ressymb = $resource->symb();
                   8502:             my ($analysis,$parts) =
                   8503:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8504:                                           $env{'user.name'},$env{'user.domain'},
                   8505:                                           1,$bubbles_per_row);
1.557     raeburn  8506:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8507:             if (ref($analysis) eq 'HASH') {
                   8508:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8509:                     $grader_randomlists_by_symb->{$ressymb} =
                   8510:                         $analysis->{'parts_withrandomlist'};
                   8511:                 }
                   8512:             }
                   8513:         }
                   8514:     }
                   8515:     return;
                   8516: }
                   8517: 
1.678     raeburn  8518: =pod
                   8519: 
                   8520: =item users_order
                   8521: 
                   8522:   Returns array of resources in current map, ordered based on either CODE,
                   8523:   if this is a CODEd exam, or based on student's identity if this is a 
                   8524:   "NAMEd" exam.
                   8525: 
1.691     raeburn  8526:   Should be used when randomorder and/or randompick applied when the 
                   8527:   corresponding exam was printed, prior to students completing bubblesheets 
                   8528:   for the version of the exam the student received.
1.678     raeburn  8529: 
                   8530: =cut
                   8531: 
                   8532: sub users_order  {
1.691     raeburn  8533:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8534:     my @mapresources;
1.691     raeburn  8535:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8536:         return @mapresources;
1.691     raeburn  8537:     }
                   8538:     if ($scancode) {
                   8539:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8540:             @mapresources = @{$orderedforcode->{$scancode}};
                   8541:         } else {
                   8542:             $env{'form.CODE'} = $scancode;
                   8543:             my $actual_seq =
                   8544:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8545:                                                                $master_seq,
                   8546:                                                                $user,$scancode,1);
                   8547:             if (ref($actual_seq) eq 'ARRAY') {
                   8548:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8549:                 if (ref($orderedforcode) eq 'HASH') {
                   8550:                     if (@mapresources > 0) { 
                   8551:                         $orderedforcode->{$scancode} = \@mapresources;
                   8552:                     }
                   8553:                 }
                   8554:             }
                   8555:             delete($env{'form.CODE'});
1.678     raeburn  8556:         }
                   8557:     } else {
                   8558:         my $actual_seq =
                   8559:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8560:                                                            $master_seq,
1.688     raeburn  8561:                                                            $user,undef,1);
1.678     raeburn  8562:         if (ref($actual_seq) eq 'ARRAY') {
                   8563:             @mapresources = 
                   8564:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8565:         }
1.691     raeburn  8566:     }
                   8567:     return @mapresources;
1.678     raeburn  8568: }
                   8569: 
1.542     raeburn  8570: sub grade_student_bubbles {
1.691     raeburn  8571:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8572:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8573:     my $uselookup = 0;
                   8574:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8575:         (ref($startline) eq 'HASH')) {
                   8576:         $uselookup = 1;
                   8577:     }
                   8578: 
1.554     raeburn  8579:     if (ref($resources) eq 'ARRAY') {
                   8580:         my $count = 0;
                   8581:         foreach my $resource (@{$resources}) {
                   8582:             my $ressymb = $resource->symb();
                   8583:             my %form = ('submitted'      => 'scantron',
                   8584:                         'grade_target'   => 'grade',
                   8585:                         'grade_username' => $uname,
                   8586:                         'grade_domain'   => $udom,
                   8587:                         'grade_courseid' => $env{'request.course.id'},
                   8588:                         'grade_symb'     => $ressymb,
                   8589:                         'CODE'           => $scancode
                   8590:                        );
1.649     raeburn  8591:             if ($bubbles_per_row ne '') {
                   8592:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8593:             }
1.663     raeburn  8594:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8595:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8596:             }
1.554     raeburn  8597:             if (ref($parts) eq 'HASH') {
                   8598:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8599:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8600:                         if ($uselookup) {
                   8601:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8602:                         } else {
                   8603:                             $form{'scantron_questnum_start.'.$part} =
                   8604:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8605:                         }
1.554     raeburn  8606:                         $count++;
                   8607:                     }
                   8608:                 }
                   8609:             }
                   8610:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8611:             return 'ssi_error' if ($ssi_error);
                   8612:             last if (&Apache::loncommon::connection_aborted($r));
                   8613:         }
1.542     raeburn  8614:     }
                   8615:     return;
                   8616: }
                   8617: 
1.157     albertel 8618: sub scantron_upload_scantron_data {
1.608     www      8619:     my ($r,$symb)=@_;
1.565     raeburn  8620:     my $dom = $env{'request.role.domain'};
                   8621:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8622:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8623:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8624: 							  'domainid',
1.565     raeburn  8625: 							  'coursename',$dom);
                   8626:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8627:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8628:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8629:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8630:     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 8631:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8632:     function checkUpload(formname) {
                   8633: 	if (formname.upfile.value == "") {
1.579     raeburn  8634: 	    alert("'.$nofile_alert.'");
1.157     albertel 8635: 	    return false;
                   8636: 	}
1.565     raeburn  8637:         if (formname.courseid.value == "") {
1.579     raeburn  8638:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8639:             return false;
                   8640:         }
1.157     albertel 8641: 	formname.submit();
                   8642:     }
1.565     raeburn  8643: 
                   8644:     function ToSyllabus() {
                   8645:         var cdom = '."'$dom'".';
                   8646:         var cnum = document.rules.courseid.value;
                   8647:         if (cdom == "" || cdom == null) {
                   8648:             return;
                   8649:         }
                   8650:         if (cnum == "" || cnum == null) {
                   8651:            return;
                   8652:         }
                   8653:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8654:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8655:         return;
                   8656:     }
                   8657: 
1.597     wenzelju 8658: '));
                   8659:     $r->print('
1.648     bisitz   8660: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8661: 
1.492     albertel 8662: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8663: '.$default_form_data.
                   8664:   &Apache::lonhtmlcommon::start_pick_box().
                   8665:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8666:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8667:   &Apache::lonhtmlcommon::row_closure().
                   8668:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8669:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8670:   &Apache::lonhtmlcommon::row_closure().
                   8671:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8672:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8673:   &Apache::lonhtmlcommon::row_closure().
                   8674:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8675:   '<input type="file" name="upfile" size="50" />'.
                   8676:   &Apache::lonhtmlcommon::row_closure(1).
                   8677:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8678: 
1.492     albertel 8679: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8680: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8681: </form>
1.492     albertel 8682: ');
1.157     albertel 8683:     return '';
                   8684: }
                   8685: 
1.423     albertel 8686: 
1.157     albertel 8687: sub scantron_upload_scantron_data_save {
1.608     www      8688:     my($r,$symb)=@_;
1.182     albertel 8689:     my $doanotherupload=
                   8690: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8691: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8692: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8693: 	'</form>'."\n";
1.257     albertel 8694:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8695: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8696: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8697: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8698: 	unless ($symb) {
1.182     albertel 8699: 	    $r->print($doanotherupload);
                   8700: 	}
1.162     albertel 8701: 	return '';
                   8702:     }
1.257     albertel 8703:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8704:     my $uploadedfile;
1.710     bisitz   8705:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8706:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8707:         $r->print(
                   8708:             &Apache::lonhtmlcommon::confirm_success(
                   8709:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8710:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8711:     } else {
1.568     raeburn  8712:         my $result = 
                   8713:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8714:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8715:         if ($result =~ m{^/uploaded/}) {
                   8716:             $r->print(
                   8717:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8718:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8719:                         (length($env{'form.upfile'})-1),
                   8720:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8721:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8722:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8723:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8724:         } else {
                   8725:             $r->print(
                   8726:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8727:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8728:                           $result,
1.568     raeburn  8729: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8730: 	}
                   8731:     }
1.174     albertel 8732:     if ($symb) {
1.612     www      8733: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8734:     } else {
1.182     albertel 8735: 	$r->print($doanotherupload);
1.174     albertel 8736:     }
1.157     albertel 8737:     return '';
                   8738: }
                   8739: 
1.567     raeburn  8740: sub validate_uploaded_scantron_file {
                   8741:     my ($cdom,$cname,$fname) = @_;
                   8742:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8743:     my @lines;
                   8744:     if ($scanlines ne '-1') {
                   8745:         @lines=split("\n",$scanlines,-1);
                   8746:     }
                   8747:     my $output;
                   8748:     if (@lines) {
                   8749:         my (%counts,$max_match_format);
1.710     bisitz   8750:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8751:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8752:         my %idmap = &username_to_idmap($classlist);
                   8753:         foreach my $key (keys(%idmap)) {
                   8754:             my $lckey = lc($key);
                   8755:             $idmap{$lckey} = $idmap{$key};
                   8756:         }
                   8757:         my %unique_formats;
                   8758:         my @formatlines = &get_scantronformat_file();
                   8759:         foreach my $line (@formatlines) {
                   8760:             chomp($line);
                   8761:             my @config = split(/:/,$line);
                   8762:             my $idstart = $config[5];
                   8763:             my $idlength = $config[6];
                   8764:             if (($idstart ne '') && ($idlength > 0)) {
                   8765:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8766:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8767:                 } else {
                   8768:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8769:                 }
                   8770:             }
                   8771:         }
                   8772:         foreach my $key (keys(%unique_formats)) {
                   8773:             my ($idstart,$idlength) = split(':',$key);
                   8774:             %{$counts{$key}} = (
                   8775:                                'found'   => 0,
                   8776:                                'total'   => 0,
                   8777:                               );
                   8778:             foreach my $line (@lines) {
                   8779:                 next if ($line =~ /^#/);
                   8780:                 next if ($line =~ /^[\s\cz]*$/);
                   8781:                 my $id = substr($line,$idstart-1,$idlength);
                   8782:                 $id = lc($id);
                   8783:                 if (exists($idmap{$id})) {
                   8784:                     $counts{$key}{'found'} ++;
                   8785:                 }
                   8786:                 $counts{$key}{'total'} ++;
                   8787:             }
                   8788:             if ($counts{$key}{'total'}) {
                   8789:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8790:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8791:                     $max_match_pct = $percent_match;
                   8792:                     $max_match_format = $key;
1.710     bisitz   8793:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8794:                     $max_match_count = $counts{$key}{'total'};
                   8795:                 }
                   8796:             }
                   8797:         }
                   8798:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8799:             my $format_descs;
                   8800:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8801:             for (my $i=0; $i<$numwithformat; $i++) {
                   8802:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8803:                 if ($i<$numwithformat-2) {
                   8804:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8805:                 } elsif ($i==$numwithformat-2) {
                   8806:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8807:                 } elsif ($i==$numwithformat-1) {
                   8808:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8809:                 }
                   8810:             }
                   8811:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8812:             $output .= '<br />';
                   8813:             if ($found_match_count == $max_match_count) {
                   8814:                 # 100% matching entries
                   8815:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8816:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8817:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8818:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8819:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8820:                     ' in the file (for the format defined for [_3]).',
                   8821:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8822:             } else {
                   8823:                 # Not all entries matching? -> Show warning and additional info
                   8824:                 $output .=
                   8825:                     &Apache::lonhtmlcommon::confirm_success(
                   8826:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8827:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8828:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8829:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8830:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8831:                         ' in the file (for the format defined for [_3]).',
                   8832:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8833:                     '<p class="LC_info">'.
                   8834:                     &mt('A low percentage of matches results from one of the following:').
                   8835:                     '</p><ul>'.
                   8836:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8837:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8838:                                '<i>'.$cdom.'</i>').'</li>'.
                   8839:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8840:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8841:                     '</ul>';
                   8842:             }
1.567     raeburn  8843:         }
                   8844:     } else {
1.710     bisitz   8845:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8846:     }
                   8847:     return $output;
                   8848: }
                   8849: 
1.202     albertel 8850: sub valid_file {
                   8851:     my ($requested_file)=@_;
                   8852:     foreach my $filename (sort(&scantron_filenames())) {
                   8853: 	if ($requested_file eq $filename) { return 1; }
                   8854:     }
                   8855:     return 0;
                   8856: }
                   8857: 
                   8858: sub scantron_download_scantron_data {
1.608     www      8859:     my ($r,$symb)=@_;
                   8860:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8861:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8862:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8863:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8864:     if (! &valid_file($file)) {
1.492     albertel 8865: 	$r->print('
1.202     albertel 8866: 	<p>
1.686     bisitz   8867: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8868:         </p>
1.492     albertel 8869: ');
1.202     albertel 8870: 	return;
                   8871:     }
                   8872:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8873:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8874:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8875:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8876:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8877:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8878:     $r->print('
1.202     albertel 8879:     <p>
1.711     bisitz   8880: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
1.492     albertel 8881: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8882:     </p>
                   8883:     <p>
1.492     albertel 8884: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8885: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8886:     </p>
                   8887:     <p>
1.492     albertel 8888: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8889: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8890:     </p>
1.492     albertel 8891: ');
1.202     albertel 8892:     return '';
                   8893: }
1.157     albertel 8894: 
1.523     raeburn  8895: sub checkscantron_results {
1.608     www      8896:     my ($r,$symb) = @_;
1.523     raeburn  8897:     if (!$symb) {return '';}
                   8898:     my $cid = $env{'request.course.id'};
1.542     raeburn  8899:     my %lettdig = &letter_to_digits();
1.523     raeburn  8900:     my $numletts = scalar(keys(%lettdig));
                   8901:     my $cnum = $env{'course.'.$cid.'.num'};
                   8902:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8903:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8904:     my %record;
                   8905:     my %scantron_config =
                   8906:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8907:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8908:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8909:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8910:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8911:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8912:     unless (ref($navmap)) {
                   8913:         $r->print(&navmap_errormsg());
                   8914:         return '';
                   8915:     }
1.523     raeburn  8916:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8917:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8918:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8919:     if (ref($map)) { 
                   8920:         $randomorder=$map->randomorder();
1.689     raeburn  8921:         $randompick=$map->randompick();
1.677     raeburn  8922:     }
1.557     raeburn  8923:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8924:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8925:     if ($nav_error) {
                   8926:         $r->print(&navmap_errormsg());
                   8927:         return '';
1.678     raeburn  8928:     }
1.673     raeburn  8929:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8930:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8931:     my ($uname,$udom);
1.523     raeburn  8932:     my (%scandata,%lastname,%bylast);
                   8933:     $r->print('
                   8934: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8935: 
                   8936:     my @delayqueue;
                   8937:     my %completedstudents;
                   8938: 
1.691     raeburn  8939:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8940:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8941:     my ($username,$domain,$started);
1.649     raeburn  8942:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8943:     if ($nav_error) {
                   8944:         $r->print(&navmap_errormsg());
                   8945:         return '';
                   8946:     }
1.523     raeburn  8947: 
1.667     www      8948:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8949:     my $start=&Time::HiRes::time();
                   8950:     my $i=-1;
                   8951: 
                   8952:     while ($i<$scanlines->{'count'}) {
                   8953:         ($username,$domain,$uname)=('','','');
                   8954:         $i++;
                   8955:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8956:         if ($line=~/^[\s\cz]*$/) { next; }
                   8957:         if ($started) {
1.667     www      8958:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8959:         }
                   8960:         $started=1;
                   8961:         my $scan_record=
                   8962:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8963:                                                      $scan_data);
1.693     raeburn  8964:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8965:                                               \%idmap,$i)) {
1.523     raeburn  8966:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8967:                                 'Unable to find a student that matches',1);
                   8968:             next;
                   8969:         }
                   8970:         if (exists $completedstudents{$uname}) {
                   8971:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8972:                                 'Student '.$uname.' has multiple sheets',2);
                   8973:             next;
                   8974:         }
                   8975:         my $pid = $scan_record->{'scantron.ID'};
                   8976:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8977:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  8978:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8979:         my $user = $uname.':'.$usec;
1.523     raeburn  8980:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  8981: 
1.678     raeburn  8982:         my $scancode;
1.677     raeburn  8983:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8984:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8985:             $scancode = $scan_record->{'scantron.CODE'};
                   8986:         } else {
                   8987:             $scancode = '';
                   8988:         }
                   8989: 
                   8990:         my @mapresources = @resources;
1.691     raeburn  8991:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8992:         my %respnumlookup=();
                   8993:         my %startline=();
1.689     raeburn  8994:         if ($randomorder || $randompick) {
1.678     raeburn  8995:             @mapresources =
1.691     raeburn  8996:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8997:                              \%orderedforcode);
                   8998:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   8999:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9000:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9001:                                              \%respnumlookup,\%startline);
                   9002:             if ($randompick && $total) {
                   9003:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9004:             }
1.677     raeburn  9005:         }
1.691     raeburn  9006:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9007:         chomp($scandata{$pid});
                   9008:         $scandata{$pid} =~ s/\r$//;
                   9009: 
1.523     raeburn  9010:         my $counter = -1;
1.677     raeburn  9011:         foreach my $resource (@mapresources) {
1.557     raeburn  9012:             my $parts;
1.554     raeburn  9013:             my $ressymb = $resource->symb();
1.557     raeburn  9014:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9015:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9016:                 (my $analysis,$parts) =
1.672     raeburn  9017:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9018:                                               $username,$domain,undef,
                   9019:                                               $bubbles_per_row);
1.557     raeburn  9020:             } else {
                   9021:                 $parts = $grader_partids_by_symb{$ressymb};
                   9022:             }
1.542     raeburn  9023:             ($counter,my $recording) =
                   9024:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9025:                                          $scandata{$pid},$parts,
1.691     raeburn  9026:                                          \%scantron_config,\%lettdig,$numletts,
                   9027:                                          $randomorder,$randompick,
                   9028:                                          \%respnumlookup,\%startline);
1.542     raeburn  9029:             $record{$pid} .= $recording;
1.523     raeburn  9030:         }
                   9031:     }
                   9032:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9033:     $r->print('<br />');
                   9034:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9035:     $passed = 0;
                   9036:     $failed = 0;
                   9037:     $numstudents = 0;
                   9038:     foreach my $last (sort(keys(%bylast))) {
                   9039:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9040:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9041:                 my $showscandata = $scandata{$pid};
                   9042:                 my $showrecord = $record{$pid};
                   9043:                 $showscandata =~ s/\s/&nbsp;/g;
                   9044:                 $showrecord =~ s/\s/&nbsp;/g;
                   9045:                 if ($scandata{$pid} eq $record{$pid}) {
                   9046:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9047:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9048: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9049: '</tr>'."\n".
                   9050: '<tr class="'.$css_class.'">'."\n".
                   9051: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   9052:                     $passed ++;
                   9053:                 } else {
                   9054:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9055:                     $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  9056: '</tr>'."\n".
                   9057: '<tr class="'.$css_class.'">'."\n".
                   9058: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   9059: '</tr>'."\n";
                   9060:                     $failed ++;
                   9061:                 }
                   9062:                 $numstudents ++;
                   9063:             }
                   9064:         }
                   9065:     }
1.648     bisitz   9066:     $r->print(
                   9067:         '<p>'
                   9068:        .&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).',
                   9069:             '<b>',
                   9070:             $numstudents,
                   9071:             '</b>',
                   9072:             $env{'form.scantron_maxbubble'})
                   9073:        .'</p>'
                   9074:     );
1.682     raeburn  9075:     $r->print('<p>'
1.683     raeburn  9076:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9077:              .'<br />'
                   9078:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9079:              .'</p>'
                   9080:     );
1.523     raeburn  9081:     if ($passed) {
1.572     www      9082:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9083:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9084:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9085:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9086:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9087:                  $okstudents."\n".
                   9088:                  &Apache::loncommon::end_data_table().'<br />');
                   9089:     }
                   9090:     if ($failed) {
1.572     www      9091:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9092:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9093:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9094:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9095:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9096:                  $badstudents."\n".
                   9097:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9098:                  &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  9099:     }
1.614     www      9100:     $r->print('</form><br />');
1.523     raeburn  9101:     return;
                   9102: }
                   9103: 
1.542     raeburn  9104: sub verify_scantron_grading {
1.554     raeburn  9105:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9106:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9107:         $respnumlookup,$startline) = @_;
1.542     raeburn  9108:     my ($record,%expected,%startpos);
                   9109:     return ($counter,$record) if (!ref($resource));
                   9110:     return ($counter,$record) if (!$resource->is_problem());
                   9111:     my $symb = $resource->symb();
1.554     raeburn  9112:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9113:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9114:         $counter ++;
                   9115:         $expected{$part_id} = 0;
1.691     raeburn  9116:         my $respnum = $counter;
                   9117:         if ($randomorder || $randompick) {
                   9118:             $respnum = $respnumlookup->{$counter};
                   9119:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9120:         } else {
                   9121:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9122:         }
                   9123:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9124:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9125:             foreach my $item (@sub_lines) {
                   9126:                 $expected{$part_id} += $item;
                   9127:             }
                   9128:         } else {
1.691     raeburn  9129:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9130:         }
                   9131:     }
                   9132:     if ($symb) {
                   9133:         my %recorded;
                   9134:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9135:         if ($returnhash{'version'}) {
                   9136:             my %lasthash=();
                   9137:             my $version;
                   9138:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9139:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9140:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9141:                 }
                   9142:             }
                   9143:             foreach my $key (keys(%lasthash)) {
                   9144:                 if ($key =~ /\.scantron$/) {
                   9145:                     my $value = &unescape($lasthash{$key});
                   9146:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9147:                     if ($value eq '') {
                   9148:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9149:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9150:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9151:                             }
                   9152:                         }
                   9153:                     } else {
                   9154:                         my @tocheck;
                   9155:                         my @items = split(//,$value);
                   9156:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9157:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9158:                             if (@items < $expected{$part_id}) {
                   9159:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9160:                                 my @singles = split(//,$fragment);
                   9161:                                 foreach my $pos (@singles) {
                   9162:                                     if ($pos eq ' ') {
                   9163:                                         push(@tocheck,$pos);
                   9164:                                     } else {
                   9165:                                         my $next = shift(@items);
                   9166:                                         push(@tocheck,$next);
                   9167:                                     }
                   9168:                                 }
                   9169:                             } else {
                   9170:                                 @tocheck = @items;
                   9171:                             }
                   9172:                             foreach my $letter (@tocheck) {
                   9173:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9174:                                     if ($letter !~ /^[A-J]$/) {
                   9175:                                         $letter = $scantron_config->{'Qoff'};
                   9176:                                     }
                   9177:                                     $recorded{$part_id} .= $letter;
                   9178:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9179:                                     my $digit;
                   9180:                                     if ($letter !~ /^[A-J]$/) {
                   9181:                                         $digit = $scantron_config->{'Qoff'};
                   9182:                                     } else {
                   9183:                                         $digit = $lettdig->{$letter};
                   9184:                                     }
                   9185:                                     $recorded{$part_id} .= $digit;
                   9186:                                 }
                   9187:                             }
                   9188:                         } else {
                   9189:                             @tocheck = @items;
                   9190:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9191:                                 my $curr_sub = shift(@tocheck);
                   9192:                                 my $digit;
                   9193:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9194:                                     $digit = $lettdig->{$curr_sub}-1;
                   9195:                                 }
                   9196:                                 if ($curr_sub eq 'J') {
                   9197:                                     $digit += scalar($numletts);
                   9198:                                 }
                   9199:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9200:                                     if ($j == $digit) {
                   9201:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9202:                                     } else {
                   9203:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9204:                                     }
                   9205:                                 }
                   9206:                             }
                   9207:                         }
                   9208:                     }
                   9209:                 }
                   9210:             }
                   9211:         }
1.554     raeburn  9212:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9213:             if ($recorded{$part_id} eq '') {
                   9214:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9215:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9216:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9217:                     }
                   9218:                 }
                   9219:             }
                   9220:             $record .= $recorded{$part_id};
                   9221:         }
                   9222:     }
                   9223:     return ($counter,$record);
                   9224: }
                   9225: 
1.691     raeburn  9226: sub letter_to_digits {
1.542     raeburn  9227:     my %lettdig = (
                   9228:                     A => 1,
                   9229:                     B => 2,
                   9230:                     C => 3,
                   9231:                     D => 4,
                   9232:                     E => 5,
                   9233:                     F => 6,
                   9234:                     G => 7,
                   9235:                     H => 8,
                   9236:                     I => 9,
                   9237:                     J => 0,
                   9238:                   );
                   9239:     return %lettdig;
                   9240: }
                   9241: 
1.423     albertel 9242: 
1.75      albertel 9243: #-------- end of section for handling grading scantron forms -------
                   9244: #
                   9245: #-------------------------------------------------------------------
                   9246: 
1.72      ng       9247: #-------------------------- Menu interface -------------------------
                   9248: #
1.614     www      9249: #--- Href with symb and command ---
                   9250: 
                   9251: sub href_symb_cmd {
                   9252:     my ($symb,$cmd)=@_;
1.669     raeburn  9253:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9254: }
                   9255: 
1.443     banghart 9256: sub grading_menu {
1.608     www      9257:     my ($request,$symb) = @_;
1.443     banghart 9258:     if (!$symb) {return '';}
                   9259: 
                   9260:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9261:                   'command'=>'individual');
1.538     schulted 9262:     
1.598     www      9263:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9264: 
                   9265:     $fields{'command'}='ungraded';
                   9266:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9267: 
                   9268:     $fields{'command'}='table';
                   9269:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9270: 
                   9271:     $fields{'command'}='all_for_one';
                   9272:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9273: 
1.621     www      9274:     $fields{'command'}='downloadfilesselect';
                   9275:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9276: 
1.443     banghart 9277:     $fields{'command'} = 'csvform';
1.538     schulted 9278:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9279:     
1.443     banghart 9280:     $fields{'command'} = 'processclicker';
1.538     schulted 9281:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9282:     
1.443     banghart 9283:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9284:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9285: 
                   9286:     $fields{'command'} = 'initialverifyreceipt';
                   9287:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9288:     
1.598     www      9289:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9290:             items =>[
1.598     www      9291:                         {	linktext => 'Select individual students to grade',
                   9292:                     		url => $url1a,
1.538     schulted 9293:                     		permission => 'F',
1.636     wenzelju 9294:                     		icon => 'grade_students.png',
1.598     www      9295:                     		linktitle => 'Grade current resource for a selection of students.'
                   9296:                         }, 
                   9297:                         {       linktext => 'Grade ungraded submissions.',
                   9298:                                 url => $url1b,
                   9299:                                 permission => 'F',
1.636     wenzelju 9300:                                 icon => 'ungrade_sub.png',
1.598     www      9301:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9302:                         },
1.598     www      9303: 
                   9304:                         {       linktext => 'Grading table',
                   9305:                                 url => $url1c,
                   9306:                                 permission => 'F',
1.636     wenzelju 9307:                                 icon => 'grading_table.png',
1.598     www      9308:                                 linktitle => 'Grade current resource for all students.'
                   9309:                         },
1.615     www      9310:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9311:                                 url => $url1d,
                   9312:                                 permission => 'F',
1.636     wenzelju 9313:                                 icon => 'grade_PageFolder.png',
1.598     www      9314:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9315:                         },
                   9316:                         {       linktext => 'Download submissions',
                   9317:                                 url => $url1e,
                   9318:                                 permission => 'F',
1.636     wenzelju 9319:                                 icon => 'download_sub.png',
1.621     www      9320:                                 linktitle => 'Download all students submissions.'
1.598     www      9321:                         }]},
                   9322:                          { categorytitle=>'Automated Grading',
                   9323:                items =>[
                   9324: 
1.538     schulted 9325:                 	    {	linktext => 'Upload Scores',
                   9326:                     		url => $url2,
                   9327:                     		permission => 'F',
                   9328:                     		icon => 'uploadscores.png',
                   9329:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9330:                 	    },
                   9331:                 	    {	linktext => 'Process Clicker',
                   9332:                     		url => $url3,
                   9333:                     		permission => 'F',
                   9334:                     		icon => 'addClickerInfoFile.png',
                   9335:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9336:                 	    },
1.587     raeburn  9337:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9338:                     		url => $url4,
                   9339:                     		permission => 'F',
1.636     wenzelju 9340:                     		icon => 'bubblesheet.png',
1.648     bisitz   9341:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9342:                 	    },
1.616     www      9343:                             {   linktext => 'Verify Receipt Number',
1.602     www      9344:                                 url => $url5,
                   9345:                                 permission => 'F',
1.636     wenzelju 9346:                                 icon => 'receipt_number.png',
1.602     www      9347:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9348:                             }
                   9349: 
1.538     schulted 9350:                     ]
                   9351:             });
                   9352: 
1.443     banghart 9353:     # Create the menu
                   9354:     my $Str;
1.445     banghart 9355:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9356:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9357:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9358: 
1.602     www      9359:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9360:     return $Str;    
                   9361: }
                   9362: 
1.598     www      9363: 
                   9364: sub ungraded {
                   9365:     my ($request)=@_;
                   9366:     &submit_options($request);
                   9367: }
                   9368: 
1.599     www      9369: sub submit_options_sequence {
1.608     www      9370:     my ($request,$symb) = @_;
1.599     www      9371:     if (!$symb) {return '';}
1.600     www      9372:     &commonJSfunctions($request);
                   9373:     my $result;
1.599     www      9374: 
1.600     www      9375:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9376:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9377:     $result.=&selectfield(0).
1.601     www      9378:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9379:             <div>
                   9380:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9381:             </div>
                   9382:         </div>
                   9383:   </form>';
                   9384:     return $result;
                   9385: }
                   9386: 
                   9387: sub submit_options_table {
1.608     www      9388:     my ($request,$symb) = @_;
1.600     www      9389:     if (!$symb) {return '';}
1.599     www      9390:     &commonJSfunctions($request);
                   9391:     my $result;
                   9392: 
                   9393:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9394:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9395: 
1.632     www      9396:     $result.=&selectfield(0).
1.601     www      9397:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9398:             <div>
                   9399:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9400:             </div>
                   9401:         </div>
                   9402:   </form>';
                   9403:     return $result;
                   9404: }
1.443     banghart 9405: 
1.621     www      9406: sub submit_options_download {
                   9407:     my ($request,$symb) = @_;
                   9408:     if (!$symb) {return '';}
                   9409: 
                   9410:     &commonJSfunctions($request);
                   9411: 
                   9412:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9413:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9414:     $result.='
                   9415: <h2>
                   9416:   '.&mt('Select Students for Which to Download Submissions').'
                   9417: </h2>'.&selectfield(1).'
                   9418:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9419:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9420:             </div>
                   9421:           </div>
1.600     www      9422: 
                   9423: 
1.621     www      9424:   </form>';
                   9425:     return $result;
                   9426: }
                   9427: 
1.443     banghart 9428: #--- Displays the submissions first page -------
                   9429: sub submit_options {
1.608     www      9430:     my ($request,$symb) = @_;
1.72      ng       9431:     if (!$symb) {return '';}
                   9432: 
1.118     ng       9433:     &commonJSfunctions($request);
1.473     albertel 9434:     my $result;
1.533     bisitz   9435: 
1.72      ng       9436:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9437: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9438:     $result.=&selectfield(1).'
1.601     www      9439:                 <input type="hidden" name="command" value="submission" /> 
                   9440: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9441:             </div>
                   9442:           </div>
                   9443: 
                   9444: 
                   9445:   </form>';
                   9446:     return $result;
                   9447: }
1.533     bisitz   9448: 
1.601     www      9449: sub selectfield {
                   9450:    my ($full)=@_;
1.635     raeburn  9451:    my %options = 
                   9452:           (&Apache::lonlocal::texthash(
                   9453:              'yes'       => 'with submissions',
                   9454:              'queued'    => 'in grading queue',
                   9455:              'graded'    => 'with ungraded submissions',
                   9456:              'incorrect' => 'with incorrect submissions',
                   9457:              'all'       => 'with any status'),
                   9458:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9459:    my $result='<div class="LC_columnSection">
1.537     harmsja  9460:   
1.533     bisitz   9461:     <fieldset>
                   9462:       <legend>
                   9463:        '.&mt('Sections').'
                   9464:       </legend>
1.601     www      9465:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9466:     </fieldset>
1.537     harmsja  9467:   
1.533     bisitz   9468:     <fieldset>
                   9469:       <legend>
                   9470:         '.&mt('Groups').'
                   9471:       </legend>
                   9472:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9473:     </fieldset>
1.537     harmsja  9474:   
1.533     bisitz   9475:     <fieldset>
                   9476:       <legend>
                   9477:         '.&mt('Access Status').'
                   9478:       </legend>
1.601     www      9479:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9480:     </fieldset>';
                   9481:     if ($full) {
                   9482:        $result.='
1.533     bisitz   9483:     <fieldset>
                   9484:       <legend>
                   9485:         '.&mt('Submission Status').'
1.601     www      9486:       </legend>'.
1.635     raeburn  9487:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9488:    '</fieldset>';
                   9489:     }
                   9490:     $result.='</div><br />';
1.44      ng       9491:     return $result;
1.2       albertel 9492: }
                   9493: 
1.285     albertel 9494: sub reset_perm {
                   9495:     undef(%perm);
                   9496: }
                   9497: 
                   9498: sub init_perm {
                   9499:     &reset_perm();
1.300     albertel 9500:     foreach my $test_perm ('vgr','mgr','opa') {
                   9501: 
                   9502: 	my $scope = $env{'request.course.id'};
                   9503: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9504: 
                   9505: 	    $scope .= '/'.$env{'request.course.sec'};
                   9506: 	    if ( $perm{$test_perm}=
                   9507: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9508: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9509: 	    } else {
                   9510: 		delete($perm{$test_perm});
                   9511: 	    }
1.285     albertel 9512: 	}
                   9513:     }
                   9514: }
                   9515: 
1.674     raeburn  9516: sub init_old_essays {
                   9517:     my ($symb,$apath,$adom,$aname) = @_;
                   9518:     if ($symb ne '') {
                   9519:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9520:         if (keys(%essays) > 0) {
                   9521:             $old_essays{$symb} = \%essays;
                   9522:         }
                   9523:     }
                   9524:     return;
                   9525: }
                   9526: 
                   9527: sub reset_old_essays {
                   9528:     undef(%old_essays);
                   9529: }
                   9530: 
1.400     www      9531: sub gather_clicker_ids {
1.408     albertel 9532:     my %clicker_ids;
1.400     www      9533: 
                   9534:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9535: 
                   9536:     # Set up a couple variables.
1.407     albertel 9537:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9538:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9539:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9540: 
1.407     albertel 9541:     foreach my $student (keys(%$classlist)) {
1.438     www      9542:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9543:         my $username = $classlist->{$student}->[$username_idx];
                   9544:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9545:         my $clickers =
1.408     albertel 9546: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9547:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9548:             $id=~s/^[\#0]+//;
1.421     www      9549:             $id=~s/[\-\:]//g;
1.407     albertel 9550:             if (exists($clicker_ids{$id})) {
1.408     albertel 9551: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9552:             } else {
1.408     albertel 9553: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9554:             }
                   9555:         }
                   9556:     }
1.407     albertel 9557:     return %clicker_ids;
1.400     www      9558: }
                   9559: 
1.402     www      9560: sub gather_adv_clicker_ids {
1.408     albertel 9561:     my %clicker_ids;
1.402     www      9562:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9563:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9564:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9565:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9566:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9567:             my ($puname,$pudom)=split(/\:/,$person);
                   9568:             my $clickers =
1.408     albertel 9569: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9570:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9571: 		$id=~s/^[\#0]+//;
1.421     www      9572:                 $id=~s/[\-\:]//g;
1.408     albertel 9573: 		if (exists($clicker_ids{$id})) {
                   9574: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9575: 		} else {
                   9576: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9577: 		}
1.405     www      9578:             }
1.402     www      9579:         }
                   9580:     }
1.407     albertel 9581:     return %clicker_ids;
1.402     www      9582: }
                   9583: 
1.413     www      9584: sub clicker_grading_parameters {
                   9585:     return ('gradingmechanism' => 'scalar',
                   9586:             'upfiletype' => 'scalar',
                   9587:             'specificid' => 'scalar',
                   9588:             'pcorrect' => 'scalar',
                   9589:             'pincorrect' => 'scalar');
                   9590: }
                   9591: 
1.400     www      9592: sub process_clicker {
1.608     www      9593:     my ($r,$symb)=@_;
1.400     www      9594:     if (!$symb) {return '';}
                   9595:     my $result=&checkforfile_js();
1.632     www      9596:     $result.=&Apache::loncommon::start_data_table().
                   9597:              &Apache::loncommon::start_data_table_header_row().
                   9598:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9599:              &Apache::loncommon::end_data_table_header_row().
                   9600:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9601: # Attempt to restore parameters from last session, set defaults if not present
                   9602:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9603:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9604:                                                  \%Saveable_Parameters);
                   9605:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9606:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9607:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9608:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9609: 
                   9610:     my %checked;
1.521     www      9611:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9612:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9613:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9614:        }
                   9615:     }
                   9616: 
1.632     www      9617:     my $upload=&mt("Evaluate File");
1.400     www      9618:     my $type=&mt("Type");
1.402     www      9619:     my $attendance=&mt("Award points just for participation");
                   9620:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9621:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9622:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9623:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9624:     my $pcorrect=&mt("Percentage points for correct solution");
                   9625:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9626:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9627: 						   {'iclicker' => 'i>clicker',
1.666     www      9628:                                                     'interwrite' => 'interwrite PRS',
                   9629:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9630:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9631:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9632: function sanitycheck() {
                   9633: // Accept only integer percentages
                   9634:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9635:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9636: // Find out grading choice
                   9637:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9638:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9639:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9640:       }
                   9641:    }
                   9642: // By default, new choice equals user selection
                   9643:    newgradingchoice=gradingchoice;
                   9644: // Not good to give more points for false answers than correct ones
                   9645:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9646:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9647:    }
                   9648: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9649:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9650:       document.forms.gradesupload.pcorrect.value=100;
                   9651:       document.forms.gradesupload.pincorrect.value=100;
                   9652:    }
                   9653: // If the values are different, cannot be attendance only
                   9654:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9655:        (gradingchoice=='attendance')) {
                   9656:        newgradingchoice='personnel';
                   9657:    }
                   9658: // Change grading choice to new one
                   9659:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9660:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9661:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9662:       } else {
                   9663:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9664:       }
                   9665:    }
                   9666: // Remember the old state
                   9667:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9668: }
1.597     wenzelju 9669: ENDUPFORM
                   9670:     $result.= <<ENDUPFORM;
1.400     www      9671: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9672: <input type="hidden" name="symb" value="$symb" />
                   9673: <input type="hidden" name="command" value="processclickerfile" />
                   9674: <input type="file" name="upfile" size="50" />
                   9675: <br /><label>$type: $selectform</label>
1.632     www      9676: ENDUPFORM
                   9677:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9678:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9679:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9680: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9681: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9682: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9683: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9684: <br />&nbsp;&nbsp;&nbsp;
                   9685: <input type="text" name="givenanswer" size="50" />
1.413     www      9686: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9687: ENDGRADINGFORM
                   9688:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9689:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9690:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9691: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9692: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9693: </form>'
1.632     www      9694: ENDPERCFORM
                   9695:     $result.='</td>'.
                   9696:              &Apache::loncommon::end_data_table_row().
                   9697:              &Apache::loncommon::end_data_table();
1.400     www      9698:     return $result;
                   9699: }
                   9700: 
                   9701: sub process_clicker_file {
1.608     www      9702:     my ($r,$symb)=@_;
1.400     www      9703:     if (!$symb) {return '';}
1.413     www      9704: 
                   9705:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9706:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9707:                                               \%Saveable_Parameters);
1.598     www      9708:     my $result='';
1.404     www      9709:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9710: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9711: 	return $result;
1.404     www      9712:     }
1.522     www      9713:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9714:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9715:         return $result;
1.521     www      9716:     }
1.522     www      9717:     my $foundgiven=0;
1.521     www      9718:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9719:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9720:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9721:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9722:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9723:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9724:         $foundgiven=$#answers+1;
1.521     www      9725:     }
1.407     albertel 9726:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9727:     my %correct_ids;
1.404     www      9728:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9729: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9730:     }
                   9731:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9732: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9733: 	   $correct_id=~tr/a-z/A-Z/;
                   9734: 	   $correct_id=~s/\s//gs;
                   9735: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9736:            $correct_id=~s/[\-\:]//g;
1.414     www      9737:            if ($correct_id) {
                   9738: 	      $correct_ids{$correct_id}='specified';
                   9739:            }
                   9740:         }
1.400     www      9741:     }
1.404     www      9742:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9743: 	$result.=&mt('Score based on attendance only');
1.521     www      9744:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9745:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9746:     } else {
1.408     albertel 9747: 	my $number=0;
1.411     www      9748: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9749: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9750: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9751: 	    if ($correct_ids{$id} eq 'specified') {
                   9752: 		$result.=&mt('specified');
                   9753: 	    } else {
                   9754: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9755: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9756: 	    }
                   9757: 	    $number++;
                   9758: 	}
1.411     www      9759:         $result.="</p>\n";
1.710     bisitz   9760:         if ($number==0) {
                   9761:             $result .=
                   9762:                  &Apache::lonhtmlcommon::confirm_success(
                   9763:                      &mt('No IDs found to determine correct answer'),1);
                   9764:             return $result;
                   9765:         }
1.404     www      9766:     }
1.405     www      9767:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9768:         $result .=
                   9769:             &Apache::lonhtmlcommon::confirm_success(
                   9770:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9771:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9772:         return $result;
1.405     www      9773:     }
1.410     www      9774: 
                   9775: # Were able to get all the info needed, now analyze the file
                   9776: 
1.411     www      9777:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9778:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9779:     $result.=&Apache::loncommon::start_data_table().
                   9780:              &Apache::loncommon::start_data_table_header_row().
                   9781:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9782:              &Apache::loncommon::end_data_table_header_row().
                   9783:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9784: <td>
1.410     www      9785: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9786: <input type="hidden" name="symb" value="$symb" />
                   9787: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9788: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9789: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9790: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9791: ENDHEADER
1.522     www      9792:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9793:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9794:     } 
1.408     albertel 9795:     my %responses;
                   9796:     my @questiontitles;
1.405     www      9797:     my $errormsg='';
                   9798:     my $number=0;
                   9799:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9800: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9801:     }
1.419     www      9802:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9803:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9804:     }
1.666     www      9805:     if ($env{'form.upfiletype'} eq 'turning') {
                   9806:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9807:     }
1.411     www      9808:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9809:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9810:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9811:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9812:              '<br />';
1.522     www      9813:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9814:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9815:        return $result;
1.522     www      9816:     } 
1.414     www      9817: # Remember Question Titles
                   9818: # FIXME: Possibly need delimiter other than ":"
                   9819:     for (my $i=0;$i<$number;$i++) {
                   9820:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9821:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9822:     }
1.411     www      9823:     my $correct_count=0;
                   9824:     my $student_count=0;
                   9825:     my $unknown_count=0;
1.414     www      9826: # Match answers with usernames
                   9827: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9828:     foreach my $id (keys(%responses)) {
1.410     www      9829:        if ($correct_ids{$id}) {
1.414     www      9830:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9831:           $correct_count++;
1.410     www      9832:        } elsif ($clicker_ids{$id}) {
1.437     www      9833:           if ($clicker_ids{$id}=~/\,/) {
                   9834: # More than one user with the same clicker!
1.632     www      9835:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9836:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9837:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9838:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9839:                            "<select name='multi".$id."'>";
                   9840:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9841:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9842:              }
                   9843:              $result.='</select>';
                   9844:              $unknown_count++;
                   9845:           } else {
                   9846: # Good: found one and only one user with the right clicker
                   9847:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9848:              $student_count++;
                   9849:           }
1.410     www      9850:        } else {
1.632     www      9851:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9852:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9853:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9854:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9855:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9856:                    "\n".&mt("Domain").": ".
                   9857:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9858:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9859:           $unknown_count++;
1.410     www      9860:        }
1.405     www      9861:     }
1.412     www      9862:     $result.='<hr />'.
                   9863:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9864:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9865:        if ($correct_count==0) {
1.696     bisitz   9866:           $errormsg.="Found no correct answers for grading!";
1.412     www      9867:        } elsif ($correct_count>1) {
1.414     www      9868:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9869:        }
                   9870:     }
1.428     www      9871:     if ($number<1) {
                   9872:        $errormsg.="Found no questions.";
                   9873:     }
1.412     www      9874:     if ($errormsg) {
                   9875:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9876:     } else {
                   9877:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9878:     }
1.632     www      9879:     $result.='</form></td>'.
                   9880:              &Apache::loncommon::end_data_table_row().
                   9881:              &Apache::loncommon::end_data_table();
1.614     www      9882:     return $result;
1.400     www      9883: }
                   9884: 
1.405     www      9885: sub iclicker_eval {
1.406     www      9886:     my ($questiontitles,$responses)=@_;
1.405     www      9887:     my $number=0;
                   9888:     my $errormsg='';
                   9889:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9890:         my %components=&Apache::loncommon::record_sep($line);
                   9891:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9892: 	if ($entries[0] eq 'Question') {
                   9893: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9894: 		$$questiontitles[$number]=$entries[$i];
                   9895: 		$number++;
                   9896: 	    }
                   9897: 	}
                   9898: 	if ($entries[0]=~/^\#/) {
                   9899: 	    my $id=$entries[0];
                   9900: 	    my @idresponses;
                   9901: 	    $id=~s/^[\#0]+//;
                   9902: 	    for (my $i=0;$i<$number;$i++) {
                   9903: 		my $idx=3+$i*6;
1.644     www      9904:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9905: 		push(@idresponses,$entries[$idx]);
                   9906: 	    }
                   9907: 	    $$responses{$id}=join(',',@idresponses);
                   9908: 	}
1.405     www      9909:     }
                   9910:     return ($errormsg,$number);
                   9911: }
                   9912: 
1.419     www      9913: sub interwrite_eval {
                   9914:     my ($questiontitles,$responses)=@_;
                   9915:     my $number=0;
                   9916:     my $errormsg='';
1.420     www      9917:     my $skipline=1;
                   9918:     my $questionnumber=0;
                   9919:     my %idresponses=();
1.419     www      9920:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9921:         my %components=&Apache::loncommon::record_sep($line);
                   9922:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9923:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9924:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9925:         next if $skipline;
                   9926:         if ($entries[0]!=$questionnumber) {
                   9927:            $questionnumber=$entries[0];
                   9928:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9929:            $number++;
1.419     www      9930:         }
1.420     www      9931:         my $id=$entries[4];
                   9932:         $id=~s/^[\#0]+//;
1.421     www      9933:         $id=~s/^v\d*\://i;
                   9934:         $id=~s/[\-\:]//g;
1.420     www      9935:         $idresponses{$id}[$number]=$entries[6];
                   9936:     }
1.524     raeburn  9937:     foreach my $id (keys(%idresponses)) {
1.420     www      9938:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9939:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9940:     }
                   9941:     return ($errormsg,$number);
                   9942: }
                   9943: 
1.666     www      9944: sub turning_eval {
                   9945:     my ($questiontitles,$responses)=@_;
                   9946:     my $number=0;
                   9947:     my $errormsg='';
                   9948:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9949:         my %components=&Apache::loncommon::record_sep($line);
                   9950:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9951:         if ($#entries>$number) { $number=$#entries; }
                   9952:         my $id=$entries[0];
                   9953:         my @idresponses;
                   9954:         $id=~s/^[\#0]+//;
                   9955:         unless ($id) { next; }
                   9956:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9957:             $entries[$idx]=~s/\,/\;/g;
                   9958:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9959:             push(@idresponses,$entries[$idx]);
                   9960:         }
                   9961:         $$responses{$id}=join(',',@idresponses);
                   9962:     }
                   9963:     for (my $i=1; $i<=$number; $i++) {
                   9964:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9965:     }
                   9966:     return ($errormsg,$number);
                   9967: }
                   9968: 
                   9969: 
1.414     www      9970: sub assign_clicker_grades {
1.608     www      9971:     my ($r,$symb)=@_;
1.414     www      9972:     if (!$symb) {return '';}
1.416     www      9973: # See which part we are saving to
1.582     raeburn  9974:     my $res_error;
                   9975:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9976:     if ($res_error) {
                   9977:         return &navmap_errormsg();
                   9978:     }
1.416     www      9979: # FIXME: This should probably look for the first handgradeable part
                   9980:     my $part=$$partlist[0];
                   9981: # Start screen output
1.632     www      9982:     my $result=&Apache::loncommon::start_data_table().
                   9983:              &Apache::loncommon::start_data_table_header_row().
                   9984:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9985:              &Apache::loncommon::end_data_table_header_row().
                   9986:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9987: # Get correct result
                   9988: # FIXME: Possibly need delimiter other than ":"
                   9989:     my @correct=();
1.415     www      9990:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9991:     my $number=$env{'form.number'};
                   9992:     if ($gradingmechanism ne 'attendance') {
1.414     www      9993:        foreach my $key (keys(%env)) {
                   9994:           if ($key=~/^form\.correct\:/) {
                   9995:              my @input=split(/\,/,$env{$key});
                   9996:              for (my $i=0;$i<=$#input;$i++) {
                   9997:                  if (($correct[$i]) && ($input[$i]) &&
                   9998:                      ($correct[$i] ne $input[$i])) {
                   9999:                     $result.='<br /><span class="LC_warning">'.
                   10000:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10001:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10002:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10003:                     $correct[$i]=$input[$i];
                   10004:                  }
                   10005:              }
                   10006:           }
                   10007:        }
1.415     www      10008:        for (my $i=0;$i<$number;$i++) {
1.644     www      10009:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10010:              $result.='<br /><span class="LC_error">'.
                   10011:                       &mt('No correct result given for question "[_1]"!',
                   10012:                           $env{'form.question:'.$i}).'</span>';
                   10013:           }
                   10014:        }
1.644     www      10015:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10016:     }
                   10017: # Start grading
1.415     www      10018:     my $pcorrect=$env{'form.pcorrect'};
                   10019:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10020:     my $storecount=0;
1.632     www      10021:     my %users=();
1.415     www      10022:     foreach my $key (keys(%env)) {
1.420     www      10023:        my $user='';
1.415     www      10024:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10025:           $user=$1;
                   10026:        }
                   10027:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10028:           my $id=$1;
                   10029:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10030:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10031:           } elsif ($env{'form.multi'.$id}) {
                   10032:              $user=$env{'form.multi'.$id};
1.420     www      10033:           }
                   10034:        }
1.632     www      10035:        if ($user) {
                   10036:           if ($users{$user}) {
                   10037:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10038:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10039:                       '</span><br />';
                   10040:           }
                   10041:           $users{$user}=1; 
1.415     www      10042:           my @answer=split(/\,/,$env{$key});
                   10043:           my $sum=0;
1.522     www      10044:           my $realnumber=$number;
1.415     www      10045:           for (my $i=0;$i<$number;$i++) {
1.576     www      10046:              if  ($correct[$i] eq '-') {
                   10047:                 $realnumber--;
1.644     www      10048:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10049:                 if ($gradingmechanism eq 'attendance') {
                   10050:                    $sum+=$pcorrect;
1.576     www      10051:                 } elsif ($correct[$i] eq '*') {
1.522     www      10052:                    $sum+=$pcorrect;
1.415     www      10053:                 } else {
1.644     www      10054: # We actually grade if correct or not
                   10055:                    my $increment=$pincorrect;
                   10056: # Special case: numerical answer "0"
                   10057:                    if ($correct[$i] eq '0') {
                   10058:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10059:                          $increment=$pcorrect;
                   10060:                       }
                   10061: # General numerical answer, both evaluate to something non-zero
                   10062:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10063:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10064:                          $increment=$pcorrect;
                   10065:                       }
                   10066: # Must be just alphanumeric
                   10067:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10068:                       $increment=$pcorrect;
1.415     www      10069:                    }
1.644     www      10070:                    $sum+=$increment;
1.415     www      10071:                 }
                   10072:              }
                   10073:           }
1.522     www      10074:           my $ave=$sum/(100*$realnumber);
1.416     www      10075: # Store
                   10076:           my ($username,$domain)=split(/\:/,$user);
                   10077:           my %grades=();
                   10078:           $grades{"resource.$part.solved"}='correct_by_override';
                   10079:           $grades{"resource.$part.awarded"}=$ave;
                   10080:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10081:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10082:                                                  $env{'request.course.id'},
                   10083:                                                  $domain,$username);
                   10084:           if ($returncode ne 'ok') {
                   10085:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10086:           } else {
                   10087:              $storecount++;
                   10088:           }
1.415     www      10089:        }
                   10090:     }
                   10091: # We are done
1.549     hauer    10092:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10093:              '</td>'.
                   10094:              &Apache::loncommon::end_data_table_row().
                   10095:              &Apache::loncommon::end_data_table();
1.614     www      10096:     return $result;
1.414     www      10097: }
                   10098: 
1.582     raeburn  10099: sub navmap_errormsg {
                   10100:     return '<div class="LC_error">'.
                   10101:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10102:            &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  10103:            '</div>';
                   10104: }
1.607     droeschl 10105: 
1.609     www      10106: sub startpage {
1.671     raeburn  10107:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10108:     if ($nomenu) {
                   10109:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10110:     } else {
                   10111:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10112:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10113:                                                  {'bread_crumbs' => $crumbs}));
                   10114:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10115:     }
1.613     www      10116:     unless ($nodisplayflag) {
1.671     raeburn  10117:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10118:     }
1.607     droeschl 10119: }
1.582     raeburn  10120: 
1.622     www      10121: sub select_problem {
                   10122:     my ($r)=@_;
1.632     www      10123:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10124:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10125:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10126:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10127: }
                   10128: 
1.1       albertel 10129: sub handler {
1.41      ng       10130:     my $request=$_[0];
1.434     albertel 10131:     &reset_caches();
1.646     raeburn  10132:     if ($request->header_only) {
                   10133:         &Apache::loncommon::content_type($request,'text/html');
                   10134:         $request->send_http_header;
                   10135:         return OK;
                   10136:     }
                   10137:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10138: 
1.664     raeburn  10139: # see what command we need to execute
                   10140: 
                   10141:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10142:     my $command=$commands[0];
                   10143: 
1.646     raeburn  10144:     &init_perm();
                   10145:     if (!$env{'request.course.id'}) {
1.664     raeburn  10146:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10147:                 ($command =~ /^scantronupload/)) {
                   10148:             # Not in a course.
                   10149:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10150:             return HTTP_NOT_ACCEPTABLE;
                   10151:         }
1.646     raeburn  10152:     } elsif (!%perm) {
                   10153:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10154:         return OK;
1.41      ng       10155:     }
1.646     raeburn  10156:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10157:     $request->send_http_header;
1.646     raeburn  10158: 
1.160     albertel 10159:     if ($#commands > 0) {
                   10160: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10161:     }
1.608     www      10162: 
                   10163: # see what the symb is
                   10164: 
                   10165:     my $symb=$env{'form.symb'};
                   10166:     unless ($symb) {
                   10167:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10168:        $symb=&Apache::lonnet::symbread($url);
                   10169:     }
1.646     raeburn  10170:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10171: 
1.513     foxr     10172:     $ssi_error = 0;
1.637     www      10173:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10174: #
1.637     www      10175: # Not called from a resource, but inside a course
1.601     www      10176: #    
1.622     www      10177:         &startpage($request,undef,[],1,1);
                   10178:         &select_problem($request);
1.41      ng       10179:     } else {
1.104     albertel 10180: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10181:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10182:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10183:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10184:                     &choose_task_version_form($symb,$env{'form.student'},
                   10185:                                               $env{'form.userdom'});
                   10186:             }
                   10187:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10188:             if ($versionform) {
                   10189:                 $request->print($versionform);
                   10190:             }
                   10191:             $request->print('<br clear="all" />');
1.611     www      10192: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10193:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10194:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10195:                 &choose_task_version_form($symb,$env{'form.student'},
                   10196:                                           $env{'form.userdom'},
                   10197:                                           $env{'form.inhibitmenu'});
                   10198:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10199:             if ($versionform) {
                   10200:                 $request->print($versionform);
                   10201:             }
                   10202:             $request->print('<br clear="all" />');
                   10203:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10204: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10205:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10206:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10207: 	    &pickStudentPage($request,$symb);
1.103     albertel 10208: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10209:             &startpage($request,$symb,
                   10210:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10211:                                        {href=>'',text=>'Select student'},
                   10212:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10213: 	    &displayPage($request,$symb);
1.104     albertel 10214: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10215:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10216:                                        {href=>'',text=>'Select student'},
                   10217:                                        {href=>'',text=>'Grade student'},
                   10218:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10219: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10220: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10221:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10222:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10223: 	    &processGroup($request,$symb);
1.104     albertel 10224: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10225:             &startpage($request,$symb);
                   10226: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10227: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10228:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10229: 	    $request->print(&submit_options($request,$symb));
1.598     www      10230:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10231:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10232:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10233:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10234:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10235:             $request->print(&submit_options_table($request,$symb));
1.598     www      10236:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10237:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10238:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10239: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10240:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10241: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10242: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10243:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10244:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10245: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10246: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10247:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10248:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10249:                                                                              text=>"Modify grades"},
                   10250:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10251: 	    $request->print(&editgrades($request,$symb));
1.602     www      10252:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10253:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10254:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10255: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10256:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10257:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10258: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10259:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10260:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10261:             $request->print(&process_clicker($request,$symb));
1.400     www      10262:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10263:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10264:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10265:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10266:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10267:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10268:                                        {href=>'', text=>'Process clicker file'},
                   10269:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10270:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10271: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10272:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10273: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10274: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10275:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10276: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10277: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10278:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10279: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10280: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10281: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10282:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10283: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10284: 	    } else {
1.257     albertel 10285: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10286: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10287: 		} else {
1.257     albertel 10288: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10289: 		}
1.627     www      10290:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10291: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10292: 	    }
1.246     albertel 10293: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10294:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10295: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10296: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10297:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10298: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10299:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10300:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10301:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10302: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10303:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10304: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10305: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10306:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10307: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10308:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10309:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10310: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10311:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10312:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10313:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10314:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10315: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10317:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10318:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10319: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10320:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10321:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10322:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10323:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10324:             $request->print(&checkscantron_results($request,$symb));
                   10325:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10326:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10327:             $request->print(&submit_options_download($request,$symb));
                   10328:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10329:             &startpage($request,$symb,
                   10330:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10331:     {href=>'', text=>'Download submissions'}]);
                   10332:             &submit_download_link($request,$symb);
1.106     albertel 10333: 	} elsif ($command) {
1.620     www      10334:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10335: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10336: 	}
1.2       albertel 10337:     }
1.513     foxr     10338:     if ($ssi_error) {
                   10339: 	&ssi_print_error($request);
                   10340:     }
1.671     raeburn  10341:     if ($env{'form.inhibitmenu'}) {
                   10342:         $request->print(&Apache::loncommon::end_page());
                   10343:     } else {
                   10344:         &Apache::lonquickgrades::endGradeScreen($request);
                   10345:     }
1.434     albertel 10346:     &reset_caches();
1.646     raeburn  10347:     return OK;
1.44      ng       10348: }
                   10349: 
1.1       albertel 10350: 1;
                   10351: 
1.13      albertel 10352: __END__;
1.531     jms      10353: 
                   10354: 
                   10355: =head1 NAME
                   10356: 
                   10357: Apache::grades
                   10358: 
                   10359: =head1 SYNOPSIS
                   10360: 
                   10361: Handles the viewing of grades.
                   10362: 
                   10363: This is part of the LearningOnline Network with CAPA project
                   10364: described at http://www.lon-capa.org.
                   10365: 
                   10366: =head1 OVERVIEW
                   10367: 
                   10368: Do an ssi with retries:
1.715     bisitz   10369: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10370: 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
                   10371: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10372: 
                   10373: At least the logic that drives this has been pulled out into loncommon.
                   10374: 
                   10375: 
                   10376: 
                   10377: ssi_with_retries - Does the server side include of a resource.
                   10378:                      if the ssi call returns an error we'll retry it up to
                   10379:                      the number of times requested by the caller.
1.715     bisitz   10380:                      If we still have a problem, no text is appended to the
1.531     jms      10381:                      output and we set some global variables.
                   10382:                      to indicate to the caller an SSI error occurred.  
                   10383:                      All of this is supposed to deal with the issues described
1.715     bisitz   10384:                      in LON-CAPA BZ 5631 see:
1.531     jms      10385:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10386:                      by informing the user that this happened.
                   10387: 
                   10388: Parameters:
                   10389:   resource   - The resource to include.  This is passed directly, without
                   10390:                interpretation to lonnet::ssi.
                   10391:   form       - The form hash parameters that guide the interpretation of the resource
                   10392:                
                   10393:   retries    - Number of retries allowed before giving up completely.
                   10394: Returns:
                   10395:   On success, returns the rendered resource identified by the resource parameter.
                   10396: Side Effects:
                   10397:   The following global variables can be set:
                   10398:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10399:                               It is up to the caller to initialize this to false
                   10400:                               if desired.
                   10401:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10402:                               of the resource that could not be rendered by the ssi
                   10403:                               call.
                   10404:    ssi_error_message   - The error string fetched from the ssi response
                   10405:                               in the event of an error.
                   10406: 
                   10407: 
                   10408: =head1 HANDLER SUBROUTINE
                   10409: 
                   10410: ssi_with_retries()
                   10411: 
                   10412: =head1 SUBROUTINES
                   10413: 
                   10414: =over
                   10415: 
1.671     raeburn  10416: =head1 Routines to display previous version of a Task for a specific student
                   10417: 
                   10418: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10419: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10420: requires a proctor to check-in the student, a new version of the Task will
                   10421: be created when the student is checked in to the new opportunity.
                   10422: 
                   10423: If a particular student has tried two or more versions of a particular task,
                   10424: the submission screen provides a user with vgr privileges (e.g., a Course
                   10425: Coordinator) the ability to display a previous version worked on by the
                   10426: student.  By default, the current version is displayed. If a previous version
                   10427: has been selected for display, submission data are only shown that pertain
                   10428: to that particular version, and the interface to submit grades is not shown.
                   10429: 
                   10430: =over 4
                   10431: 
                   10432: =item show_previous_task_version()
                   10433: 
                   10434: Displays a specified version of a student's Task, as the student sees it.
                   10435: 
                   10436: Inputs: 2
                   10437:         request - request object
                   10438:         symb    - unique symb for current instance of resource
                   10439: 
                   10440: Output: None.
                   10441: 
                   10442: Side Effects: calls &show_problem() to print version of Task, with
                   10443:               version contained in form item: $env{'form.previousversion'}
                   10444: 
                   10445: =item choose_task_version_form()
                   10446: 
                   10447: Displays a web form used to select which version of a student's view of a
                   10448: Task should be displayed.  Either launches a pop-up window, or replaces
                   10449: content in existing pop-up, or replaces page in main window.
                   10450: 
                   10451: Inputs: 4
                   10452:         symb    - unique symb for current instance of resource
                   10453:         uname   - username of student
                   10454:         udom    - domain of student
                   10455:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10456:                   breadcrumbs etc., are displayed
                   10457: 
                   10458: Output: 4
                   10459:         current   - student's current version
                   10460:         displayed - student's version being displayed
                   10461:         result    - scalar containing HTML for web form used to switch to
                   10462:                     a different version (or a link to close window, if pop-up).
                   10463:         js        - javascript for processing selection in versions web form
                   10464: 
                   10465: Side Effects: None.
                   10466: 
                   10467: =item previous_display_javascript()
                   10468: 
                   10469: Inputs: 2
                   10470:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10471:                   breadcrumbs etc., are displayed.
                   10472:         current - student's current version number.
                   10473: 
                   10474: Output: 1
                   10475:         js      - javascript for processing selection in versions web form.
                   10476: 
                   10477: Side Effects: None.
                   10478: 
                   10479: =back
                   10480: 
                   10481: =head1 Routines to process bubblesheet data.
                   10482: 
                   10483: =over 4
                   10484: 
1.531     jms      10485: =item scantron_get_correction() : 
                   10486: 
                   10487:    Builds the interface screen to interact with the operator to fix a
                   10488:    specific error condition in a specific scanline
                   10489: 
                   10490:  Arguments:
                   10491:     $r           - Apache request object
                   10492:     $i           - number of the current scanline
                   10493:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10494:     $scan_config - hash ref as returned from &get_scantron_config()
                   10495:     $line        - full contents of the current scanline
                   10496:     $error       - error condition, valid values are
                   10497:                    'incorrectCODE', 'duplicateCODE',
                   10498:                    'doublebubble', 'missingbubble',
                   10499:                    'duplicateID', 'incorrectID'
                   10500:     $arg         - extra information needed
                   10501:        For errors:
                   10502:          - duplicateID   - paper number that this studentID was seen before on
                   10503:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10504:                            seen on before
                   10505:          - incorrectCODE - current incorrect CODE 
                   10506:          - doublebubble  - array ref of the bubble lines that have double
                   10507:                            bubble errors
                   10508:          - missingbubble - array ref of the bubble lines that have missing
                   10509:                            bubble errors
                   10510: 
1.691     raeburn  10511:    $randomorder - True if exam folder has randomorder set
                   10512:    $randompick  - True if exam folder has randompick set
                   10513:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10514:                      for current line to question number used for same question
                   10515:                      in "Master Seqence" (as seen by Course Coordinator).
                   10516:    $startline   - Reference to hash where key is question number (0 is first)
                   10517:                   and value is number of first bubble line for current student
                   10518:                   or code-based randompick and/or randomorder.
                   10519: 
                   10520: 
                   10521: 
1.531     jms      10522: =item  scantron_get_maxbubble() : 
                   10523: 
1.582     raeburn  10524:    Arguments:
                   10525:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10526:                       failure to retrieve a navmap object.
                   10527:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10528:        calling routine should trap the error condition and display the warning
                   10529:        found in &navmap_errormsg().
                   10530: 
1.649     raeburn  10531:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10532: 
1.531     jms      10533:    Returns the maximum number of bubble lines that are expected to
                   10534:    occur. Does this by walking the selected sequence rendering the
                   10535:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10536:    for what the current value of the problem counter is.
                   10537: 
                   10538:    Caches the results to $env{'form.scantron_maxbubble'},
                   10539:    $env{'form.scantron.bubble_lines.n'}, 
                   10540:    $env{'form.scantron.first_bubble_line.n'} and
                   10541:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10542:    which are the total number of bubble lines, the number of bubble
1.531     jms      10543:    lines for response n and number of the first bubble line for response n,
                   10544:    and a comma separated list of numbers of bubble lines for sub-questions
                   10545:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10546: 
                   10547: 
                   10548: =item  scantron_validate_missingbubbles() : 
                   10549: 
                   10550:    Validates all scanlines in the selected file to not have any
                   10551:     answers that don't have bubbles that have not been verified
                   10552:     to be bubble free.
                   10553: 
                   10554: =item  scantron_process_students() : 
                   10555: 
1.659     raeburn  10556:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10557: 
                   10558:    The parsed scanline hash is added to %env 
                   10559: 
                   10560:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10561:    foreach resource , with the form data of
                   10562: 
                   10563: 	'submitted'     =>'scantron' 
                   10564: 	'grade_target'  =>'grade',
                   10565: 	'grade_username'=> username of student
                   10566: 	'grade_domain'  => domain of student
                   10567: 	'grade_courseid'=> of course
                   10568: 	'grade_symb'    => symb of resource to grade
                   10569: 
                   10570:     This triggers a grading pass. The problem grading code takes care
                   10571:     of converting the bubbled letter information (now in %env) into a
                   10572:     valid submission.
                   10573: 
                   10574: =item  scantron_upload_scantron_data() :
                   10575: 
1.659     raeburn  10576:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10577: 
                   10578: =item  scantron_upload_scantron_data_save() : 
                   10579: 
                   10580:    Adds a provided bubble information data file to the course if user
                   10581:    has the correct privileges to do so. 
                   10582: 
                   10583: =item  valid_file() :
                   10584: 
                   10585:    Validates that the requested bubble data file exists in the course.
                   10586: 
                   10587: =item  scantron_download_scantron_data() : 
                   10588: 
                   10589:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10590:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10591:    course.
                   10592: 
                   10593: =item  scantron_validate_ID() : 
                   10594: 
                   10595:    Validates all scanlines in the selected file to not have any
1.556     weissno  10596:    invalid or underspecified student/employee IDs
1.531     jms      10597: 
1.582     raeburn  10598: =item navmap_errormsg() :
                   10599: 
                   10600:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10601:    Should be called whenever the request to instantiate a navmap object fails.
                   10602: 
                   10603: =back
1.582     raeburn  10604: 
1.531     jms      10605: =back
                   10606: 
                   10607: =cut

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