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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.697   ! bisitz      4: # $Id: grades.pm,v 1.696 2013/07/19 18:24: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.440     albertel  440:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    441: 	$answer = 
                    442: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    443: 							      $answer);
1.122     ng        444:     }
1.118     ng        445:     return $answer;
                    446: }
                    447: 
                    448: #-- A couple of common js functions
                    449: sub commonJSfunctions {
                    450:     my $request = shift;
1.597     wenzelju  451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        452:     function radioSelection(radioButton) {
                    453: 	var selection=null;
                    454: 	if (radioButton.length > 1) {
                    455: 	    for (var i=0; i<radioButton.length; i++) {
                    456: 		if (radioButton[i].checked) {
                    457: 		    return radioButton[i].value;
                    458: 		}
                    459: 	    }
                    460: 	} else {
                    461: 	    if (radioButton.checked) return radioButton.value;
                    462: 	}
                    463: 	return selection;
                    464:     }
                    465: 
                    466:     function pullDownSelection(selectOne) {
                    467: 	var selection="";
                    468: 	if (selectOne.length > 1) {
                    469: 	    for (var i=0; i<selectOne.length; i++) {
                    470: 		if (selectOne[i].selected) {
                    471: 		    return selectOne[i].value;
                    472: 		}
                    473: 	    }
                    474: 	} else {
1.138     albertel  475:             // only one value it must be the selected one
                    476: 	    return selectOne.value;
1.118     ng        477: 	}
                    478:     }
                    479: COMMONJSFUNCTIONS
                    480: }
                    481: 
1.44      ng        482: #--- Dumps the class list with usernames,list of sections,
                    483: #--- section, ids and fullnames for each user.
                    484: sub getclasslist {
1.449     banghart  485:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  486:     my @getsec;
1.450     banghart  487:     my @getgroup;
1.442     banghart  488:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  489:     if (!ref($getsec)) {
                    490: 	if ($getsec ne '' && $getsec ne 'all') {
                    491: 	    @getsec=($getsec);
                    492: 	}
                    493:     } else {
                    494: 	@getsec=@{$getsec};
                    495:     }
                    496:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  497:     if (!ref($getgroup)) {
                    498: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    499: 	    @getgroup=($getgroup);
                    500: 	}
                    501:     } else {
                    502: 	@getgroup=@{$getgroup};
                    503:     }
                    504:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  505: 
1.449     banghart  506:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  507:     # Bail out if we were unable to get the classlist
1.56      matthew   508:     return if (! defined($classlist));
1.449     banghart  509:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   510:     #
                    511:     my %sections;
                    512:     my %fullnames;
1.205     matthew   513:     foreach my $student (keys(%$classlist)) {
                    514:         my $end      = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    516:         my $start    = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    518:         my $id       = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    520:         my $section  = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    522:         my $fullname = 
                    523:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    524:         my $status   = 
                    525:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  526:         my $group   = 
                    527:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        528: 	# filter students according to status selected
1.442     banghart  529: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    530: 	    if (!($stu_status =~ $status)) {
1.450     banghart  531: 		delete($classlist->{$student});
1.76      ng        532: 		next;
                    533: 	    }
                    534: 	}
1.450     banghart  535: 	# filter students according to groups selected
1.453     banghart  536: 	my @stu_groups = split(/,/,$group);
1.450     banghart  537: 	if (@getgroup) {
                    538: 	    my $exclude = 1;
1.454     banghart  539: 	    foreach my $grp (@getgroup) {
                    540: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  541: 	            if ($stu_group eq $grp) {
                    542: 	                $exclude = 0;
                    543:     	            } 
1.450     banghart  544: 	        }
1.453     banghart  545:     	        if (($grp eq 'none') && !$group) {
                    546:         	        $exclude = 0;
                    547:         	}
1.450     banghart  548: 	    }
                    549: 	    if ($exclude) {
                    550: 	        delete($classlist->{$student});
                    551: 	    }
                    552: 	}
1.205     matthew   553: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  554: 	if (&canview($section)) {
1.291     albertel  555: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  556: 		$sections{$section}++;
1.450     banghart  557: 		if ($classlist->{$student}) {
                    558: 		    $fullnames{$student}=$fullname;
                    559: 		}
1.103     albertel  560: 	    } else {
1.205     matthew   561: 		delete($classlist->{$student});
1.103     albertel  562: 	    }
                    563: 	} else {
1.205     matthew   564: 	    delete($classlist->{$student});
1.103     albertel  565: 	}
1.44      ng        566:     }
                    567:     my %seen = ();
1.56      matthew   568:     my @sections = sort(keys(%sections));
                    569:     return ($classlist,\@sections,\%fullnames);
1.44      ng        570: }
                    571: 
1.103     albertel  572: sub canmodify {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'mgr'}) {
                    575: 	if (!defined($perm{'mgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'mgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
                    592: sub canview {
                    593:     my ($sec)=@_;
                    594:     if ($perm{'vgr'}) {
                    595: 	if (!defined($perm{'vgr_section'})) {
                    596: 	    # can modify whole class
                    597: 	    return 1;
                    598: 	} else {
                    599: 	    if ($sec eq $perm{'vgr_section'}) {
                    600: 		#can modify the requested section
                    601: 		return 1;
                    602: 	    } else {
                    603: 		# can't modify the request section
                    604: 		return 0;
                    605: 	    }
                    606: 	}
                    607:     }
                    608:     #can't modify
                    609:     return 0;
                    610: }
                    611: 
1.44      ng        612: #--- Retrieve the grade status of a student for all the parts
                    613: sub student_gradeStatus {
1.324     albertel  614:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  615:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        616:     my %partstatus = ();
                    617:     foreach (@$partlist) {
1.128     ng        618: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        619: 	$status              = 'nothing' if ($status eq '');
                    620: 	$partstatus{$_}      = $status;
                    621: 	my $subkey           = "resource.$_.submitted_by";
                    622: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    623:     }
                    624:     return %partstatus;
                    625: }
                    626: 
1.45      ng        627: # hidden form and javascript that calls the form
                    628: # Use by verifyscript and viewgrades
                    629: # Shows a student's view of problem and submission
                    630: sub jscriptNform {
1.324     albertel  631:     my ($symb) = @_;
1.442     banghart  632:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  633:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        634: 	'    function viewOneStudent(user,domain) {'."\n".
                    635: 	'	document.onestudent.student.value = user;'."\n".
                    636: 	'	document.onestudent.userdom.value = domain;'."\n".
                    637: 	'	document.onestudent.submit();'."\n".
                    638: 	'    }'."\n".
1.597     wenzelju  639: 	"\n");
1.45      ng        640:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  641: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        643: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    644: 	'<input type="hidden" name="student" value="" />'."\n".
                    645: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    646: 	'</form>'."\n";
                    647:     return $jscript;
                    648: }
1.39      ng        649: 
1.447     foxr      650: 
                    651: 
1.315     bowersj2  652: # Given the score (as a number [0-1] and the weight) what is the final
                    653: # point value? This function will round to the nearest tenth, third,
                    654: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  655: sub compute_points {
1.315     bowersj2  656:     my ($score, $weight) = @_;
                    657:     
                    658:     my $tolerance = .00001;
                    659:     my $points = $score * $weight;
                    660: 
                    661:     # Check for nearness to 1/x.
                    662:     my $check_for_nearness = sub {
                    663:         my ($factor) = @_;
                    664:         my $num = ($points * $factor) + $tolerance;
                    665:         my $floored_num = floor($num);
1.316     albertel  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  667:             return $floored_num / $factor;
                    668:         }
                    669:         return $points;
                    670:     };
                    671: 
                    672:     $points = $check_for_nearness->(10);
                    673:     $points = $check_for_nearness->(3);
                    674:     $points = $check_for_nearness->(4);
                    675:     
                    676:     return $points;
                    677: }
                    678: 
1.44      ng        679: #------------------ End of general use routines --------------------
1.87      www       680: 
                    681: #
                    682: # Find most similar essay
                    683: #
                    684: 
                    685: sub most_similar {
1.674     raeburn   686:     my ($uname,$udom,$symb,$uessay)=@_;
                    687: 
                    688:     unless ($symb) { return ''; }
                    689: 
                    690:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       691: 
                    692: # ignore spaces and punctuation
                    693: 
                    694:     $uessay=~s/\W+/ /gs;
                    695: 
1.282     www       696: # ignore empty submissions (occuring when only files are sent)
                    697: 
1.598     www       698:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       699: 
1.87      www       700: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       701:     my $limit=0.6;
1.87      www       702:     my $sname='';
                    703:     my $sdom='';
                    704:     my $scrsid='';
                    705:     my $sessay='';
                    706: # go through all essays ...
1.674     raeburn   707:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  708: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       709: # ... except the same student
1.426     albertel  710:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   711: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  712: 	$tessay=~s/\W+/ /gs;
1.87      www       713: # String similarity gives up if not even limit
1.426     albertel  714: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       715: # Found one
1.426     albertel  716: 	if ($tsimilar>$limit) {
                    717: 	    $limit=$tsimilar;
                    718: 	    $sname=$tname;
                    719: 	    $sdom=$tdom;
                    720: 	    $scrsid=$tcrsid;
1.674     raeburn   721: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  722: 	}
1.87      www       723:     }
1.88      www       724:     if ($limit>0.6) {
1.87      www       725:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    726:     } else {
                    727:        return ('','','','',0);
                    728:     }
                    729: }
                    730: 
1.44      ng        731: #-------------------------------------------------------------------
                    732: 
                    733: #------------------------------------ Receipt Verification Routines
1.45      ng        734: #
1.602     www       735: 
                    736: sub initialverifyreceipt {
1.608     www       737:    my ($request,$symb) = @_;
1.602     www       738:    &commonJSfunctions($request);
1.694     bisitz    739:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       740:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    741:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       742:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    743:         '<input type="hidden" name="command" value="verify" />'.
                    744:         "</form>\n";
1.602     www       745: }
                    746: 
1.44      ng        747: #--- Check whether a receipt number is valid.---
                    748: sub verifyreceipt {
1.608     www       749:     my ($request,$symb)  = @_;
1.44      ng        750: 
1.257     albertel  751:     my $courseid = $env{'request.course.id'};
1.184     www       752:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  753: 	$env{'form.receipt'};
1.44      ng        754:     $receipt     =~ s/[^\-\d]//g;
                    755: 
1.487     albertel  756:     my $title.=
                    757: 	'<h3><span class="LC_info">'.
1.605     www       758: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    759: 	'</span></h3>'."\n";
1.44      ng        760: 
                    761:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   762:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  763:     
                    764:     my $receiptparts=0;
1.390     albertel  765:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    766: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  767:     my $parts=['0'];
1.582     raeburn   768:     if ($receiptparts) {
                    769:         my $res_error; 
                    770:         ($parts)=&response_type($symb,\$res_error);
                    771:         if ($res_error) {
                    772:             return &navmap_errormsg();
                    773:         } 
                    774:     }
1.486     albertel  775:     
                    776:     my $header = 
                    777: 	&Apache::loncommon::start_data_table().
                    778: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  779: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    780: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    781: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  782:     if ($receiptparts) {
1.487     albertel  783: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  784:     }
                    785:     $header.=
                    786: 	&Apache::loncommon::end_data_table_header_row();
                    787: 
1.294     albertel  788:     foreach (sort 
                    789: 	     {
                    790: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    791: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    792: 		 }
                    793: 		 return $a cmp $b;
                    794: 	     } (keys(%$fullname))) {
1.44      ng        795: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  796: 	foreach my $part (@$parts) {
                    797: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  798: 		$contents.=
                    799: 		    &Apache::loncommon::start_data_table_row().
                    800: 		    '<td>&nbsp;'."\n".
1.177     albertel  801: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  802: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  803: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    804: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    805: 		if ($receiptparts) {
                    806: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    807: 		}
1.486     albertel  808: 		$contents.= 
                    809: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  810: 		
                    811: 		$matches++;
                    812: 	    }
1.44      ng        813: 	}
                    814:     }
                    815:     if ($matches == 0) {
1.584     bisitz    816:         $string = $title
                    817:                  .'<p class="LC_warning">'
                    818:                  .&mt('No match found for the above receipt number.')
                    819:                  .'</p>';
1.44      ng        820:     } else {
1.324     albertel  821: 	$string = &jscriptNform($symb).$title.
1.487     albertel  822: 	    '<p>'.
1.584     bisitz    823: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  824: 	    '</p>'.
1.486     albertel  825: 	    $header.
                    826: 	    $contents.
                    827: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        828:     }
1.614     www       829:     return $string;
1.44      ng        830: }
                    831: 
                    832: #--- This is called by a number of programs.
                    833: #--- Called from the Grading Menu - View/Grade an individual student
                    834: #--- Also called directly when one clicks on the subm button 
                    835: #    on the problem page.
1.30      ng        836: sub listStudents {
1.617     www       837:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  838: 
1.257     albertel  839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  842:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       843:     unless ($submitonly) {
                    844:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    845:     }
1.49      albertel  846: 
1.632     www       847:     my $result='';
1.623     www       848:     my $res_error;
                    849:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  850: 
1.559     raeburn   851:     my %lt = &Apache::lonlocal::texthash (
                    852: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    853: 		'single'   => 'Please select the student before clicking on the Next button.',
                    854: 	     );
1.597     wenzelju  855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        856:     function checkSelect(checkBox) {
                    857: 	var ctr=0;
                    858: 	var sense="";
                    859: 	if (checkBox.length > 1) {
                    860: 	    for (var i=0; i<checkBox.length; i++) {
                    861: 		if (checkBox[i].checked) {
                    862: 		    ctr++;
                    863: 		}
                    864: 	    }
1.485     albertel  865: 	    sense = '$lt{'multiple'}';
1.110     ng        866: 	} else {
                    867: 	    if (checkBox.checked) {
                    868: 		ctr = 1;
                    869: 	    }
1.485     albertel  870: 	    sense = '$lt{'single'}';
1.110     ng        871: 	}
                    872: 	if (ctr == 0) {
1.485     albertel  873: 	    alert(sense);
1.110     ng        874: 	    return false;
                    875: 	}
                    876: 	document.gradesub.submit();
                    877:     }
                    878: 
                    879:     function reLoadList(formname) {
1.112     ng        880: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        881: 	formname.command.value = 'submission';
                    882: 	formname.submit();
                    883:     }
1.45      ng        884: LISTJAVASCRIPT
                    885: 
1.118     ng        886:     &commonJSfunctions($request);
1.41      ng        887:     $request->print($result);
1.39      ng        888: 
1.154     albertel  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       890: 	"\n";
1.485     albertel  891: 	
1.561     bisitz    892:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    893:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    894:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    895:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    897:                   .&Apache::lonhtmlcommon::row_closure();
                    898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    899:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    900:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    902:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  903: 
                    904:     my $submission_options;
1.442     banghart  905:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    906:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  907:     $env{'form.Status'} = $saveStatus;
1.485     albertel  908:     $submission_options.=
1.592     bisitz    909:         '<span class="LC_nobreak">'.
1.624     www       910:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    911:         &mt('last submission only').' </label></span>'."\n".
                    912:         '<span class="LC_nobreak">'.
                    913:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    914:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    915:         '<span class="LC_nobreak">'.
1.628     www       916:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    917:         &mt('by dates and submissions').'</label></span>'."\n".
                    918:         '<span class="LC_nobreak">'.
                    919:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    920:         &mt('all details').'</label></span>';
1.561     bisitz    921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    922:                   .$submission_options
                    923:                   .&Apache::lonhtmlcommon::row_closure();
                    924: 
                    925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    926:                   .'<select name="increment">'
                    927:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    928:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    929:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    930:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    931:                   .'</select>'
                    932:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  933: 
                    934:     $gradeTable .= 
1.432     banghart  935:         &build_section_inputs().
1.45      ng        936: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    939: 
1.618     www       940:     if (exists($env{'form.Status'})) {
1.561     bisitz    941: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        942:     } else {
1.561     bisitz    943:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    944:                       .&Apache::lonhtmlcommon::StatusOptions(
                    945:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    946:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        947:     }
1.112     ng        948: 
1.561     bisitz    949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    950:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    951:                   .&Apache::lonhtmlcommon::row_closure(1)
                    952:                   .&Apache::lonhtmlcommon::end_pick_box();
                    953: 
                    954:     $gradeTable .= '<p>'
1.618     www       955:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz    956:                   .'<input type="hidden" name="command" value="processGroup" />'
                    957:                   .'</p>';
1.249     albertel  958: 
                    959: # checkall buttons
                    960:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        961:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    962:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    963:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  964:     $gradeTable.=&check_buttons();
1.450     banghart  965:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  966:     $gradeTable.= &Apache::loncommon::start_data_table().
                    967: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        968:     my $loop = 0;
                    969:     while ($loop < 2) {
1.485     albertel  970: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    971: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       972: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  973: 	    foreach my $part (sort(@$partlist)) {
                    974: 		my $display_part=
                    975: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    976: 		$gradeTable.=
                    977: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        978: 	    }
1.301     albertel  979: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  980: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        981: 	}
                    982: 	$loop++;
1.126     ng        983: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        984:     }
1.474     albertel  985:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        986: 
1.45      ng        987:     my $ctr = 0;
1.294     albertel  988:     foreach my $student (sort 
                    989: 			 {
                    990: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    991: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    992: 			     }
                    993: 			     return $a cmp $b;
                    994: 			 }
                    995: 			 (keys(%$fullname))) {
1.41      ng        996: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  997: 
1.110     ng        998: 	my %status = ();
1.301     albertel  999: 
                   1000: 	if ($submitonly eq 'queued') {
                   1001: 	    my %queue_status = 
                   1002: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1003: 							$udom,$uname);
                   1004: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1005: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1006: 	}
                   1007: 
1.618     www      1008: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1009: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1010: 	    my $submitted = 0;
1.164     albertel 1011: 	    my $graded = 0;
1.248     albertel 1012: 	    my $incorrect = 0;
1.110     ng       1013: 	    foreach (keys(%status)) {
1.145     albertel 1014: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1015: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1016: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1017: 		
1.110     ng       1018: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1019: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1020: 		    $submitted = 0;
1.150     albertel 1021: 		    my ($part)=split(/\./,$partid);
1.110     ng       1022: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1023: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1024: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1025: 		}
1.41      ng       1026: 	    }
1.248     albertel 1027: 	    
1.156     albertel 1028: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1029: 				     $submitonly eq 'incorrect' ||
                   1030: 				     $submitonly eq 'graded'));
1.248     albertel 1031: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1032: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1033: 	}
1.34      ng       1034: 
1.45      ng       1035: 	$ctr++;
1.249     albertel 1036: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1037:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1038: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1039: 	    if ($ctr%2 ==1) {
                   1040: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1041: 	    }
1.126     ng       1042: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1043:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1044:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1045: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1046: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1047: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1048: 
1.618     www      1049: 	    if ($submitonly ne 'all') {
1.524     raeburn  1050: 		foreach (sort(keys(%status))) {
1.485     albertel 1051: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1052: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1053: 		}
1.41      ng       1054: 	    }
1.126     ng       1055: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1056: 	    if ($ctr%2 ==0) {
                   1057: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1058: 	    }
1.41      ng       1059: 	}
                   1060:     }
1.110     ng       1061:     if ($ctr%2 ==1) {
1.126     ng       1062: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1063: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1064: 		foreach (@$partlist) {
                   1065: 		    $gradeTable.='<td>&nbsp;</td>';
                   1066: 		}
1.301     albertel 1067: 	    } elsif ($submitonly eq 'queued') {
                   1068: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1069: 	    }
1.474     albertel 1070: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1071:     }
                   1072: 
1.474     albertel 1073:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1074:         '<input type="button" '.
                   1075:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1076:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1077:     if ($ctr == 0) {
1.96      albertel 1078: 	my $num_students=(scalar(keys(%$fullname)));
                   1079: 	if ($num_students eq 0) {
1.485     albertel 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1081: 	} else {
1.171     albertel 1082: 	    my $submissions='submissions';
                   1083: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1084: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1085: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1086: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1087: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1088: 		    $num_students).
                   1089: 		'</span><br />';
1.96      albertel 1090: 	}
1.46      ng       1091:     } elsif ($ctr == 1) {
1.474     albertel 1092: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1093:     }
                   1094:     $request->print($gradeTable);
1.44      ng       1095:     return '';
1.10      ng       1096: }
                   1097: 
1.44      ng       1098: #---- Called from the listStudents routine
1.249     albertel 1099: 
                   1100: sub check_script {
                   1101:     my ($form, $type)=@_;
1.597     wenzelju 1102:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1103:     function checkall() {
                   1104:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1105:             ele = document.forms.'.$form.'.elements[i];
                   1106:             if (ele.name == "'.$type.'") {
                   1107:             document.forms.'.$form.'.elements[i].checked=true;
                   1108:                                        }
                   1109:         }
                   1110:     }
                   1111: 
                   1112:     function checksec() {
                   1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1114:             ele = document.forms.'.$form.'.elements[i];
                   1115:            string = document.forms.'.$form.'.chksec.value;
                   1116:            if
                   1117:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1118:               document.forms.'.$form.'.elements[i].checked=true;
                   1119:             }
                   1120:         }
                   1121:     }
                   1122: 
                   1123: 
                   1124:     function uncheckall() {
                   1125:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1126:             ele = document.forms.'.$form.'.elements[i];
                   1127:             if (ele.name == "'.$type.'") {
                   1128:             document.forms.'.$form.'.elements[i].checked=false;
                   1129:                                        }
                   1130:         }
                   1131:     }
                   1132: 
1.597     wenzelju 1133: '."\n");
1.249     albertel 1134:     return $chkallscript;
                   1135: }
                   1136: 
                   1137: sub check_buttons {
1.485     albertel 1138:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1139:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1140:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1141:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1142:     return $buttons;
                   1143: }
                   1144: 
1.44      ng       1145: #     Displays the submissions for one student or a group of students
1.34      ng       1146: sub processGroup {
1.619     www      1147:     my ($request,$symb)  = @_;
1.41      ng       1148:     my $ctr        = 0;
1.155     albertel 1149:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1150:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1151: 
1.396     banghart 1152:     foreach my $student (@stuchecked) {
                   1153: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1154: 	$env{'form.student'}        = $uname;
                   1155: 	$env{'form.userdom'}        = $udom;
                   1156: 	$env{'form.fullname'}       = $fullname;
1.619     www      1157: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1158: 	$ctr++;
                   1159:     }
                   1160:     return '';
1.35      ng       1161: }
1.34      ng       1162: 
1.44      ng       1163: #------------------------------------------------------------------------------------
                   1164: #
                   1165: #-------------------------- Next few routines handles grading by student, essentially
                   1166: #                           handles essay response type problem/part
                   1167: #
                   1168: #--- Javascript to handle the submission page functionality ---
                   1169: sub sub_page_js {
                   1170:     my $request = shift;
1.539     riegler  1171: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1172:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1173:     function updateRadio(formname,id,weight) {
1.125     ng       1174: 	var gradeBox = formname["GD_BOX"+id];
                   1175: 	var radioButton = formname["RADVAL"+id];
                   1176: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1177: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1178: 	gradeBox.value = pts;
                   1179: 	var resetbox = false;
                   1180: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1181: 	    alert("$alertmsg"+pts);
1.71      ng       1182: 	    for (var i=0; i<radioButton.length; i++) {
                   1183: 		if (radioButton[i].checked) {
                   1184: 		    gradeBox.value = i;
                   1185: 		    resetbox = true;
                   1186: 		}
                   1187: 	    }
                   1188: 	    if (!resetbox) {
                   1189: 		formtextbox.value = "";
                   1190: 	    }
                   1191: 	    return;
1.44      ng       1192: 	}
1.71      ng       1193: 
                   1194: 	if (pts > weight) {
                   1195: 	    var resp = confirm("You entered a value ("+pts+
                   1196: 			       ") greater than the weight for the part. Accept?");
                   1197: 	    if (resp == false) {
1.125     ng       1198: 		gradeBox.value = oldpts;
1.71      ng       1199: 		return;
                   1200: 	    }
1.44      ng       1201: 	}
1.13      albertel 1202: 
1.71      ng       1203: 	for (var i=0; i<radioButton.length; i++) {
                   1204: 	    radioButton[i].checked=false;
                   1205: 	    if (pts == i && pts != "") {
                   1206: 		radioButton[i].checked=true;
                   1207: 	    }
                   1208: 	}
                   1209: 	updateSelect(formname,id);
1.125     ng       1210: 	formname["stores"+id].value = "0";
1.41      ng       1211:     }
1.5       albertel 1212: 
1.72      ng       1213:     function writeBox(formname,id,pts) {
1.125     ng       1214: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1215: 	if (checkSolved(formname,id) == 'update') {
                   1216: 	    gradeBox.value = pts;
                   1217: 	} else {
1.125     ng       1218: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1219: 	    gradeBox.value = oldpts;
1.125     ng       1220: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1221: 	    for (var i=0; i<radioButton.length; i++) {
                   1222: 		radioButton[i].checked=false;
1.72      ng       1223: 		if (i == oldpts) {
1.71      ng       1224: 		    radioButton[i].checked=true;
                   1225: 		}
                   1226: 	    }
1.41      ng       1227: 	}
1.125     ng       1228: 	formname["stores"+id].value = "0";
1.71      ng       1229: 	updateSelect(formname,id);
                   1230: 	return;
1.41      ng       1231:     }
1.44      ng       1232: 
1.71      ng       1233:     function clearRadBox(formname,id) {
                   1234: 	if (checkSolved(formname,id) == 'noupdate') {
                   1235: 	    updateSelect(formname,id);
                   1236: 	    return;
                   1237: 	}
1.125     ng       1238: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1239: 	for (var i=0; i<gradeSelect.length; i++) {
                   1240: 	    if (gradeSelect[i].selected) {
                   1241: 		var selectx=i;
                   1242: 	    }
                   1243: 	}
1.125     ng       1244: 	var stores = formname["stores"+id];
1.71      ng       1245: 	if (selectx == stores.value) { return };
1.125     ng       1246: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1247: 	gradeBox.value = "";
1.125     ng       1248: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1249: 	for (var i=0; i<radioButton.length; i++) {
                   1250: 	    radioButton[i].checked=false;
                   1251: 	}
                   1252: 	stores.value = selectx;
                   1253:     }
1.5       albertel 1254: 
1.71      ng       1255:     function checkSolved(formname,id) {
1.125     ng       1256: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1257: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1258: 	    if (!reply) {return "noupdate";}
1.120     ng       1259: 	    formname.overRideScore.value = 'yes';
1.41      ng       1260: 	}
1.71      ng       1261: 	return "update";
1.13      albertel 1262:     }
1.71      ng       1263: 
                   1264:     function updateSelect(formname,id) {
1.125     ng       1265: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1266: 	return;
1.41      ng       1267:     }
1.33      ng       1268: 
1.121     ng       1269: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1270:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1271: 	formname.gradeOpt.value = val;
1.71      ng       1272: 	if (val == "Save & Next") {
                   1273: 	    for (i=0;i<=total;i++) {
                   1274: 		for (j=0;j<parttot;j++) {
1.125     ng       1275: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1276: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1277: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1278: 			if (points == "") {
1.125     ng       1279: 			    var name = formname["name"+i].value;
1.129     ng       1280: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1281: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1282: 					       ", part "+partid+". Continue?");
1.71      ng       1283: 			    if (resp == false) {
1.125     ng       1284: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1285: 				return false;
                   1286: 			    }
                   1287: 			}
                   1288: 		    }
                   1289: 		    
                   1290: 		}
                   1291: 	    }
                   1292: 	    
                   1293: 	}
1.120     ng       1294: 	formname.submit();
                   1295:     }
                   1296: 
1.71      ng       1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1298:     function checkSubmitPage(formname,total) {
                   1299: 	noscore = new Array(100);
                   1300: 	var ptr = 0;
                   1301: 	for (i=1;i<total;i++) {
1.125     ng       1302: 	    var partid = formname["q_"+i].value;
1.127     ng       1303: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1304: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1305: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1306: 		if (points == "" && status != "correct_by_student") {
                   1307: 		    noscore[ptr] = i;
                   1308: 		    ptr++;
                   1309: 		}
                   1310: 	    }
                   1311: 	}
                   1312: 	if (ptr != 0) {
                   1313: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1314: 	    var prolist = "";
                   1315: 	    if (ptr == 1) {
                   1316: 		prolist = noscore[0];
                   1317: 	    } else {
                   1318: 		var i = 0;
                   1319: 		while (i < ptr-1) {
                   1320: 		    prolist += noscore[i]+", ";
                   1321: 		    i++;
                   1322: 		}
                   1323: 		prolist += "and "+noscore[i];
                   1324: 	    }
                   1325: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1326: 	    if (resp == false) {
                   1327: 		return false;
                   1328: 	    }
                   1329: 	}
1.45      ng       1330: 
1.71      ng       1331: 	formname.submit();
                   1332:     }
                   1333: SUBJAVASCRIPT
                   1334: }
1.45      ng       1335: 
1.71      ng       1336: #--- javascript for essay type problem --
                   1337: sub sub_page_kw_js {
                   1338:     my $request = shift;
1.80      ng       1339:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1340:     &commonJSfunctions($request);
1.350     albertel 1341: 
1.629     www      1342:     my $inner_js_msg_central= (<<INNERJS);
                   1343: <script type="text/javascript">
1.350     albertel 1344:     function checkInput() {
                   1345:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1346:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1347:       var usrctr = document.msgcenter.usrctr.value;
                   1348:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1349:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1350: 
                   1351:       var msgchk = "";
                   1352:       if (document.msgcenter.subchk.checked) {
                   1353:          msgchk = "msgsub,";
                   1354:       }
                   1355:       var includemsg = 0;
                   1356:       for (var i=1; i<=nmsg; i++) {
                   1357:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1358:           var frmmsg = document.msgcenter["msg"+i];
                   1359:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1360:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1361:           showflg.value = "1";
                   1362:           var chkbox = document.msgcenter["msgn"+i];
                   1363:           if (chkbox.checked) {
                   1364:              msgchk += "savemsg"+i+",";
                   1365:              includemsg = 1;
                   1366:           }
                   1367:       }
                   1368:       if (document.msgcenter.newmsgchk.checked) {
                   1369:          msgchk += "newmsg"+usrctr;
                   1370:          includemsg = 1;
                   1371:       }
                   1372:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1373:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1374:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1375:       includemsg.value = msgchk;
                   1376: 
                   1377:       self.close()
                   1378: 
                   1379:     }
1.629     www      1380: </script>
1.350     albertel 1381: INNERJS
                   1382: 
1.629     www      1383:     my $inner_js_highlight_central= (<<INNERJS);
                   1384: <script type="text/javascript">
1.351     albertel 1385:     function updateChoice(flag) {
                   1386:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1387:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1388:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1389:       opener.document.SCORE.refresh.value = "on";
                   1390:       if (opener.document.SCORE.keywords.value!=""){
                   1391:          opener.document.SCORE.submit();
                   1392:       }
                   1393:       self.close()
                   1394:     }
1.629     www      1395: </script>
1.351     albertel 1396: INNERJS
                   1397: 
                   1398:     my $start_page_msg_central = 
                   1399:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1400: 				       {'js_ready'  => 1,
                   1401: 					'only_body' => 1,
                   1402: 					'bgcolor'   =>'#FFFFFF',});
                   1403:     my $end_page_msg_central = 
                   1404: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1405: 
                   1406: 
                   1407:     my $start_page_highlight_central = 
                   1408:         &Apache::loncommon::start_page('Highlight Central',
                   1409: 				       $inner_js_highlight_central,
1.350     albertel 1410: 				       {'js_ready'  => 1,
                   1411: 					'only_body' => 1,
                   1412: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1413:     my $end_page_highlight_central = 
1.350     albertel 1414: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1415: 
1.219     www      1416:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1417:     $docopen=~s/^document\.//;
1.652     raeburn  1418:     my %lt = &Apache::lonlocal::texthash(
                   1419:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1420:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1421:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1422:                 comp => 'Compose Message for: ',
                   1423:                 incl => 'Include',
1.656     raeburn  1424:                 type => 'Type',
1.652     raeburn  1425:                 subj => 'Subject',
                   1426:                 mesa => 'Message',
                   1427:                 new  => 'New',
                   1428:                 save => 'Save',
                   1429:                 canc => 'Cancel',
                   1430:                 kehi => 'Keyword Highlight Options',
                   1431:                 txtc => 'Text Color',
                   1432:                 font => 'Font Size',
1.656     raeburn  1433:                 fnst => 'Font Style',
1.652     raeburn  1434:              );
1.597     wenzelju 1435:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1436: 
1.44      ng       1437: //===================== Show list of keywords ====================
1.122     ng       1438:   function keywords(formname) {
1.652     raeburn  1439:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1440:     if (nret==null) return;
1.122     ng       1441:     formname.keywords.value = nret;
1.44      ng       1442: 
1.122     ng       1443:     if (formname.keywords.value != "") {
1.128     ng       1444: 	formname.refresh.value = "on";
1.122     ng       1445: 	formname.submit();
1.44      ng       1446:     }
                   1447:     return;
                   1448:   }
                   1449: 
                   1450: //===================== Script to view submitted by ==================
                   1451:   function viewSubmitter(submitter) {
                   1452:     document.SCORE.refresh.value = "on";
                   1453:     document.SCORE.NCT.value = "1";
                   1454:     document.SCORE.unamedom0.value = submitter;
                   1455:     document.SCORE.submit();
                   1456:     return;
                   1457:   }
                   1458: 
                   1459: //===================== Script to add keyword(s) ==================
                   1460:   function getSel() {
                   1461:     if (document.getSelection) txt = document.getSelection();
                   1462:     else if (document.selection) txt = document.selection.createRange().text;
                   1463:     else return;
                   1464:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1465:     if (cleantxt=="") {
1.652     raeburn  1466: 	alert("$lt{'plse'}");
1.44      ng       1467: 	return;
                   1468:     }
1.652     raeburn  1469:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1470:     if (nret==null) return;
1.127     ng       1471:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1472:     if (document.SCORE.keywords.value != "") {
1.127     ng       1473: 	document.SCORE.refresh.value = "on";
1.44      ng       1474: 	document.SCORE.submit();
                   1475:     }
                   1476:     return;
                   1477:   }
                   1478: 
                   1479: //====================== Script for composing message ==============
1.80      ng       1480:    // preload images
                   1481:    img1 = new Image();
                   1482:    img1.src = "$iconpath/mailbkgrd.gif";
                   1483:    img2 = new Image();
                   1484:    img2.src = "$iconpath/mailto.gif";
                   1485: 
1.44      ng       1486:   function msgCenter(msgform,usrctr,fullname) {
                   1487:     var Nmsg  = msgform.savemsgN.value;
                   1488:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1489:     var subject = msgform.msgsub.value;
1.127     ng       1490:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1491:     re = /msgsub/;
                   1492:     var shwsel = "";
                   1493:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1494:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1495:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1496:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1497: 	var testmsg = "savemsg"+i+",";
                   1498: 	re = new RegExp(testmsg,"g");
1.44      ng       1499: 	shwsel = "";
                   1500: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1501: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1502: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1503: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1504: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1505:     }
1.125     ng       1506:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1507:     shwsel = "";
                   1508:     re = /newmsg/;
                   1509:     if (re.test(msgchk)) { shwsel = "checked" }
                   1510:     newMsg(newmsg,shwsel);
                   1511:     msgTail(); 
                   1512:     return;
                   1513:   }
                   1514: 
1.123     ng       1515:   function checkEntities(strx) {
                   1516:     if (strx.length == 0) return strx;
                   1517:     var orgStr = ["&", "<", ">", '"']; 
                   1518:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1519:     var counter = 0;
                   1520:     while (counter < 4) {
                   1521: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1522: 	counter++;
                   1523:     }
                   1524:     return strx;
                   1525:   }
                   1526: 
                   1527:   function strReplace(strx, orgStr, newStr) {
                   1528:     return strx.split(orgStr).join(newStr);
                   1529:   }
                   1530: 
1.44      ng       1531:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1532:     var height = 70*Nmsg+250;
1.44      ng       1533:     if (height > 600) {
                   1534: 	height = 600;
                   1535:     }
1.118     ng       1536:     var xpos = (screen.width-600)/2;
                   1537:     xpos = (xpos < 0) ? '0' : xpos;
                   1538:     var ypos = (screen.height-height)/2-30;
                   1539:     ypos = (ypos < 0) ? '0' : ypos;
                   1540: 
1.668     www      1541:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1542:     pWin.focus();
                   1543:     pDoc = pWin.document;
1.219     www      1544:     pDoc.$docopen;
1.351     albertel 1545:     pDoc.write('$start_page_msg_central');
1.76      ng       1546: 
                   1547:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1548:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1549:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1550: 
1.676     golterma 1551:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1552:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1553: }
                   1554:     function displaySubject(msg,shwsel) {
1.76      ng       1555:     pDoc = pWin.document;
1.676     golterma 1556:     pDoc.write("<tr>");
                   1557:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1558:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1559:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1560: }
                   1561: 
1.72      ng       1562:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1563:     pDoc = pWin.document;
1.676     golterma 1564:     pDoc.write("<tr>");
                   1565:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1566:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1567:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1568: }
                   1569: 
                   1570:   function newMsg(newmsg,shwsel) {
1.76      ng       1571:     pDoc = pWin.document;
1.676     golterma 1572:     pDoc.write("<tr>");
                   1573:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1574:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1575:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1576: }
                   1577: 
                   1578:   function msgTail() {
1.76      ng       1579:     pDoc = pWin.document;
1.676     golterma 1580:     //pDoc.write("<\\/table>");
1.465     albertel 1581:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1582:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1584:     pDoc.write("<\\/form>");
1.351     albertel 1585:     pDoc.write('$end_page_msg_central');
1.128     ng       1586:     pDoc.close();
1.44      ng       1587: }
                   1588: 
                   1589: //====================== Script for keyword highlight options ==============
                   1590:   function kwhighlight() {
                   1591:     var kwclr    = document.SCORE.kwclr.value;
                   1592:     var kwsize   = document.SCORE.kwsize.value;
                   1593:     var kwstyle  = document.SCORE.kwstyle.value;
                   1594:     var redsel = "";
                   1595:     var grnsel = "";
                   1596:     var blusel = "";
                   1597:     if (kwclr=="red")   {var redsel="checked"};
                   1598:     if (kwclr=="green") {var grnsel="checked"};
                   1599:     if (kwclr=="blue")  {var blusel="checked"};
                   1600:     var sznsel = "";
                   1601:     var sz1sel = "";
                   1602:     var sz2sel = "";
                   1603:     if (kwsize=="0")  {var sznsel="checked"};
                   1604:     if (kwsize=="+1") {var sz1sel="checked"};
                   1605:     if (kwsize=="+2") {var sz2sel="checked"};
                   1606:     var synsel = "";
                   1607:     var syisel = "";
                   1608:     var sybsel = "";
                   1609:     if (kwstyle=="")    {var synsel="checked"};
                   1610:     if (kwstyle=="<i>") {var syisel="checked"};
                   1611:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1612:     highlightCentral();
                   1613:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1614:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1615:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1616:     highlightend();
                   1617:     return;
                   1618:   }
                   1619: 
                   1620:   function highlightCentral() {
1.76      ng       1621: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1622:     var xpos = (screen.width-400)/2;
                   1623:     xpos = (xpos < 0) ? '0' : xpos;
                   1624:     var ypos = (screen.height-330)/2-30;
                   1625:     ypos = (ypos < 0) ? '0' : ypos;
                   1626: 
1.206     albertel 1627:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1628:     hwdWin.focus();
                   1629:     var hDoc = hwdWin.document;
1.219     www      1630:     hDoc.$docopen;
1.351     albertel 1631:     hDoc.write('$start_page_highlight_central');
1.76      ng       1632:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1633:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1634: 
1.564     bisitz   1635:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1636:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1637:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1638:   }
                   1639: 
                   1640:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1641:     var hDoc = hwdWin.document;
                   1642:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1643:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1644:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1645:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1646:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1647:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1648:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1649:     hDoc.write("<\\/tr>");
1.44      ng       1650:   }
                   1651: 
                   1652:   function highlightend() { 
1.76      ng       1653:     var hDoc = hwdWin.document;
1.465     albertel 1654:     hDoc.write("<\\/table>");
                   1655:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1656:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1658:     hDoc.write("<\\/form>");
1.351     albertel 1659:     hDoc.write('$end_page_highlight_central');
1.128     ng       1660:     hDoc.close();
1.44      ng       1661:   }
                   1662: 
                   1663: SUBJAVASCRIPT
                   1664: }
                   1665: 
1.349     albertel 1666: sub get_increment {
1.348     bowersj2 1667:     my $increment = $env{'form.increment'};
                   1668:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1669:         $increment != .1) {
                   1670:         $increment = 1;
                   1671:     }
                   1672:     return $increment;
                   1673: }
                   1674: 
1.585     bisitz   1675: sub gradeBox_start {
                   1676:     return (
                   1677:         &Apache::loncommon::start_data_table()
                   1678:        .&Apache::loncommon::start_data_table_header_row()
                   1679:        .'<th>'.&mt('Part').'</th>'
                   1680:        .'<th>'.&mt('Points').'</th>'
                   1681:        .'<th>&nbsp;</th>'
                   1682:        .'<th>'.&mt('Assign Grade').'</th>'
                   1683:        .'<th>'.&mt('Weight').'</th>'
                   1684:        .'<th>'.&mt('Grade Status').'</th>'
                   1685:        .&Apache::loncommon::end_data_table_header_row()
                   1686:     );
                   1687: }
                   1688: 
                   1689: sub gradeBox_end {
                   1690:     return (
                   1691:         &Apache::loncommon::end_data_table()
                   1692:     );
                   1693: }
1.71      ng       1694: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1695: sub gradeBox {
1.322     albertel 1696:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1697:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1698: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1699:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1700:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1701:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1702:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1703:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1704: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1705:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1706:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1707:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1708: 				       [$partid]);
                   1709:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1710:     if ($last_resets{$partid}) {
                   1711:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1712:     }
1.695     bisitz   1713:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1714:     my $ctr = 0;
1.348     bowersj2 1715:     my $thisweight = 0;
1.349     albertel 1716:     my $increment = &get_increment();
1.485     albertel 1717: 
                   1718:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1719:     while ($thisweight<=$wgt) {
1.532     bisitz   1720: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1721:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1722: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1723: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1724: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1725:         $thisweight += $increment;
1.71      ng       1726: 	$ctr++;
                   1727:     }
1.485     albertel 1728:     $radio.='</tr></table>';
                   1729: 
                   1730:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1731: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1732: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1733: 	$wgt.')" /></td>'."\n";
1.485     albertel 1734:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1735: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1736: 	' </td>'."\n";
                   1737:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1738: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1739:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1740: 	$line.='<option></option>'.
                   1741: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1742:     } else {
1.485     albertel 1743: 	$line.='<option selected="selected"></option>'.
                   1744: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1745:     }
1.485     albertel 1746:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1747: 
                   1748: 
                   1749:     $result .= 
1.695     bisitz   1750: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1751:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1752:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1753:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1754: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1755: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1756: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1757:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1758:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1759:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1760:         $aggtries.'" />'."\n";
1.582     raeburn  1761:     my $res_error;
                   1762:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1763:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1764:     if ($res_error) {
                   1765:         return &navmap_errormsg();
                   1766:     }
1.318     banghart 1767:     return $result;
                   1768: }
1.322     albertel 1769: 
                   1770: sub handback_box {
1.623     www      1771:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1772:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1773:     my (@respids);
1.652     raeburn  1774:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1775:     foreach my $part_response_id (@part_response_id) {
                   1776:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1777:         if ($part eq $partid) {
1.375     albertel 1778:             push(@respids,$resp);
1.323     banghart 1779:         }
                   1780:     }
1.318     banghart 1781:     my $result;
1.323     banghart 1782:     foreach my $respid (@respids) {
1.322     albertel 1783: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1784: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1785: 	next if (!@$files);
1.654     raeburn  1786: 	my $file_counter = 0;
1.313     banghart 1787: 	foreach my $file (@$files) {
1.368     banghart 1788: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1789:                 $file_counter++;
1.368     banghart 1790:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1791:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1792:     	        $file_disp = "$name.$ext";
                   1793:     	        $file = $file_path.$file_disp;
                   1794:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1795:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1796:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1797:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1798: 	    }
1.322     albertel 1799: 	}
1.654     raeburn  1800:         if ($file_counter) {
                   1801:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1802:                        '<span class="LC_info">'.
                   1803:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1804:         }
1.313     banghart 1805:     }
1.318     banghart 1806:     return $result;    
1.71      ng       1807: }
1.44      ng       1808: 
1.58      albertel 1809: sub show_problem {
1.382     albertel 1810:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1811:     my $rendered;
1.382     albertel 1812:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1813:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1814:     if ($mode eq 'both' or $mode eq 'text') {
                   1815: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1816: 						       $env{'request.course.id'},
                   1817: 						       undef,\%form);
1.144     albertel 1818:     }
1.58      albertel 1819:     if ($removeform) {
                   1820: 	$rendered=~s|<form(.*?)>||g;
                   1821: 	$rendered=~s|</form>||g;
1.374     albertel 1822: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1823:     }
1.144     albertel 1824:     my $companswer;
                   1825:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1826: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1827: 	$companswer=
                   1828: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1829: 						    $env{'request.course.id'},
                   1830: 						    %form);
1.144     albertel 1831:     }
1.58      albertel 1832:     if ($removeform) {
                   1833: 	$companswer=~s|<form(.*?)>||g;
                   1834: 	$companswer=~s|</form>||g;
1.144     albertel 1835: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1836:     }
1.671     raeburn  1837:     my $renderheading = &mt('View of the problem');
                   1838:     my $answerheading = &mt('Correct answer');
                   1839:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1840:         my $stu_fullname = $env{'form.fullname'};
                   1841:         if ($stu_fullname eq '') {
                   1842:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1843:         }
                   1844:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1845:         if ($forwhom ne '') {
                   1846:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1847:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1848:         }
                   1849:     }
1.468     albertel 1850:     $rendered=
1.588     bisitz   1851:         '<div class="LC_Box">'
1.671     raeburn  1852:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1853:        .$rendered
                   1854:        .'</div>';
1.468     albertel 1855:     $companswer=
1.588     bisitz   1856:         '<div class="LC_Box">'
1.671     raeburn  1857:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1858:        .$companswer
                   1859:        .'</div>';
1.468     albertel 1860:     my $result;
1.144     albertel 1861:     if ($mode eq 'both') {
1.588     bisitz   1862:         $result=$rendered.$companswer;
1.144     albertel 1863:     } elsif ($mode eq 'text') {
1.588     bisitz   1864:         $result=$rendered;
1.144     albertel 1865:     } elsif ($mode eq 'answer') {
1.588     bisitz   1866:         $result=$companswer;
1.144     albertel 1867:     }
1.71      ng       1868:     return $result;
1.58      albertel 1869: }
1.397     albertel 1870: 
1.396     banghart 1871: sub files_exist {
                   1872:     my ($r, $symb) = @_;
                   1873:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1874: 
1.396     banghart 1875:     foreach my $student (@students) {
                   1876:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1877:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1878: 					      $udom,$uname);
1.396     banghart 1879:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1880:         foreach my $submission (@$string) {
                   1881:             my ($partid,$respid) =
                   1882: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1883:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1884: 					   \%record);
                   1885:             return 1 if (@$files);
1.396     banghart 1886:         }
                   1887:     }
1.397     albertel 1888:     return 0;
1.396     banghart 1889: }
1.397     albertel 1890: 
1.394     banghart 1891: sub download_all_link {
                   1892:     my ($r,$symb) = @_;
1.621     www      1893:     unless (&files_exist($r, $symb)) {
                   1894:        $r->print(&mt('There are currently no submitted documents.'));
                   1895:        return;
                   1896:     }
                   1897: 
1.395     albertel 1898:     my $all_students = 
                   1899: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1900: 
                   1901:     my $parts =
                   1902: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1903: 
1.394     banghart 1904:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1905:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1906:                              'cgi.'.$identifier.'.symb' => $symb,
                   1907:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1908:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1909: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1910:     return;
                   1911: }
                   1912: 
                   1913: sub submit_download_link {
                   1914:     my ($request,$symb) = @_;
                   1915:     if (!$symb) { return ''; }
                   1916: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1917:     &download_all_link($request,$symb);
1.394     banghart 1918: }
1.395     albertel 1919: 
1.432     banghart 1920: sub build_section_inputs {
                   1921:     my $section_inputs;
                   1922:     if ($env{'form.section'} eq '') {
                   1923:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1924:     } else {
                   1925:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1926:         foreach my $section (@sections) {
1.432     banghart 1927:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1928:         }
                   1929:     }
                   1930:     return $section_inputs;
                   1931: }
                   1932: 
1.44      ng       1933: # --------------------------- show submissions of a student, option to grade 
                   1934: sub submission {
1.608     www      1935:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1936:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1937:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1938:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1939:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1940: 
1.605     www      1941:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1942:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1943: 
                   1944:     if (!&canview($usec)) {
1.398     albertel 1945: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1946: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1947: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1948: 	return;
                   1949:     }
                   1950: 
1.257     albertel 1951:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1952:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1953:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1954:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1955:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1956: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1957: 	'/check.gif" height="16" border="0" />';
1.41      ng       1958: 
                   1959:     # header info
                   1960:     if ($counter == 0) {
                   1961: 	&sub_page_js($request);
1.621     www      1962: 	&sub_page_kw_js($request);
1.118     ng       1963: 
1.44      ng       1964: 	# option to display problem, only once else it cause problems 
                   1965:         # with the form later since the problem has a form.
1.257     albertel 1966: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1967: 	    my $mode;
1.257     albertel 1968: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1969: 		$mode='both';
1.257     albertel 1970: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1971: 		$mode='text';
1.257     albertel 1972: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1973: 		$mode='answer';
                   1974: 	    }
1.329     albertel 1975: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1976: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1977: 	}
1.441     www      1978: 
1.44      ng       1979: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1980:         # if this subroutine has been called once.
1.41      ng       1981: 	my %keyhash = ();
1.624     www      1982: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1983:         if (1) {
1.41      ng       1984: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1985: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1986: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1987: 
1.257     albertel 1988: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1989: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1990: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1991: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1992: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1993: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1994: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1995: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1996: 	}
1.257     albertel 1997: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1998: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1999: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2000: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2001: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2002: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2003: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2004: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2005: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2006: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2007: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2008: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2009: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2010: 			&build_section_inputs().
1.326     albertel 2011: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2012: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2013: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2014: #	if ($env{'form.handgrade'} eq 'yes') {
                   2015:         if (1) {
1.257     albertel 2016: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2017: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2018: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2019: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2020: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2021: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2022: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2023: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2024: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2025: 	    }
1.123     ng       2026: 	}
1.41      ng       2027: 	
                   2028: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2029: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2030: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2031: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2032: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2033: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2034: 		'" />'."\n".
                   2035: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2036: 	    $cts++;
                   2037: 	}
                   2038: 	$request->print($prnmsg);
1.32      ng       2039: 
1.624     www      2040: #	if ($env{'form.handgrade'} eq 'yes') {
                   2041:         if (1) {
1.652     raeburn  2042: 
                   2043:             my %lt = &Apache::lonlocal::texthash(
                   2044:                           keyw => 'Keyword Options',
1.655     raeburn  2045:                           list => 'List',
1.652     raeburn  2046:                           past => 'Paste Selection to List',
1.661     www      2047:                           high => 'Highlight Attribute',
1.652     raeburn  2048:                      );    
1.88      www      2049: #
                   2050: # Print out the keyword options line
                   2051: #
1.41      ng       2052: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2053: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2054: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2055: <a href="#" onmousedown="javascript:getSel(); return false"
1.695     bisitz   2056:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
1.652     raeburn  2057: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2058: KEYWORDS
1.88      www      2059: #
                   2060: # Load the other essays for similarity check
                   2061: #
1.324     albertel 2062:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2063: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2064: 	    $apath=&escape($apath);
1.88      www      2065: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2066:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2067:         }
                   2068:     }
1.44      ng       2069: 
1.441     www      2070: # This is where output for one specific student would start
1.592     bisitz   2071:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2072:     $request->print(
                   2073:         "\n\n"
                   2074:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2075:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2076:        ."\n"
                   2077:     );
1.441     www      2078: 
1.592     bisitz   2079:     # Show additional functions if allowed
                   2080:     if ($perm{'vgr'}) {
                   2081:         $request->print(
                   2082:             &Apache::loncommon::track_student_link(
                   2083:                 &mt('View recent activity'),
                   2084:                 $uname,$udom,'check')
                   2085:            .' '
                   2086:         );
                   2087:     }
                   2088:     if ($perm{'opa'}) {
                   2089:         $request->print(
                   2090:             &Apache::loncommon::pprmlink(
                   2091:                 &mt('Set/Change parameters'),
                   2092:                 $uname,$udom,$symb,'check'));
                   2093:     }
                   2094: 
                   2095:     # Show Problem
1.257     albertel 2096:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2097: 	my $mode;
1.257     albertel 2098: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2099: 	    $mode='both';
1.257     albertel 2100: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2101: 	    $mode='text';
1.257     albertel 2102: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2103: 	    $mode='answer';
                   2104: 	}
1.329     albertel 2105: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2106: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2107:     }
1.144     albertel 2108: 
1.257     albertel 2109:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2110:     my $res_error;
                   2111:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2112:     if ($res_error) {
                   2113:         $request->print(&navmap_errormsg());
                   2114:         return;
                   2115:     }
1.41      ng       2116: 
1.44      ng       2117:     # Display student info
1.41      ng       2118:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2119: 
                   2120:     my $result='<div class="LC_Box">'
                   2121:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2122:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2123:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2124: #    if ($env{'form.handgrade'} eq 'no') {
                   2125:     if (1) {
1.588     bisitz   2126:         $result.='<p class="LC_info">'
                   2127:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2128:                 ."</p>\n";
1.469     albertel 2129:     }
                   2130: 
1.118     ng       2131:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2132:     my $fullname;
                   2133:     my $col_fullnames = [];
1.624     www      2134: #    if ($env{'form.handgrade'} eq 'yes') {
                   2135:     if (1) {
1.464     albertel 2136: 	(my $sub_result,$fullname,$col_fullnames)=
                   2137: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2138: 				 $counter);
                   2139: 	$result.=$sub_result;
1.41      ng       2140:     }
1.44      ng       2141:     $request->print($result."\n");
1.588     bisitz   2142: 
1.44      ng       2143:     # print student answer/submission
1.588     bisitz   2144:     # Options are (1) Handgraded submission only
1.44      ng       2145:     #             (2) Last submission, includes submission that is not handgraded 
                   2146:     #                  (for multi-response type part)
                   2147:     #             (3) Last submission plus the parts info
                   2148:     #             (4) The whole record for this student
1.257     albertel 2149:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2150: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2151: 	
                   2152: 	my $lastsubonly;
                   2153: 
1.588     bisitz   2154:         if ($$timestamp eq '') {
                   2155:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2156:         } else {
1.592     bisitz   2157:             $lastsubonly =
                   2158:                 '<div class="LC_grade_submissions_body">'
                   2159:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2160: 
1.151     albertel 2161: 	    my %seenparts;
1.375     albertel 2162: 	    my @part_response_id = &flatten_responseType($responseType);
                   2163: 	    foreach my $part (@part_response_id) {
1.393     albertel 2164: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2165: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2166: 
1.375     albertel 2167: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2168: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2169: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2170: 		    if (exists($seenparts{$partid})) { next; }
                   2171: 		    $seenparts{$partid}=1;
1.695     bisitz   2172:                     $request->print(
                   2173:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2174:                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2175:                                    '<a href="javascript:viewSubmitter(\''.
                   2176:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2177:                                    '\');" target="_self">'.
                   2178:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2179:                         '<br />');
1.151     albertel 2180: 		    next;
                   2181: 		}
                   2182: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2183: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2184:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2185:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2186:                         ' <span class="LC_internal_info">'.
1.623     www      2187:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2188:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2189: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2190: 		    next;
                   2191: 		}
1.468     albertel 2192: 		foreach my $submission (@$string) {
                   2193: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2194: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2195: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2196: 		    # Similarity check
                   2197: 		    my $similar='';
1.640     raeburn  2198:                     my ($type,$trial,$rndseed);
                   2199:                     if ($hide eq 'rand') {
                   2200:                         $type = 'randomizetry';
                   2201:                         $trial = $record{"resource.$partid.tries"};
                   2202:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2203:                     }
1.257     albertel 2204: 		    if($env{'form.checkPlag'}){
1.151     albertel 2205: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.674     raeburn  2206: 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2207: 			if ($osim) {
                   2208: 			    $osim=int($osim*100.0);
1.426     albertel 2209: 			    my %old_course_desc = 
                   2210: 				&Apache::lonnet::coursedescription($ocrsid,
                   2211: 								   {'one_time' => 1});
                   2212: 
1.640     raeburn  2213:                             if ($hide eq 'anon') {
1.596     raeburn  2214:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2215:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2216:                             } else {
                   2217: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2218: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2219: 				        $osim,
                   2220: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2221: 				        $old_course_desc{'description'},
                   2222: 				        $old_course_desc{'num'},
                   2223: 				        $old_course_desc{'domain'}).
                   2224: 				    '</span></h3><blockquote><i>'.
                   2225: 				    &keywords_highlight($oessay).
                   2226: 				    '</i></blockquote><hr />';
                   2227:                             }
1.151     albertel 2228: 			}
1.150     albertel 2229: 		    }
1.640     raeburn  2230: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2231:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2232: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2233: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2234: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2235: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2236:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2237:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2238:                             ' <span class="LC_internal_info">'.
1.623     www      2239:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2240:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2241: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2242: 			if (@$files) {
1.640     raeburn  2243:                             if ($hide eq 'anon') {
1.596     raeburn  2244:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2245:                             } else {
                   2246:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2247:                                 foreach my $file (@$files) {
                   2248:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.695     bisitz   2249:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2250:                                 }
                   2251:                             }
1.236     albertel 2252: 			    $lastsubonly.='<br />';
1.41      ng       2253: 			}
1.640     raeburn  2254:                         if ($hide eq 'anon') {
1.596     raeburn  2255:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2256:                         } else {
                   2257: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2258: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2259: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2260:                         }
1.151     albertel 2261: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2262: 			$lastsubonly.='</div>';
1.41      ng       2263: 		    }
                   2264: 		}
                   2265: 	    }
1.588     bisitz   2266: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2267: 	}
                   2268: 	$request->print($lastsubonly);
1.468     albertel 2269:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2270:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2271: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2272:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2273: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2274: 								 $env{'request.course.id'},
1.44      ng       2275: 								 $last,'.submission',
                   2276: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2277:     }
1.121     ng       2278:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2279: 	.$udom.'" />'."\n");
1.44      ng       2280:     # return if view submission with no grading option
1.618     www      2281:     if (!&canmodify($usec)) {
1.633     www      2282: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2283: 	return;
1.180     albertel 2284:     } else {
1.468     albertel 2285: 	$request->print('</div>'."\n");
1.41      ng       2286:     }
1.33      ng       2287: 
1.121     ng       2288:     # essay grading message center
1.624     www      2289: #    if ($env{'form.handgrade'} eq 'yes') {
                   2290:     if (1) {
1.468     albertel 2291: 	my $result='<div class="LC_grade_message_center">';
                   2292:     
                   2293: 	$result.='<div class="LC_grade_message_center_header">'.
                   2294: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2295: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2296: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2297: 	if (scalar(@$col_fullnames) > 0) {
                   2298: 	    my $lastone = pop(@$col_fullnames);
                   2299: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2300: 	}
                   2301: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2302: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2303: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2304: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2305: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2306: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2307: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2308: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2309: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2310: 	    '<br />&nbsp;('.
1.468     albertel 2311: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2312: 	$result.='</div></div>';
1.121     ng       2313: 	$request->print($result);
1.118     ng       2314:     }
1.41      ng       2315: 
                   2316:     my %seen = ();
                   2317:     my @partlist;
1.129     ng       2318:     my @gradePartRespid;
1.375     albertel 2319:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2320:     $request->print(
1.588     bisitz   2321:         '<div class="LC_Box">'
                   2322:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2323:     );
1.592     bisitz   2324:     $request->print(&gradeBox_start());
1.375     albertel 2325:     foreach my $part_response_id (@part_response_id) {
                   2326:     	my ($partid,$respid) = @{ $part_response_id };
                   2327: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2328: 	next if ($seen{$partid} > 0);
1.41      ng       2329: 	$seen{$partid}++;
1.393     albertel 2330: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2331: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2332: 	push(@partlist,$partid);
                   2333: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2334: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2335:     }
1.585     bisitz   2336:     $request->print(&gradeBox_end()); # </div>
                   2337:     $request->print('</div>');
1.468     albertel 2338: 
                   2339:     $request->print('<div class="LC_grade_info_links">');
                   2340:     $request->print('</div>');
                   2341: 
1.45      ng       2342:     $result='<input type="hidden" name="partlist'.$counter.
                   2343: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2344:     $result.='<input type="hidden" name="gradePartRespid'.
                   2345: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2346:     my $ctr = 0;
                   2347:     while ($ctr < scalar(@partlist)) {
                   2348: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2349: 	    $partlist[$ctr].'" />'."\n";
                   2350: 	$ctr++;
                   2351:     }
1.468     albertel 2352:     $request->print($result.''."\n");
1.41      ng       2353: 
1.441     www      2354: # Done with printing info for one student
                   2355: 
1.468     albertel 2356:     $request->print('</div>');#LC_grade_show_user
1.441     www      2357: 
                   2358: 
1.41      ng       2359:     # print end of form
                   2360:     if ($counter == $total) {
1.592     bisitz   2361:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2362: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2363: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2364: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2365: 	my $ntstu ='<select name="NTSTU">'.
                   2366: 	    '<option>1</option><option>2</option>'.
                   2367: 	    '<option>3</option><option>5</option>'.
                   2368: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2369: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2370: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2371:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2372: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2373: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2374: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2375: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2376:         $endform.='<span class="LC_warning">'.
                   2377:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2378:                   '</span>'."\n" ;
1.349     albertel 2379:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2380:             "' name='increment' />";
1.485     albertel 2381: 	$endform.='</td></tr></table></form>';
1.41      ng       2382: 	$request->print($endform);
                   2383:     }
                   2384:     return '';
1.38      ng       2385: }
                   2386: 
1.464     albertel 2387: sub check_collaborators {
                   2388:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2389:     my ($result,@col_fullnames);
                   2390:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2391:     foreach my $part (keys(%$handgrade)) {
                   2392: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2393: 					'.maxcollaborators',
                   2394: 					$symb,$udom,$uname);
                   2395: 	next if ($ncol <= 0);
                   2396: 	$part =~ s/\_/\./g;
                   2397: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2398: 	my (@good_collaborators, @bad_collaborators);
                   2399: 	foreach my $possible_collaborator
1.630     www      2400: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2401: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2402: 	    next if ($possible_collaborator eq '');
1.631     www      2403: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2404: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2405: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2406: 	    # Doing this grep allows 'fuzzy' specification
                   2407: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2408: 			       keys(%$classlist));
                   2409: 	    if (! scalar(@matches)) {
                   2410: 		push(@bad_collaborators, $possible_collaborator);
                   2411: 	    } else {
                   2412: 		push(@good_collaborators, @matches);
                   2413: 	    }
                   2414: 	}
                   2415: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2416: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2417: 	    foreach my $name (@good_collaborators) {
                   2418: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2419: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2420: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2421: 	    }
1.630     www      2422: 	    $result.='</ol><br />'."\n";
1.466     albertel 2423: 	    my ($part)=split(/\./,$part);
1.464     albertel 2424: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2425: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2426: 		"\n";
                   2427: 	}
                   2428: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2429: 	    $result.='<div class="LC_warning">';
1.464     albertel 2430: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2431: 	    $result .= '</div>';
                   2432: 	}         
                   2433: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2434: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2435: 	    $result .= &mt('This student has submitted too many '.
                   2436: 		'collaborators.  Maximum is [_1].',$ncol);
                   2437: 	    $result .= '</div>';
                   2438: 	}
                   2439:     }
                   2440:     return ($result,$fullname,\@col_fullnames);
                   2441: }
                   2442: 
1.44      ng       2443: #--- Retrieve the last submission for all the parts
1.38      ng       2444: sub get_last_submission {
1.119     ng       2445:     my ($returnhash)=@_;
1.596     raeburn  2446:     my (@string,$timestamp,%lasthidden);
1.119     ng       2447:     if ($$returnhash{'version'}) {
1.46      ng       2448: 	my %lasthash=();
                   2449: 	my ($version);
1.119     ng       2450: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2451: 	    foreach my $key (sort(split(/\:/,
                   2452: 					$$returnhash{$version.':keys'}))) {
                   2453: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2454: 		$timestamp = 
1.545     raeburn  2455: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2456: 	    }
                   2457: 	}
1.640     raeburn  2458:         my (%typeparts,%randombytry);
1.596     raeburn  2459:         my $showsurv = 
                   2460:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2461:         foreach my $key (sort(keys(%lasthash))) {
                   2462:             if ($key =~ /\.type$/) {
                   2463:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2464:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2465:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2466:                     my ($ign,@parts) = split(/\./,$key);
                   2467:                     pop(@parts);
1.641     raeburn  2468:                     my $id = join('.',@parts);
1.640     raeburn  2469:                     if ($lasthash{$key} eq 'randomizetry') {
                   2470:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2471:                     } else {
                   2472:                         unless ($showsurv) {
                   2473:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2474:                         }
1.596     raeburn  2475:                     }
                   2476:                     delete($lasthash{$key});
                   2477:                 }
                   2478:             }
                   2479:         }
                   2480:         my @hidden = keys(%typeparts);
1.640     raeburn  2481:         my @randomize = keys(%randombytry);
1.397     albertel 2482: 	foreach my $key (keys(%lasthash)) {
                   2483: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2484:             my $hide;
                   2485:             if (@hidden) {
                   2486:                 foreach my $id (@hidden) {
                   2487:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2488:                         $hide = 'anon';
1.596     raeburn  2489:                         last;
                   2490:                     }
                   2491:                 }
                   2492:             }
1.640     raeburn  2493:             unless ($hide) {
                   2494:                 if (@randomize) {
                   2495:                     foreach my $id (@hidden) {
                   2496:                         if ($key =~ /^\Q$id\E/) {
                   2497:                             $hide = 'rand';
                   2498:                             last;
                   2499:                         }
                   2500:                     }
                   2501:                 }
                   2502:             }
1.397     albertel 2503: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2504: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2505: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2506: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2507: 	}
                   2508:     }
1.397     albertel 2509:     if (!@string) {
                   2510: 	$string[0] =
1.539     riegler  2511: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2512:     }
                   2513:     return (\@string,\$timestamp);
1.38      ng       2514: }
1.35      ng       2515: 
1.44      ng       2516: #--- High light keywords, with style choosen by user.
1.38      ng       2517: sub keywords_highlight {
1.44      ng       2518:     my $string    = shift;
1.257     albertel 2519:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2520:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2521:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2522:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2523:     foreach my $keyword (@keylist) {
                   2524: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2525:     }
                   2526:     return $string;
1.38      ng       2527: }
1.36      ng       2528: 
1.671     raeburn  2529: # For Tasks provide a mechanism to display previous version for one specific student
                   2530: 
                   2531: sub show_previous_task_version {
                   2532:     my ($request,$symb) = @_;
                   2533:     if ($symb eq '') {
                   2534:         $request->print("Unable to handle ambiguous references.");
                   2535: 
                   2536:         return '';
                   2537:     }
                   2538:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2539:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2540:     if (!&canview($usec)) {
                   2541:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
                   2542:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
                   2543:                         $env{'request.course.id'}.')</span>');
                   2544:         return;
                   2545:     }
                   2546:     my $mode = 'both';
                   2547:     my $isTask = ($symb =~/\.task$/);
                   2548:     if ($isTask) {
                   2549:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2550:             if ($env{'form.fullname'} eq '') {
                   2551:                 $env{'form.fullname'} =
                   2552:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2553:             }
                   2554:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2555:             $request->print("\n\n".
                   2556:                             '<div class="LC_grade_show_user">'.
                   2557:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2558:                             '</h2>'."\n");
                   2559:             &Apache::lonxml::clear_problem_counter();
                   2560:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2561:                             {'previousversion' => $env{'form.previousversion'} }));
                   2562:             $request->print("\n</div>");
                   2563:         }
                   2564:     }
                   2565:     return;
                   2566: }
                   2567: 
                   2568: sub choose_task_version_form {
                   2569:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2570:     my $isTask = ($symb =~/\.task$/);
                   2571:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2572:     if ($isTask) {
                   2573:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2574:                                               $udom,$uname);
                   2575:         if (($record{'resource.0.version'} eq '') ||
                   2576:             ($record{'resource.0.version'} < 2)) {
                   2577:             return ($record{'resource.0.version'},
                   2578:                     $record{'resource.0.version'},$result,$js);
                   2579:         } else {
                   2580:             $current = $record{'resource.0.version'};
                   2581:         }
                   2582:         if ($env{'form.previousversion'}) {
                   2583:             $displayed = $env{'form.previousversion'};
                   2584:             $rowtitle = &mt('Choose another version:')
                   2585:         } else {
                   2586:             $displayed = $current;
                   2587:             $rowtitle = &mt('Show earlier version:');
                   2588:         }
                   2589:         $result = '<div class="LC_left_float">';
                   2590:         my $list;
                   2591:         my $numversions = 0;
                   2592:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2593:             if ($i == $current) {
                   2594:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2595:                     next;
                   2596:                 } else {
                   2597:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2598:                     $numversions ++;
                   2599:                 }
                   2600:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2601:                 unless ($i == $env{'form.previousversion'}) {
                   2602:                     $numversions ++;
                   2603:                 }
                   2604:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2605:             }
                   2606:         }
                   2607:         if ($numversions) {
                   2608:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2609:             $result .=
                   2610:                 '<form name="getprev" method="post" action=""'.
                   2611:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2612:                 &Apache::loncommon::start_data_table().
                   2613:                 &Apache::loncommon::start_data_table_row().
                   2614:                 '<th align="left">'.$rowtitle.'</th>'.
                   2615:                 '<td><select name="version">'.
                   2616:                 '<option>'.&mt('Select').'</option>'.
                   2617:                 $list.
                   2618:                 '</select></td>'.
                   2619:                 &Apache::loncommon::end_data_table_row();
                   2620:             unless ($nomenu) {
                   2621:                 $result .= &Apache::loncommon::start_data_table_row().
                   2622:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2623:                 '<td><span class="LC_nobreak">'.
                   2624:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2625:                 &mt('Yes').'</label>'.
                   2626:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2627:                 '</span></td>'.
                   2628:                 &Apache::loncommon::end_data_table_row();
                   2629:             }
                   2630:             $result .=
                   2631:                 &Apache::loncommon::start_data_table_row().
                   2632:                 '<th align="left">&nbsp;</th>'.
                   2633:                 '<td>'.
                   2634:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2635:                 '</td>'.
                   2636:                 &Apache::loncommon::end_data_table_row().
                   2637:                 &Apache::loncommon::end_data_table().
                   2638:                 '</form>';
                   2639:             $js = &previous_display_javascript($nomenu,$current);
                   2640:         } elsif ($displayed && $nomenu) {
                   2641:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2642:         } else {
                   2643:             $result .= &mt('No previous versions to show for this student');
                   2644:         }
                   2645:         $result .= '</div>';
                   2646:     }
                   2647:     return ($current,$displayed,$result,$js);
                   2648: }
                   2649: 
                   2650: sub previous_display_javascript {
                   2651:     my ($nomenu,$current) = @_;
                   2652:     my $js = <<"JSONE";
                   2653: <script type="text/javascript">
                   2654: // <![CDATA[
                   2655: function previousVersion(uname,udom,symb) {
                   2656:     var current = '$current';
                   2657:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2658:     var prevstr = new RegExp("^\\\\d+\$");
                   2659:     if (!prevstr.test(version)) {
                   2660:         return false;
                   2661:     }
                   2662:     var url = '';
                   2663:     if (version == current) {
                   2664:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2665:     } else {
                   2666:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2667:     }
                   2668: JSONE
                   2669:     if ($nomenu) {
                   2670:         $js .= <<"JSTWO";
                   2671:     document.location.href = url;
                   2672: JSTWO
                   2673:     } else {
                   2674:         $js .= <<"JSTHREE";
                   2675:     var newwin = 0;
                   2676:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2677:         if (document.getprev.prevwin[i].checked == true) {
                   2678:             newwin = document.getprev.prevwin[i].value;
                   2679:         }
                   2680:     }
                   2681:     if (newwin == 1) {
                   2682:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2683:         url = url+'&inhibitmenu=yes';
                   2684:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2685:             previousWin = window.open(url,'',options,1);
                   2686:         } else {
                   2687:             previousWin.location.href = url;
                   2688:         }
                   2689:         previousWin.focus();
                   2690:         return false;
                   2691:     } else {
                   2692:         document.location.href = url;
                   2693:         return false;
                   2694:     }
                   2695: JSTHREE
                   2696:     }
                   2697:     $js .= <<"ENDJS";
                   2698:     return false;
                   2699: }
                   2700: // ]]>
                   2701: </script>
                   2702: ENDJS
                   2703: 
                   2704: }
                   2705: 
1.44      ng       2706: #--- Called from submission routine
1.38      ng       2707: sub processHandGrade {
1.608     www      2708:     my ($request,$symb) = @_;
1.324     albertel 2709:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2710:     my $button = $env{'form.gradeOpt'};
                   2711:     my $ngrade = $env{'form.NCT'};
                   2712:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2713:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2714:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2715: 
1.44      ng       2716:     if ($button eq 'Save & Next') {
                   2717: 	my $ctr = 0;
                   2718: 	while ($ctr < $ngrade) {
1.257     albertel 2719: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2720: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2721: 	    if ($errorflag eq 'no_score') {
                   2722: 		$ctr++;
                   2723: 		next;
                   2724: 	    }
1.104     albertel 2725: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2726: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2727: 		$ctr++;
                   2728: 		next;
                   2729: 	    }
1.257     albertel 2730: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2731: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2732: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2733:             my ($feedurl,$showsymb) =
                   2734: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2735: 	    my $messagetail;
1.62      albertel 2736: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2737: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2738: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2739: 		$subject.=' ['.$restitle.']';
1.44      ng       2740: 		my (@msgnum) = split(/,/,$includemsg);
                   2741: 		foreach (@msgnum) {
1.257     albertel 2742: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2743: 		}
1.80      ng       2744: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2745: 		if ($env{'form.withgrades'.$ctr}) {
                   2746: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2747: 		    $messagetail = " for <a href=\"".
1.605     www      2748: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2749: 		}
                   2750: 		$msgstatus = 
                   2751:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2752: 						     $message.$messagetail,
1.418     albertel 2753:                                                      undef,$feedurl,undef,
1.386     raeburn  2754:                                                      undef,undef,$showsymb,
                   2755:                                                      $restitle);
1.574     bisitz   2756: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2757: 				$msgstatus.'<br />');
1.44      ng       2758: 	    }
1.257     albertel 2759: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2760: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2761: 		foreach my $collabstr (@collabstrs) {
                   2762: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2763: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2764: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2765: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2766: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2767: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2768: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2769: 			    next;
1.418     albertel 2770: 			} elsif ($message ne '') {
                   2771: 			    my ($baseurl,$showsymb) = 
                   2772: 				&get_feedurl_and_symb($symb,$collaborator,
                   2773: 						      $udom);
                   2774: 			    if ($env{'form.withgrades'.$ctr}) {
                   2775: 				$messagetail = " for <a href=\"".
1.605     www      2776:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2777: 			    }
1.418     albertel 2778: 			    $msgstatus = 
                   2779: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2780: 			}
1.44      ng       2781: 		    }
                   2782: 		}
                   2783: 	    }
                   2784: 	    $ctr++;
                   2785: 	}
                   2786:     }
                   2787: 
1.624     www      2788: #    if ($env{'form.handgrade'} eq 'yes') {
                   2789:     if (1) {
1.119     ng       2790: 	# Keywords sorted in alphabatical order
1.257     albertel 2791: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2792: 	my %keyhash = ();
1.257     albertel 2793: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2794: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2795: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2796: 	$env{'form.keywords'} = join(' ',@keywords);
                   2797: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2798: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2799: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2800: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2801: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2802: 
                   2803: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2804: 	# New messages are saved in env for the next student.
1.119     ng       2805: 	# All messages are saved in nohist_handgrade.db
                   2806: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2807: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2808: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2809: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2810: 		$idx++;
                   2811: 	    }
                   2812: 	    $ctr++;
1.41      ng       2813: 	}
1.119     ng       2814: 	$ctr = 0;
                   2815: 	while ($ctr < $ngrade) {
1.257     albertel 2816: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2817: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2818: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2819: 		$idx++;
                   2820: 	    }
                   2821: 	    $ctr++;
1.41      ng       2822: 	}
1.257     albertel 2823: 	$env{'form.savemsgN'} = --$idx;
                   2824: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2825: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2826: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2827:     }
1.44      ng       2828:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2829:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2830:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2831: 	my ($ctr,$total) = (0,0);
                   2832: 	while ($ctr < $ngrade) {
1.257     albertel 2833: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2834: 	    $ctr++;
                   2835: 	}
1.257     albertel 2836: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2837: 	$ctr = 0;
                   2838: 	while ($ctr < $total) {
1.257     albertel 2839: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2840: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2841: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2842: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2843: 	    $ctr++;
                   2844: 	}
                   2845: 	return '';
                   2846:     }
1.36      ng       2847: 
1.44      ng       2848:     # Get the next/previous one or group of students
1.257     albertel 2849:     my $firststu = $env{'form.unamedom0'};
                   2850:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2851:     my $ctr = 2;
1.41      ng       2852:     while ($laststu eq '') {
1.257     albertel 2853: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2854: 	$ctr++;
                   2855: 	$laststu = $firststu if ($ctr > $ngrade);
                   2856:     }
1.44      ng       2857: 
1.41      ng       2858:     my (@parsedlist,@nextlist);
                   2859:     my ($nextflg) = 0;
1.524     raeburn  2860:     foreach my $item (sort 
1.294     albertel 2861: 	     {
                   2862: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2863: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2864: 		 }
                   2865: 		 return $a cmp $b;
                   2866: 	     } (keys(%$fullname))) {
1.605     www      2867: # FIXME: this is fishy, looks like the button label
1.41      ng       2868: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2869: 	    push(@parsedlist,$item);
1.41      ng       2870: 	}
1.524     raeburn  2871: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2872: 	if ($button eq 'Previous') {
1.524     raeburn  2873: 	    last if ($item eq $firststu);
                   2874: 	    push(@parsedlist,$item);
1.41      ng       2875: 	}
                   2876:     }
                   2877:     $ctr = 0;
1.605     www      2878: # FIXME: this is fishy, looks like the button label
1.41      ng       2879:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2880:     my $res_error;
                   2881:     my ($partlist) = &response_type($symb,\$res_error);
                   2882:     if ($res_error) {
                   2883:         $request->print(&navmap_errormsg());
                   2884:         return;
                   2885:     }
1.41      ng       2886:     foreach my $student (@parsedlist) {
1.257     albertel 2887: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2888: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2889: 	
                   2890: 	if ($submitonly eq 'queued') {
                   2891: 	    my %queue_status = 
                   2892: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2893: 							$udom,$uname);
                   2894: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2895: 	}
                   2896: 
1.156     albertel 2897: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2898: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2899: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2900: 	    my $submitted = 0;
1.248     albertel 2901: 	    my $ungraded = 0;
                   2902: 	    my $incorrect = 0;
1.524     raeburn  2903: 	    foreach my $item (keys(%status)) {
                   2904: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2905: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2906: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2907: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2908: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2909: 		    $submitted = 0;
                   2910: 		}
1.41      ng       2911: 	    }
1.156     albertel 2912: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2913: 				     $submitonly eq 'incorrect' ||
                   2914: 				     $submitonly eq 'graded'));
1.248     albertel 2915: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2916: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2917: 	}
1.524     raeburn  2918: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2919: 	last if ($ctr == $ntstu);
1.41      ng       2920: 	$ctr++;
                   2921:     }
1.36      ng       2922: 
1.41      ng       2923:     $ctr = 0;
                   2924:     my $total = scalar(@nextlist)-1;
1.39      ng       2925: 
1.524     raeburn  2926:     foreach (sort(@nextlist)) {
1.41      ng       2927: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2928: 	$env{'form.student'}  = $uname;
                   2929: 	$env{'form.userdom'}  = $udom;
                   2930: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2931: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2932: 	$ctr++;
                   2933:     }
                   2934:     if ($total < 0) {
1.653     raeburn  2935: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2936: 	$request->print($the_end);
                   2937:     }
                   2938:     return '';
1.38      ng       2939: }
1.36      ng       2940: 
1.44      ng       2941: #---- Save the score and award for each student, if changed
1.38      ng       2942: sub saveHandGrade {
1.324     albertel 2943:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2944:     my @version_parts;
1.104     albertel 2945:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2946: 					   $env{'request.course.id'});
1.104     albertel 2947:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2948:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2949:     my @parts_graded;
1.77      ng       2950:     my %newrecord  = ();
                   2951:     my ($pts,$wgt) = ('','');
1.269     raeburn  2952:     my %aggregate = ();
                   2953:     my $aggregateflag = 0;
1.301     albertel 2954:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2955:     foreach my $new_part (@parts) {
1.337     banghart 2956: 	#collaborator ($submi may vary for different parts
1.259     banghart 2957: 	if ($submitter && $new_part ne $part) { next; }
                   2958: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2959: 	if ($dropMenu eq 'excused') {
1.259     banghart 2960: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2961: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2962: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2963: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2964: 		}
1.364     banghart 2965: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2966: 	    }
1.125     ng       2967: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2968: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2969: 	    foreach my $key (keys(%record)) {
1.259     banghart 2970: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2971: 	    }
1.259     banghart 2972: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2973: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2974:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2975: 
                   2976:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2977: 					       [$new_part]);
                   2978:             my $aggtries =$totaltries;
1.269     raeburn  2979:             if ($last_resets{$new_part}) {
1.270     albertel 2980:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2981: 					   $new_part);
1.269     raeburn  2982:             }
1.270     albertel 2983: 
                   2984:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2985:             if ($aggtries > 0) {
1.327     albertel 2986:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2987:                 $aggregateflag = 1;
                   2988:             }
1.125     ng       2989: 	} elsif ($dropMenu eq '') {
1.259     banghart 2990: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2991: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2992: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2993: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2994: 		next;
                   2995: 	    }
1.259     banghart 2996: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2997: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2998: 	    my $partial= $pts/$wgt;
1.259     banghart 2999: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3000: 		#do not update score for part if not changed.
1.346     banghart 3001:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3002: 		next;
1.251     banghart 3003: 	    } else {
1.524     raeburn  3004: 	        push(@parts_graded,$new_part);
1.153     albertel 3005: 	    }
1.259     banghart 3006: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3007: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3008: 	    }
1.259     banghart 3009: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3010: 	    if ($partial == 0) {
1.153     albertel 3011: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3012: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3013: 		}
1.41      ng       3014: 	    } else {
1.153     albertel 3015: 		if ($record{$reckey} ne 'correct_by_override') {
                   3016: 		    $newrecord{$reckey} = 'correct_by_override';
                   3017: 		}
                   3018: 	    }	    
                   3019: 	    if ($submitter && 
1.259     banghart 3020: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3021: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3022: 	    }
1.259     banghart 3023: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3024: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3025: 	}
1.259     banghart 3026: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3027: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3028: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3029: 	        $dropMenu eq 'reset status')
                   3030: 	   {
1.524     raeburn  3031: 	    push(@version_parts,$new_part);
1.259     banghart 3032: 	}
1.41      ng       3033:     }
1.301     albertel 3034:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3035:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3036: 
1.344     albertel 3037:     if (%newrecord) {
                   3038:         if (@version_parts) {
1.364     banghart 3039:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3040:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3041: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3042: 	    foreach my $new_part (@version_parts) {
                   3043: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3044: 				$new_part,\%newrecord);
                   3045: 	    }
1.259     banghart 3046:         }
1.44      ng       3047: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3048: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3049: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3050: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3051:     }
1.269     raeburn  3052:     if ($aggregateflag) {
                   3053:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3054: 			      $cdom,$cnum);
1.269     raeburn  3055:     }
1.301     albertel 3056:     return ('',$pts,$wgt);
1.36      ng       3057: }
1.322     albertel 3058: 
1.380     albertel 3059: sub check_and_remove_from_queue {
                   3060:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3061:     my @ungraded_parts;
                   3062:     foreach my $part (@{$parts}) {
                   3063: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3064: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3065: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3066: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3067: 		) {
                   3068: 	    push(@ungraded_parts, $part);
                   3069: 	}
                   3070:     }
                   3071:     if ( !@ungraded_parts ) {
                   3072: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3073: 					       $cnum,$domain,$stuname);
                   3074:     }
                   3075: }
                   3076: 
1.337     banghart 3077: sub handback_files {
                   3078:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3079:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3080:     my $res_error;
                   3081:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3082:     if ($res_error) {
                   3083:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3084:         return;
                   3085:     }
1.654     raeburn  3086:     my @handedback;
                   3087:     my $file_msg;
1.375     albertel 3088:     my @part_response_id = &flatten_responseType($responseType);
                   3089:     foreach my $part_response_id (@part_response_id) {
                   3090:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3091: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3092:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3093:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3094:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3095:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3096:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3097:                     my ($directory,$answer_file) = 
1.654     raeburn  3098:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3099:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3100: 		        &file_name_version_ext($answer_file);
1.355     banghart 3101: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3102:                     my $getpropath = 1;
1.662     raeburn  3103:                     my ($dir_list,$listerror) = 
                   3104:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3105:                                                  $domain,$stuname,$getpropath);
                   3106: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3107:                     # fix filename
1.355     banghart 3108:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3109:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3110:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3111:             	                                $save_file_name);
1.337     banghart 3112:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3113:                         $request->print('<br /><span class="LC_error">'.
                   3114:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3115:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3116:                                         '</span>');
1.356     banghart 3117:                     } else {
1.360     banghart 3118:                         # mark the file as read only
1.654     raeburn  3119:                         push(@handedback,$save_file_name);
1.367     albertel 3120: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3121: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3122: 			}
                   3123:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3124: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3125:                     }
1.686     bisitz   3126:                     $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 3127:                 }
                   3128:             }
                   3129:         }
1.654     raeburn  3130:     }
                   3131:     if (@handedback > 0) {
                   3132:         $request->print('<br />');
                   3133:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3134:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3135:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3136:         my ($subject,$message);
                   3137:         if (scalar(@handedback) == 1) {
                   3138:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3139:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3140:         } else {
                   3141:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3142:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3143:         }
                   3144:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3145:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3146:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3147:         my ($feedurl,$showsymb) =
                   3148:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3149:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3150:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3151:         my $msgstatus =
                   3152:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3153:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3154:                  $restitle);
                   3155:         if ($msgstatus) {
                   3156:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3157:         }
                   3158:     }
1.338     banghart 3159:     return;
1.337     banghart 3160: }
                   3161: 
1.418     albertel 3162: sub get_feedurl_and_symb {
                   3163:     my ($symb,$uname,$udom) = @_;
                   3164:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3165:     $url = &Apache::lonnet::clutter($url);
                   3166:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3167: 					$symb,$udom,$uname);
                   3168:     if ($encrypturl =~ /^yes$/i) {
                   3169: 	&Apache::lonenc::encrypted(\$url,1);
                   3170: 	&Apache::lonenc::encrypted(\$symb,1);
                   3171:     }
                   3172:     return ($url,$symb);
                   3173: }
                   3174: 
1.313     banghart 3175: sub get_submitted_files {
                   3176:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3177:     my @files;
                   3178:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3179:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3180:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3181:     	    push(@files,$file_url.$file);
                   3182:         }
                   3183:     }
                   3184:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3185:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3186:     }
                   3187:     return (\@files);
                   3188: }
1.322     albertel 3189: 
1.269     raeburn  3190: # ----------- Provides number of tries since last reset.
                   3191: sub get_num_tries {
                   3192:     my ($record,$last_reset,$part) = @_;
                   3193:     my $timestamp = '';
                   3194:     my $num_tries = 0;
                   3195:     if ($$record{'version'}) {
                   3196:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3197:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3198:                 $timestamp = $$record{$version.':timestamp'};
                   3199:                 if ($timestamp > $last_reset) {
                   3200:                     $num_tries ++;
                   3201:                 } else {
                   3202:                     last;
                   3203:                 }
                   3204:             }
                   3205:         }
                   3206:     }
                   3207:     return $num_tries;
                   3208: }
                   3209: 
                   3210: # ----------- Determine decrements required in aggregate totals 
                   3211: sub decrement_aggs {
                   3212:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3213:     my %decrement = (
                   3214:                         attempts => 0,
                   3215:                         users => 0,
                   3216:                         correct => 0
                   3217:                     );
                   3218:     $decrement{'attempts'} = $aggtries;
                   3219:     if ($solvedstatus =~ /^correct/) {
                   3220:         $decrement{'correct'} = 1;
                   3221:     }
                   3222:     if ($aggtries == $totaltries) {
                   3223:         $decrement{'users'} = 1;
                   3224:     }
1.524     raeburn  3225:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3226:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3227:     }
                   3228:     return;
                   3229: }
                   3230: 
                   3231: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3232: sub get_last_resets {
1.270     albertel 3233:     my ($symb,$courseid,$partids) =@_;
                   3234:     my %last_resets;
1.269     raeburn  3235:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3236:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3237:     my @keys;
                   3238:     foreach my $part (@{$partids}) {
                   3239: 	push(@keys,"$symb\0$part\0resettime");
                   3240:     }
                   3241:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3242: 				     $cdom,$cname);
                   3243:     foreach my $part (@{$partids}) {
                   3244: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3245:     }
1.270     albertel 3246:     return %last_resets;
1.269     raeburn  3247: }
                   3248: 
1.251     banghart 3249: # ----------- Handles creating versions for portfolio files as answers
                   3250: sub version_portfiles {
1.343     banghart 3251:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3252:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3253:     my @returned_keys;
1.255     banghart 3254:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3255:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3256:     foreach my $key (keys(%$record)) {
1.259     banghart 3257:         my $new_portfiles;
1.263     banghart 3258:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3259:             my @versioned_portfiles;
1.367     albertel 3260:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3261:             foreach my $file (@portfiles) {
1.306     banghart 3262:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3263:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3264: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3265: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3266:                 my $getpropath = 1;    
1.662     raeburn  3267:                 my ($dir_list,$listerror) = 
                   3268:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3269:                                              $stu_name,$getpropath);
                   3270:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3271:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3272:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3273:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3274:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3275:                         [$directory.$new_answer],
1.306     banghart 3276:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3277:                 }
1.252     banghart 3278:             }
1.343     banghart 3279:             $$record{$key} = join(',',@versioned_portfiles);
                   3280:             push(@returned_keys,$key);
1.251     banghart 3281:         }
                   3282:     } 
1.343     banghart 3283:     return (@returned_keys);   
1.305     banghart 3284: }
                   3285: 
1.307     banghart 3286: sub get_next_version {
1.341     banghart 3287:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3288:     my $version;
1.662     raeburn  3289:     if (ref($dir_list) eq 'ARRAY') {
                   3290:         foreach my $row (@{$dir_list}) {
                   3291:             my ($file) = split(/\&/,$row,2);
                   3292:             my ($file_name,$file_version,$file_ext) =
                   3293: 	        &file_name_version_ext($file);
                   3294:             if (($file_name eq $answer_name) && 
                   3295: 	        ($file_ext eq $answer_ext)) {
                   3296:                      # gets here if filename and extension match, 
                   3297:                      # regardless of version
1.307     banghart 3298:                 if ($file_version ne '') {
1.662     raeburn  3299:                     # a versioned file is found  so save it for later
                   3300:                     if ($file_version > $version) {
                   3301: 		        $version = $file_version;
                   3302: 	            }
                   3303:                 }
1.307     banghart 3304:             }
                   3305:         }
1.662     raeburn  3306:     }
1.307     banghart 3307:     $version ++;
                   3308:     return($version);
                   3309: }
                   3310: 
1.305     banghart 3311: sub version_selected_portfile {
1.306     banghart 3312:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3313:     my ($answer_name,$answer_ver,$answer_ext) =
                   3314:         &file_name_version_ext($file_name);
                   3315:     my $new_answer;
                   3316:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3317:     if($env{'form.copy'} eq '-1') {
                   3318:         $new_answer = 'problem getting file';
                   3319:     } else {
                   3320:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3321:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3322:                             $stu_name,$domain,'copy',
                   3323: 		        '/portfolio'.$directory.$new_answer);
                   3324:     }    
                   3325:     return ($new_answer);
1.251     banghart 3326: }
                   3327: 
1.304     albertel 3328: sub file_name_version_ext {
                   3329:     my ($file)=@_;
                   3330:     my @file_parts = split(/\./, $file);
                   3331:     my ($name,$version,$ext);
                   3332:     if (@file_parts > 1) {
                   3333: 	$ext=pop(@file_parts);
                   3334: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3335: 	    $version=pop(@file_parts);
                   3336: 	}
                   3337: 	$name=join('.',@file_parts);
                   3338:     } else {
                   3339: 	$name=join('.',@file_parts);
                   3340:     }
                   3341:     return($name,$version,$ext);
                   3342: }
                   3343: 
1.44      ng       3344: #--------------------------------------------------------------------------------------
                   3345: #
                   3346: #-------------------------- Next few routines handles grading by section or whole class
                   3347: #
                   3348: #--- Javascript to handle grading by section or whole class
1.42      ng       3349: sub viewgrades_js {
                   3350:     my ($request) = shift;
                   3351: 
1.539     riegler  3352:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3353:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3354:    function writePoint(partid,weight,point) {
1.125     ng       3355: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3356: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3357: 	if (point == "textval") {
1.125     ng       3358: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3359: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3360: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3361: 		var resetbox = false;
                   3362: 		for (var i=0; i<radioButton.length; i++) {
                   3363: 		    if (radioButton[i].checked) {
                   3364: 			textbox.value = i;
                   3365: 			resetbox = true;
                   3366: 		    }
                   3367: 		}
                   3368: 		if (!resetbox) {
                   3369: 		    textbox.value = "";
                   3370: 		}
                   3371: 		return;
                   3372: 	    }
1.109     matthew  3373: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3374: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3375: 				   ") greater than the weight for the part. Accept?");
                   3376: 		if (resp == false) {
                   3377: 		    textbox.value = "";
                   3378: 		    return;
                   3379: 		}
                   3380: 	    }
1.42      ng       3381: 	    for (var i=0; i<radioButton.length; i++) {
                   3382: 		radioButton[i].checked=false;
1.109     matthew  3383: 		if (parseFloat(point) == i) {
1.42      ng       3384: 		    radioButton[i].checked=true;
                   3385: 		}
                   3386: 	    }
1.41      ng       3387: 
1.42      ng       3388: 	} else {
1.125     ng       3389: 	    textbox.value = parseFloat(point);
1.42      ng       3390: 	}
1.41      ng       3391: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3392: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3393: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3394: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3395: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3396: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3397: 	    if (saveval != "correct") {
                   3398: 		scorename.value = point;
1.43      ng       3399: 		if (selname[0].selected != true) {
                   3400: 		    selname[0].selected = true;
                   3401: 		}
1.42      ng       3402: 	    }
                   3403: 	}
1.125     ng       3404: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3405:     }
                   3406: 
                   3407:     function writeRadText(partid,weight) {
1.125     ng       3408: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3409: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3410:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3411: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3412: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3413: 	    for (var i=0; i<radioButton.length; i++) {
                   3414: 		radioButton[i].checked=false;
                   3415: 
                   3416: 	    }
                   3417: 	    textbox.value = "";
                   3418: 
                   3419: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3420: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3421: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3422: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3423: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3424: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3425: 		if ((saveval != "correct") || override) {
1.42      ng       3426: 		    scorename.value = "";
1.125     ng       3427: 		    if (selval[1].selected) {
                   3428: 			selname[1].selected = true;
                   3429: 		    } else {
                   3430: 			selname[2].selected = true;
                   3431: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3432: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3433: 		    }
1.42      ng       3434: 		}
                   3435: 	    }
1.43      ng       3436: 	} else {
                   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.125     ng       3444: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3445: 		    selname[0].selected = true;
                   3446: 		}
                   3447: 	    }
                   3448: 	}	    
1.42      ng       3449:     }
                   3450: 
                   3451:     function changeSelect(partid,user) {
1.125     ng       3452: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3453: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3454: 	var point  = textbox.value;
1.125     ng       3455: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3456: 
1.109     matthew  3457: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3458: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3459: 	    textbox.value = "";
                   3460: 	    return;
                   3461: 	}
1.109     matthew  3462: 	if (parseFloat(point) > parseFloat(weight)) {
                   3463: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3464: 			       ") greater than the weight of the part. Accept?");
                   3465: 	    if (resp == false) {
                   3466: 		textbox.value = "";
                   3467: 		return;
                   3468: 	    }
                   3469: 	}
1.42      ng       3470: 	selval[0].selected = true;
                   3471:     }
                   3472: 
                   3473:     function changeOneScore(partid,user) {
1.125     ng       3474: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3475: 	if (selval[1].selected || selval[2].selected) {
                   3476: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3477: 	    if (selval[2].selected) {
                   3478: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3479: 	    }
1.269     raeburn  3480:         }
1.42      ng       3481:     }
                   3482: 
                   3483:     function resetEntry(numpart) {
                   3484: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3485: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3486: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3487: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3488: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3489: 	    for (var i=0; i<radioButton.length; i++) {
                   3490: 		radioButton[i].checked=false;
                   3491: 
                   3492: 	    }
                   3493: 	    textbox.value = "";
                   3494: 	    selval[0].selected = true;
                   3495: 
                   3496: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3497: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3498: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3499: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3500: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3501: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3502: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3503: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3504: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3505: 		if (saveselval == "excused") {
1.43      ng       3506: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3507: 		} else {
1.43      ng       3508: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3509: 		}
                   3510: 	    }
1.41      ng       3511: 	}
1.42      ng       3512:     }
                   3513: 
1.41      ng       3514: VIEWJAVASCRIPT
1.42      ng       3515: }
                   3516: 
1.44      ng       3517: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3518: sub viewgrades {
1.608     www      3519:     my ($request,$symb) = @_;
1.42      ng       3520:     &viewgrades_js($request);
1.41      ng       3521: 
1.168     albertel 3522:     #need to make sure we have the correct data for later EXT calls, 
                   3523:     #thus invalidate the cache
                   3524:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3525:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3526:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3527:     &Apache::lonnet::clear_EXT_cache_status();
                   3528: 
1.398     albertel 3529:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3530: 
                   3531:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3532:     $result.=&jscriptNform($symb);
1.41      ng       3533: 
1.44      ng       3534:     #beginning of class grading form
1.442     banghart 3535:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3536:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3537: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3538: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3539: 	&build_section_inputs().
1.442     banghart 3540: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3541: 
1.560     raeburn  3542:     my ($common_header,$specific_header);
1.257     albertel 3543:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3544: 	$common_header = &mt('Assign Common Grade to Class');
                   3545:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3546:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3547:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3548: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3549:     } else {
1.560     raeburn  3550:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3551:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3552: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3553:     }
1.560     raeburn  3554:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3555:     #radio buttons/text box for assigning points for a section or class.
                   3556:     #handles different parts of a problem
1.582     raeburn  3557:     my $res_error;
                   3558:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3559:     if ($res_error) {
                   3560:         return &navmap_errormsg();
                   3561:     }
1.42      ng       3562:     my %weight = ();
                   3563:     my $ctsparts = 0;
1.45      ng       3564:     my %seen = ();
1.375     albertel 3565:     my @part_response_id = &flatten_responseType($responseType);
                   3566:     foreach my $part_response_id (@part_response_id) {
                   3567:     	my ($partid,$respid) = @{ $part_response_id };
                   3568: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3569: 	next if $seen{$partid};
                   3570: 	$seen{$partid}++;
1.375     albertel 3571: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3572: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3573: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3574: 
1.324     albertel 3575: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3576: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3577: 	my $ctr = 0;
1.42      ng       3578: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3579: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3580: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3581: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3582: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3583: 	    $ctr++;
                   3584: 	}
1.485     albertel 3585: 	$radio.='</tr></table>';
                   3586: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3587: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3588: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3589: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3590: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3591: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3592: 		$weight{$partid}.')"> '.
1.401     albertel 3593: 	    '<option selected="selected"> </option>'.
1.485     albertel 3594: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3595: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3596: 	    '</select></td>'.
                   3597:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3598: 	$line.='<input type="hidden" name="partid_'.
                   3599: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3600: 	$line.='<input type="hidden" name="weight_'.
                   3601: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3602: 
                   3603: 	$result.=
                   3604: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3605: 	    '<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 3606: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3607: 	$ctsparts++;
1.41      ng       3608:     }
1.474     albertel 3609:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3610: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3611:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3612: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3613: 
1.44      ng       3614:     #table listing all the students in a section/class
                   3615:     #header of table
1.560     raeburn  3616:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3617:               &Apache::loncommon::start_data_table().
                   3618: 	      &Apache::loncommon::start_data_table_header_row().
                   3619: 	      '<th>'.&mt('No.').'</th>'.
                   3620: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3621:     my $partserror;
                   3622:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3623:     if ($partserror) {
                   3624:         return &navmap_errormsg();
                   3625:     }
1.324     albertel 3626:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3627:     my @partids = ();
1.41      ng       3628:     foreach my $part (@parts) {
                   3629: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3630:         my $narrowtext = &mt('Tries');
                   3631: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3632: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3633: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3634:         push(@partids,$partid);
1.628     www      3635: #
                   3636: # FIXME: Looks like $display looks at English text
                   3637: #
1.324     albertel 3638: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3639: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3640: 	    $result.='<th>'.
1.697   ! bisitz   3641: 		&mt('Score Part: [_1][_2](weight = [_3])',
        !          3642: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3643: 	    next;
1.485     albertel 3644: 	    
1.207     albertel 3645: 	} else {
1.485     albertel 3646: 	    if ($display =~ /Problem Status/) {
                   3647: 		my $grade_status_mt = &mt('Grade Status');
                   3648: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3649: 	    }
                   3650: 	    my $part_mt = &mt('Part:');
                   3651: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3652: 	}
1.485     albertel 3653: 
1.474     albertel 3654: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3655:     }
1.474     albertel 3656:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3657: 
1.270     albertel 3658:     my %last_resets = 
                   3659: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3660: 
1.41      ng       3661:     #get info for each student
1.44      ng       3662:     #list all the students - with points and grade status
1.257     albertel 3663:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3664:     my $ctr = 0;
1.294     albertel 3665:     foreach (sort 
                   3666: 	     {
                   3667: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3668: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3669: 		 }
                   3670: 		 return $a cmp $b;
                   3671: 	     } (keys(%$fullname))) {
1.126     ng       3672: 	$ctr++;
1.324     albertel 3673: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3674: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3675:     }
1.474     albertel 3676:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3677:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3678:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3679: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3680:     if (scalar(%$fullname) eq 0) {
                   3681: 	my $colspan=3+scalar(@parts);
1.433     banghart 3682: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3683:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3684: 	$result='<span class="LC_warning">'.
1.485     albertel 3685: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3686: 	        $section_display, $stu_status).
1.433     banghart 3687: 	    '</span>';
1.96      albertel 3688:     }
1.41      ng       3689:     return $result;
                   3690: }
                   3691: 
1.44      ng       3692: #--- call by previous routine to display each student
1.41      ng       3693: sub viewstudentgrade {
1.324     albertel 3694:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3695:     my ($uname,$udom) = split(/:/,$student);
                   3696:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3697:     my %aggregates = (); 
1.474     albertel 3698:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3699: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3700: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3701: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3702: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3703: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3704:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3705:     foreach my $apart (@$parts) {
                   3706: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3707: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3708:         $result.='<td align="center">';
1.269     raeburn  3709:         my ($aggtries,$totaltries);
                   3710:         unless (exists($aggregates{$part})) {
1.270     albertel 3711: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3712: 
                   3713: 	    $aggtries = $totaltries;
1.269     raeburn  3714:             if ($$last_resets{$part}) {  
1.270     albertel 3715:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3716: 					   $part);
                   3717:             }
1.269     raeburn  3718:             $result.='<input type="hidden" name="'.
                   3719:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3720:             $result.='<input type="hidden" name="'.
                   3721:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3722:             $aggregates{$part} = 1;
                   3723:         }
1.41      ng       3724: 	if ($type eq 'awarded') {
1.320     albertel 3725: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3726: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3727: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3728: 	    $result.='<input type="text" name="'.
1.89      albertel 3729: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3730:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3731: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3732: 	} elsif ($type eq 'solved') {
                   3733: 	    my ($status,$foo)=split(/_/,$score,2);
                   3734: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3735: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3736: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3737: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3738: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3739:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3740: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3741: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3742: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3743: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3744: 	} else {
                   3745: 	    $result.='<input type="hidden" name="'.
                   3746: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3747: 		    "\n";
1.233     albertel 3748: 	    $result.='<input type="text" name="'.
1.122     ng       3749: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3750: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3751: 	}
                   3752:     }
1.474     albertel 3753:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3754:     return $result;
1.38      ng       3755: }
                   3756: 
1.44      ng       3757: #--- change scores for all the students in a section/class
                   3758: #    record does not get update if unchanged
1.38      ng       3759: sub editgrades {
1.608     www      3760:     my ($request,$symb) = @_;
1.41      ng       3761: 
1.433     banghart 3762:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3763:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3764:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3765: 
1.477     albertel 3766:     my $result= &Apache::loncommon::start_data_table().
                   3767: 	&Apache::loncommon::start_data_table_header_row().
                   3768: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3769: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3770:     my %scoreptr = (
                   3771: 		    'correct'  =>'correct_by_override',
                   3772: 		    'incorrect'=>'incorrect_by_override',
                   3773: 		    'excused'  =>'excused',
                   3774: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3775:                     'credited' =>'credit_attempted',
1.43      ng       3776: 		    'nothing'  => '',
                   3777: 		    );
1.257     albertel 3778:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3779: 
1.44      ng       3780:     my (@partid);
                   3781:     my %weight = ();
1.54      albertel 3782:     my %columns = ();
1.44      ng       3783:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3784: 
1.582     raeburn  3785:     my $partserror;
                   3786:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3787:     if ($partserror) {
                   3788:         return &navmap_errormsg();
                   3789:     }
1.54      albertel 3790:     my $header;
1.257     albertel 3791:     while ($ctr < $env{'form.totalparts'}) {
                   3792: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3793: 	push(@partid,$partid);
1.257     albertel 3794: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3795: 	$ctr++;
1.54      albertel 3796:     }
1.324     albertel 3797:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3798:     foreach my $partid (@partid) {
1.478     albertel 3799: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3800: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3801: 	$columns{$partid}=2;
                   3802: 	foreach my $stores (@parts) {
                   3803: 	    my ($part,$type) = &split_part_type($stores);
                   3804: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3805: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3806: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3807: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3808:             my $narrowtext = &mt('Tries');
                   3809: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3810: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3811: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3812: 	    $columns{$partid}+=2;
                   3813: 	}
                   3814:     }
                   3815:     foreach my $partid (@partid) {
1.324     albertel 3816: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3817: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3818: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3819: 	    '</th>';
1.54      albertel 3820: 
1.44      ng       3821:     }
1.477     albertel 3822:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3823: 	&Apache::loncommon::start_data_table_header_row().
                   3824: 	$header.
                   3825: 	&Apache::loncommon::end_data_table_header_row();
                   3826:     my @noupdate;
1.126     ng       3827:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3828:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3829: 	my $line;
1.257     albertel 3830: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3831: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3832: 	my %newrecord;
                   3833: 	my $updateflag = 0;
1.281     albertel 3834: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3835: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3836: 	if (!&canmodify($usec)) {
1.126     ng       3837: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3838: 	    push(@noupdate,
1.478     albertel 3839: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3840: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3841: 	    next;
                   3842: 	}
1.269     raeburn  3843:         my %aggregate = ();
                   3844:         my $aggregateflag = 0;
1.281     albertel 3845: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3846: 	foreach (@partid) {
1.257     albertel 3847: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3848: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3849: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3850: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3851: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3852: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3853: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3854: 	    my $score;
                   3855: 	    if ($partial eq '') {
1.257     albertel 3856: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3857: 	    } elsif ($partial > 0) {
                   3858: 		$score = 'correct_by_override';
                   3859: 	    } elsif ($partial == 0) {
                   3860: 		$score = 'incorrect_by_override';
                   3861: 	    }
1.257     albertel 3862: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3863: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3864: 
1.292     albertel 3865: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3866: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3867: 	    if ($dropMenu eq 'reset status' &&
                   3868: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3869: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3870: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3871: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3872: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3873: 		$updateflag = 1;
1.269     raeburn  3874:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3875:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3876:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3877:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3878:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3879:                     $aggregateflag = 1;
                   3880:                 }
1.139     albertel 3881: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3882: 		$updateflag = 1;
                   3883: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3884: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3885: 		$rec_update++;
1.125     ng       3886: 	    }
                   3887: 
1.93      albertel 3888: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3889: 		'<td align="center">'.$awarded.
                   3890: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3891: 
1.54      albertel 3892: 
                   3893: 	    my $partid=$_;
                   3894: 	    foreach my $stores (@parts) {
                   3895: 		my ($part,$type) = &split_part_type($stores);
                   3896: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3897: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3898: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3899: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3900: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3901: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3902: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3903: 		    $updateflag=1;
                   3904: 		}
1.93      albertel 3905: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3906: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3907: 	    }
1.44      ng       3908: 	}
1.477     albertel 3909: 	$line.="\n";
1.301     albertel 3910: 
                   3911: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3912: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3913: 
1.44      ng       3914: 	if ($updateflag) {
                   3915: 	    $count++;
1.257     albertel 3916: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3917: 				    $udom,$uname);
1.301     albertel 3918: 
                   3919: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3920: 					      $cnum,$udom,$uname)) {
                   3921: 		# need to figure out if should be in queue.
                   3922: 		my %record =  
                   3923: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3924: 					     $udom,$uname);
                   3925: 		my $all_graded = 1;
                   3926: 		my $none_graded = 1;
                   3927: 		foreach my $part (@parts) {
                   3928: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3929: 			$all_graded = 0;
                   3930: 		    } else {
                   3931: 			$none_graded = 0;
                   3932: 		    }
                   3933: 		}
                   3934: 
                   3935: 		if ($all_graded || $none_graded) {
                   3936: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3937: 							   $symb,$cdom,$cnum,
                   3938: 							   $udom,$uname);
                   3939: 		}
                   3940: 	    }
                   3941: 
1.477     albertel 3942: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3943: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3944: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3945: 	    $updateCtr++;
1.93      albertel 3946: 	} else {
1.477     albertel 3947: 	    push(@noupdate,
                   3948: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3949: 	    $noupdateCtr++;
1.44      ng       3950: 	}
1.269     raeburn  3951:         if ($aggregateflag) {
                   3952:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3953: 				  $cdom,$cnum);
1.269     raeburn  3954:         }
1.93      albertel 3955:     }
1.477     albertel 3956:     if (@noupdate) {
1.126     ng       3957: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3958: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3959: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3960: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3961: 	    &mt('No Changes Occurred For the Students Below').
                   3962: 	    '</td>'.
1.477     albertel 3963: 	    &Apache::loncommon::end_data_table_row();
                   3964: 	foreach my $line (@noupdate) {
                   3965: 	    $result.=
                   3966: 		&Apache::loncommon::start_data_table_row().
                   3967: 		$line.
                   3968: 		&Apache::loncommon::end_data_table_row();
                   3969: 	}
1.44      ng       3970:     }
1.614     www      3971:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3972:     my $msg = '<p><b>'.
                   3973: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3974: 	    $rec_update,$count).'</b><br />'.
                   3975: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3976: 	'</b></p>';
1.44      ng       3977:     return $title.$msg.$result;
1.5       albertel 3978: }
1.54      albertel 3979: 
                   3980: sub split_part_type {
                   3981:     my ($partstr) = @_;
                   3982:     my ($temp,@allparts)=split(/_/,$partstr);
                   3983:     my $type=pop(@allparts);
1.439     albertel 3984:     my $part=join('_',@allparts);
1.54      albertel 3985:     return ($part,$type);
                   3986: }
                   3987: 
1.44      ng       3988: #------------- end of section for handling grading by section/class ---------
                   3989: #
                   3990: #----------------------------------------------------------------------------
                   3991: 
1.5       albertel 3992: 
1.44      ng       3993: #----------------------------------------------------------------------------
                   3994: #
                   3995: #-------------------------- Next few routines handles grading by csv upload
                   3996: #
                   3997: #--- Javascript to handle csv upload
1.27      albertel 3998: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3999:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4000:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4001:   return(<<ENDPICK);
                   4002:   function verify(vf) {
                   4003:     var foundsomething=0;
                   4004:     var founduname=0;
1.243     albertel 4005:     var foundID=0;
1.27      albertel 4006:     for (i=0;i<=vf.nfields.value;i++) {
                   4007:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4008:       if (i==0 && tw!=0) { foundID=1; }
                   4009:       if (i==1 && tw!=0) { founduname=1; }
                   4010:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4011:     }
1.246     albertel 4012:     if (founduname==0 && foundID==0) {
                   4013: 	alert('$error1');
                   4014: 	return;
1.27      albertel 4015:     }
                   4016:     if (foundsomething==0) {
1.246     albertel 4017: 	alert('$error2');
                   4018: 	return;
1.27      albertel 4019:     }
                   4020:     vf.submit();
                   4021:   }
                   4022:   function flip(vf,tf) {
                   4023:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4024:     var i;
                   4025:     for (i=0;i<=vf.nfields.value;i++) {
                   4026:       //can not pick the same destination field for both name and domain
                   4027:       if (((i ==0)||(i ==1)) && 
                   4028:           ((tf==0)||(tf==1)) && 
                   4029:           (i!=tf) &&
                   4030:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4031:         eval('vf.f'+i+'.selectedIndex=0;')
                   4032:       }
                   4033:     }
                   4034:   }
                   4035: ENDPICK
                   4036: }
                   4037: 
                   4038: sub csvupload_javascript_forward_associate {
1.573     bisitz   4039:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4040:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4041:   return(<<ENDPICK);
                   4042:   function verify(vf) {
                   4043:     var foundsomething=0;
                   4044:     var founduname=0;
1.243     albertel 4045:     var foundID=0;
1.27      albertel 4046:     for (i=0;i<=vf.nfields.value;i++) {
                   4047:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4048:       if (tw==1) { foundID=1; }
                   4049:       if (tw==2) { founduname=1; }
                   4050:       if (tw>3) { foundsomething=1; }
1.27      albertel 4051:     }
1.246     albertel 4052:     if (founduname==0 && foundID==0) {
                   4053: 	alert('$error1');
                   4054: 	return;
1.27      albertel 4055:     }
                   4056:     if (foundsomething==0) {
1.246     albertel 4057: 	alert('$error2');
                   4058: 	return;
1.27      albertel 4059:     }
                   4060:     vf.submit();
                   4061:   }
                   4062:   function flip(vf,tf) {
                   4063:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4064:     var i;
                   4065:     //can not pick the same destination field twice
                   4066:     for (i=0;i<=vf.nfields.value;i++) {
                   4067:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4068:         eval('vf.f'+i+'.selectedIndex=0;')
                   4069:       }
                   4070:     }
                   4071:   }
                   4072: ENDPICK
                   4073: }
                   4074: 
1.26      albertel 4075: sub csvuploadmap_header {
1.324     albertel 4076:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4077:     my $javascript;
1.257     albertel 4078:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4079: 	$javascript=&csvupload_javascript_reverse_associate();
                   4080:     } else {
                   4081: 	$javascript=&csvupload_javascript_forward_associate();
                   4082:     }
1.45      ng       4083: 
1.418     albertel 4084:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4085:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4086:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4087:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4088:     my $reverse=&mt("Reverse Association");
1.41      ng       4089:     $request->print(<<ENDPICK);
1.632     www      4090: <br />
                   4091: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4092: <input type="hidden" name="associate"  value="" />
                   4093: <input type="hidden" name="phase"      value="three" />
                   4094: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4095: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4096: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4097: <input type="hidden" name="upfile_associate" 
1.257     albertel 4098:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4099: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4100: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4101: <hr />
                   4102: ENDPICK
1.597     wenzelju 4103:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4104:     return '';
1.26      albertel 4105: 
                   4106: }
                   4107: 
                   4108: sub csvupload_fields {
1.582     raeburn  4109:     my ($symb,$errorref) = @_;
                   4110:     my (@parts) = &getpartlist($symb,$errorref);
                   4111:     if (ref($errorref)) {
                   4112:         if ($$errorref) {
                   4113:             return;
                   4114:         }
                   4115:     }
                   4116: 
1.556     weissno  4117:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4118: 		['username','Student Username'],
                   4119: 		['domain','Student Domain']);
1.324     albertel 4120:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4121:     foreach my $part (sort(@parts)) {
                   4122: 	my @datum;
                   4123: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4124: 	my $name=$part;
                   4125: 	if  (!$display) { $display = $name; }
                   4126: 	@datum=($name,$display);
1.244     albertel 4127: 	if ($name=~/^stores_(.*)_awarded/) {
                   4128: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4129: 	}
1.41      ng       4130: 	push(@fields,\@datum);
                   4131:     }
                   4132:     return (@fields);
1.26      albertel 4133: }
                   4134: 
                   4135: sub csvuploadmap_footer {
1.41      ng       4136:     my ($request,$i,$keyfields) =@_;
                   4137:     $request->print(<<ENDPICK);
1.26      albertel 4138: </table>
                   4139: <input type="hidden" name="nfields" value="$i" />
                   4140: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4141: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4142: </form>
                   4143: ENDPICK
                   4144: }
                   4145: 
1.283     albertel 4146: sub checkforfile_js {
1.638     www      4147:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4148:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4149:     function checkUpload(formname) {
                   4150: 	if (formname.upfile.value == "") {
1.539     riegler  4151: 	    alert("$alertmsg");
1.86      ng       4152: 	    return false;
                   4153: 	}
                   4154: 	formname.submit();
                   4155:     }
                   4156: CSVFORMJS
1.283     albertel 4157:     return $result;
                   4158: }
                   4159: 
                   4160: sub upcsvScores_form {
1.608     www      4161:     my ($request,$symb) = @_;
1.283     albertel 4162:     if (!$symb) {return '';}
                   4163:     my $result=&checkforfile_js();
1.632     www      4164:     $result.=&Apache::loncommon::start_data_table().
                   4165:              &Apache::loncommon::start_data_table_header_row().
                   4166:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4167:              &Apache::loncommon::end_data_table_header_row().
                   4168:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4169:     my $upload=&mt("Upload Scores");
1.86      ng       4170:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4171:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4172:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4173:     $result.=<<ENDUPFORM;
1.106     albertel 4174: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4175: <input type="hidden" name="symb" value="$symb" />
                   4176: <input type="hidden" name="command" value="csvuploadmap" />
                   4177: $upfile_select
1.589     bisitz   4178: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4179: </form>
                   4180: ENDUPFORM
1.370     www      4181:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4182:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4183:              '</td>'.
                   4184:             &Apache::loncommon::end_data_table_row().
                   4185:             &Apache::loncommon::end_data_table();
1.86      ng       4186:     return $result;
                   4187: }
                   4188: 
                   4189: 
1.26      albertel 4190: sub csvuploadmap {
1.608     www      4191:     my ($request,$symb)= @_;
1.41      ng       4192:     if (!$symb) {return '';}
1.72      ng       4193: 
1.41      ng       4194:     my $datatoken;
1.257     albertel 4195:     if (!$env{'form.datatoken'}) {
1.41      ng       4196: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4197:     } else {
1.257     albertel 4198: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4199: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4200:     }
1.41      ng       4201:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4202:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4203:     my ($i,$keyfields);
                   4204:     if (@records) {
1.582     raeburn  4205:         my $fieldserror;
                   4206: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4207:         if ($fieldserror) {
                   4208:             $request->print(&navmap_errormsg());
                   4209:             return;
                   4210:         }
1.257     albertel 4211: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4212: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4213: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4214: 							  \@fields);
                   4215: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4216: 	    chop($keyfields);
                   4217: 	} else {
                   4218: 	    unshift(@fields,['none','']);
                   4219: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4220: 							    \@fields);
1.311     banghart 4221:             foreach my $rec (@records) {
                   4222:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4223:                 if (%temp) {
                   4224:                     $keyfields=join(',',sort(keys(%temp)));
                   4225:                     last;
                   4226:                 }
                   4227:             }
1.41      ng       4228: 	}
                   4229:     }
                   4230:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4231: 
1.41      ng       4232:     return '';
1.27      albertel 4233: }
                   4234: 
1.246     albertel 4235: sub csvuploadoptions {
1.608     www      4236:     my ($request,$symb)= @_;
1.632     www      4237:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4238:     $request->print(<<ENDPICK);
                   4239: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4240: <input type="hidden" name="command"    value="csvuploadassign" />
                   4241: <p>
                   4242: <label>
                   4243:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4244:    $overwrite
1.246     albertel 4245: </label>
                   4246: </p>
                   4247: ENDPICK
                   4248:     my %fields=&get_fields();
                   4249:     if (!defined($fields{'domain'})) {
1.257     albertel 4250: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4251: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4252:     }
1.257     albertel 4253:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4254: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4255: 	my $cleankey=$1;
                   4256: 	if ($cleankey eq 'command') { next; }
                   4257: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4258: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4259:     }
                   4260:     # FIXME do a check for any duplicated user ids...
                   4261:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4262:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4263: <hr /></form>'."\n");
1.246     albertel 4264:     return '';
                   4265: }
                   4266: 
                   4267: sub get_fields {
                   4268:     my %fields;
1.257     albertel 4269:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4270:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4271: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4272: 	    if ($env{'form.f'.$i} ne 'none') {
                   4273: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4274: 	    }
                   4275: 	} else {
1.257     albertel 4276: 	    if ($env{'form.f'.$i} ne 'none') {
                   4277: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4278: 	    }
                   4279: 	}
1.27      albertel 4280:     }
1.246     albertel 4281:     return %fields;
                   4282: }
                   4283: 
                   4284: sub csvuploadassign {
1.608     www      4285:     my ($request,$symb)= @_;
1.246     albertel 4286:     if (!$symb) {return '';}
1.345     bowersj2 4287:     my $error_msg = '';
1.246     albertel 4288:     &Apache::loncommon::load_tmp_file($request);
                   4289:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4290:     my %fields=&get_fields();
1.257     albertel 4291:     my $courseid=$env{'request.course.id'};
1.97      albertel 4292:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4293:     my @notallowed;
1.41      ng       4294:     my @skipped;
1.657     raeburn  4295:     my @warnings;
1.41      ng       4296:     my $countdone=0;
                   4297:     foreach my $grade (@gradedata) {
                   4298: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4299: 	my $domain;
                   4300: 	if ($entries{$fields{'domain'}}) {
                   4301: 	    $domain=$entries{$fields{'domain'}};
                   4302: 	} else {
1.257     albertel 4303: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4304: 	}
1.243     albertel 4305: 	$domain=~s/\s//g;
1.41      ng       4306: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4307: 	$username=~s/\s//g;
1.243     albertel 4308: 	if (!$username) {
                   4309: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4310: 	    $id=~s/\s//g;
1.243     albertel 4311: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4312: 	    $username=$ids{$id};
                   4313: 	}
1.41      ng       4314: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4315: 	    my $id=$entries{$fields{'ID'}};
                   4316: 	    $id=~s/\s//g;
                   4317: 	    if ($id) {
                   4318: 		push(@skipped,"$id:$domain");
                   4319: 	    } else {
                   4320: 		push(@skipped,"$username:$domain");
                   4321: 	    }
1.41      ng       4322: 	    next;
                   4323: 	}
1.108     albertel 4324: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4325: 	if (!&canmodify($usec)) {
                   4326: 	    push(@notallowed,"$username:$domain");
                   4327: 	    next;
                   4328: 	}
1.244     albertel 4329: 	my %points;
1.41      ng       4330: 	my %grades;
                   4331: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4332: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4333: 		$dest eq 'domain') { next; }
                   4334: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4335: 	    if ($dest=~/stores_(.*)_points/) {
                   4336: 		my $part=$1;
                   4337: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4338: 					      $symb,$domain,$username);
1.345     bowersj2 4339:                 if ($wgt) {
                   4340:                     $entries{$fields{$dest}}=~s/\s//g;
                   4341:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4342:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4343:                                           : 'correct_by_override';
1.638     www      4344:                     if ($pcr>1) {
1.657     raeburn  4345:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4346:                     }
1.345     bowersj2 4347:                     $grades{"resource.$part.awarded"}=$pcr;
                   4348:                     $grades{"resource.$part.solved"}=$award;
                   4349:                     $points{$part}=1;
                   4350:                 } else {
                   4351:                     $error_msg = "<br />" .
                   4352:                         &mt("Some point values were assigned"
                   4353:                             ." for problems with a weight "
                   4354:                             ."of zero. These values were "
                   4355:                             ."ignored.");
                   4356:                 }
1.244     albertel 4357: 	    } else {
                   4358: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4359: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4360: 		my $store_key=$dest;
                   4361: 		$store_key=~s/^stores/resource/;
                   4362: 		$store_key=~s/_/\./g;
                   4363: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4364: 	    }
1.41      ng       4365: 	}
1.508     www      4366: 	if (! %grades) { 
                   4367:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4368:         } else {
                   4369: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4370: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4371: 					   $env{'request.course.id'},
                   4372: 					   $domain,$username);
1.508     www      4373: 	   if ($result eq 'ok') {
1.627     www      4374: # Successfully stored
1.508     www      4375: 	      $request->print('.');
1.627     www      4376: # Remove from grading queue
                   4377:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4378:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4379:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4380:                                              $domain,$username);
                   4381:               $countdone++;
                   4382:            } else {
1.508     www      4383: 	      $request->print("<p><span class=\"LC_error\">".
                   4384:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4385:                                   "$username:$domain",$result)."</span></p>");
                   4386: 	   }
                   4387: 	   $request->rflush();
                   4388:         }
1.41      ng       4389:     }
1.570     www      4390:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4391:     if (@warnings) {
                   4392:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4393:         $request->print(join(', ',@warnings));
                   4394:     }
1.41      ng       4395:     if (@skipped) {
1.571     www      4396: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4397:         $request->print(join(', ',@skipped));
1.106     albertel 4398:     }
                   4399:     if (@notallowed) {
1.571     www      4400: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4401: 	$request->print(join(', ',@notallowed));
1.41      ng       4402:     }
1.106     albertel 4403:     $request->print("<br />\n");
1.345     bowersj2 4404:     return $error_msg;
1.26      albertel 4405: }
1.44      ng       4406: #------------- end of section for handling csv file upload ---------
                   4407: #
                   4408: #-------------------------------------------------------------------
                   4409: #
1.122     ng       4410: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4411: #
                   4412: #--- Select a page/sequence and a student to grade
1.68      ng       4413: sub pickStudentPage {
1.608     www      4414:     my ($request,$symb) = @_;
1.68      ng       4415: 
1.539     riegler  4416:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4417:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4418: 
                   4419: function checkPickOne(formname) {
1.76      ng       4420:     if (radioSelection(formname.student) == null) {
1.539     riegler  4421: 	alert("$alertmsg");
1.68      ng       4422: 	return;
                   4423:     }
1.125     ng       4424:     ptr = pullDownSelection(formname.selectpage);
                   4425:     formname.page.value = formname["page"+ptr].value;
                   4426:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4427:     formname.submit();
                   4428: }
                   4429: 
                   4430: LISTJAVASCRIPT
1.118     ng       4431:     &commonJSfunctions($request);
1.608     www      4432: 
1.257     albertel 4433:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4434:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4435:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4436: 
1.398     albertel 4437:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4438: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4439: 
1.80      ng       4440:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4441:     my $map_error;
                   4442:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4443:     if ($map_error) {
                   4444:         $request->print(&navmap_errormsg());
                   4445:         return; 
                   4446:     }
1.137     albertel 4447:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4448: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4449: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4450:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4451:     my $ctr=0;
1.68      ng       4452:     foreach (@$titles) {
                   4453: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4454: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4455: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4456: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4457: 	$ctr++;
1.68      ng       4458:     }
1.485     albertel 4459:     $select.= '</select>';
1.539     riegler  4460:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4461: 
1.70      ng       4462:     $ctr=0;
                   4463:     foreach (@$titles) {
                   4464: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4465: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4466: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4467: 	$ctr++;
                   4468:     }
1.72      ng       4469:     $result.='<input type="hidden" name="page" />'."\n".
                   4470: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4471: 
1.485     albertel 4472:     my $options =
                   4473: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4474: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4475:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4476: 
                   4477:     $options =
                   4478: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4479: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4480: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4481:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4482:     
                   4483:     $result.=&build_section_inputs();
1.442     banghart 4484:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4485:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4486: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4487: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4488: 
1.539     riegler  4489:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4490: 
1.80      ng       4491:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4492:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4493: 
1.68      ng       4494:     $request->print($result);
                   4495: 
1.485     albertel 4496:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4497: 	&Apache::loncommon::start_data_table().
                   4498: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4499: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4500: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4501: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4502: 	'<th>'.&nameUserString('header').'</th>'.
                   4503: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4504:  
1.76      ng       4505:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4506:     my $ptr = 1;
1.294     albertel 4507:     foreach my $student (sort 
                   4508: 			 {
                   4509: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4510: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4511: 			     }
                   4512: 			     return $a cmp $b;
                   4513: 			 } (keys(%$fullname))) {
1.68      ng       4514: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4515: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4516:                                   : '</td>');
1.126     ng       4517: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4518: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4519: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4520: 	$studentTable.=
                   4521: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4522:                          : '');
1.68      ng       4523: 	$ptr++;
                   4524:     }
1.484     albertel 4525:     if ($ptr%2 == 0) {
                   4526: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4527: 	    &Apache::loncommon::end_data_table_row();
                   4528:     }
                   4529:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4530:     $studentTable.='<input type="button" '.
1.589     bisitz   4531:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4532: 
                   4533:     $request->print($studentTable);
                   4534: 
                   4535:     return '';
                   4536: }
                   4537: 
                   4538: sub getSymbMap {
1.582     raeburn  4539:     my ($map_error) = @_;
1.132     bowersj2 4540:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4541:     unless (ref($navmap)) {
                   4542:         if (ref($map_error)) {
                   4543:             $$map_error = 'navmap';
                   4544:         }
                   4545:         return;
                   4546:     }
1.68      ng       4547:     my %symbx = ();
                   4548:     my @titles = ();
1.117     bowersj2 4549:     my $minder = 0;
                   4550: 
                   4551:     # Gather every sequence that has problems.
1.240     albertel 4552:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4553: 					       1,0,1);
1.117     bowersj2 4554:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4555: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4556: 	    my $title = $minder.'.'.
                   4557: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4558: 	    push(@titles, $title); # minder in case two titles are identical
                   4559: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4560: 	    $minder++;
1.241     albertel 4561: 	}
1.68      ng       4562:     }
                   4563:     return \@titles,\%symbx;
                   4564: }
                   4565: 
1.72      ng       4566: #
                   4567: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4568: sub displayPage {
1.608     www      4569:     my ($request,$symb) = @_;
1.257     albertel 4570:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4571:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4572:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4573:     my $pageTitle = $env{'form.page'};
1.103     albertel 4574:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4575:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4576:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4577: 
                   4578:     #need to make sure we have the correct data for later EXT calls, 
                   4579:     #thus invalidate the cache
                   4580:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4581:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4582:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4583:     &Apache::lonnet::clear_EXT_cache_status();
                   4584: 
1.103     albertel 4585:     if (!&canview($usec)) {
1.485     albertel 4586: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4587: 	return;
                   4588:     }
1.398     albertel 4589:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4590:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4591: 	'</h3>'."\n";
1.500     albertel 4592:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4593:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4594: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4595:     } else {
                   4596: 	delete($env{'form.CODE'});
                   4597:     }
1.71      ng       4598:     &sub_page_js($request);
                   4599:     $request->print($result);
                   4600: 
1.132     bowersj2 4601:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4602:     unless (ref($navmap)) {
                   4603:         $request->print(&navmap_errormsg());
                   4604:         return;
                   4605:     }
1.257     albertel 4606:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4607:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4608:     if (!$map) {
1.485     albertel 4609: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4610: 	return; 
                   4611:     }
1.68      ng       4612:     my $iterator = $navmap->getIterator($map->map_start(),
                   4613: 					$map->map_finish());
                   4614: 
1.71      ng       4615:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4616: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4617: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4618: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4619: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4620: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4622: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4623: 
1.382     albertel 4624:     if (defined($env{'form.CODE'})) {
                   4625: 	$studentTable.=
                   4626: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4627:     }
1.381     albertel 4628:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4629: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4630: 
1.594     bisitz   4631:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4632:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4633:         '</span>'."\n".
1.484     albertel 4634: 	&Apache::loncommon::start_data_table().
                   4635: 	&Apache::loncommon::start_data_table_header_row().
                   4636: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4637: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4638: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4639: 
1.329     albertel 4640:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4641:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4642:     $iterator->next(); # skip the first BEGIN_MAP
                   4643:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4644:     while ($depth > 0) {
1.68      ng       4645:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4646:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4647: 
1.385     albertel 4648:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4649: 	    my $parts = $curRes->parts();
1.68      ng       4650:             my $title = $curRes->compTitle();
1.71      ng       4651: 	    my $symbx = $curRes->symb();
1.484     albertel 4652: 	    $studentTable.=
                   4653: 		&Apache::loncommon::start_data_table_row().
                   4654: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4655: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4656: 		                        : '<br />('.&mt('[_1]parts',
                   4657: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4658: 		 ).
                   4659: 		 '</td>';
1.71      ng       4660: 	    $studentTable.='<td valign="top">';
1.382     albertel 4661: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4662: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4663: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4664: 					     undef,'both',\%form);
1.71      ng       4665: 	    } else {
1.382     albertel 4666: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4667: 		$companswer =~ s|<form(.*?)>||g;
                   4668: 		$companswer =~ s|</form>||g;
1.71      ng       4669: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4670: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4671: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4672: #		}
1.116     ng       4673: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4674: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4675: 	    }
                   4676: 
1.257     albertel 4677: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4678: 
1.257     albertel 4679: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4680: 		if ($record{'version'} eq '') {
1.485     albertel 4681: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4682: 		} else {
1.116     ng       4683: 		    my %responseType = ();
                   4684: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4685: 			my @responseIds =$curRes->responseIds($partid);
                   4686: 			my @responseType =$curRes->responseType($partid);
                   4687: 			my %responseIds;
                   4688: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4689: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4690: 			}
                   4691: 			$responseType{$partid} = \%responseIds;
1.116     ng       4692: 		    }
1.148     albertel 4693: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4694: 
1.71      ng       4695: 		}
1.257     albertel 4696: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4697: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4698: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4699: 									$env{'request.course.id'},
1.71      ng       4700: 									'','.submission');
                   4701:  
                   4702: 	    }
1.103     albertel 4703: 	    if (&canmodify($usec)) {
1.585     bisitz   4704:             $studentTable.=&gradeBox_start();
1.103     albertel 4705: 		foreach my $partid (@{$parts}) {
                   4706: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4707: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4708: 		    $question++;
                   4709: 		}
1.585     bisitz   4710:             $studentTable.=&gradeBox_end();
1.196     albertel 4711: 		$prob++;
1.71      ng       4712: 	    }
                   4713: 	    $studentTable.='</td></tr>';
1.68      ng       4714: 
1.103     albertel 4715: 	}
1.68      ng       4716:         $curRes = $iterator->next();
                   4717:     }
                   4718: 
1.589     bisitz   4719:     $studentTable.=
                   4720:         '</table>'."\n".
                   4721:         '<input type="button" value="'.&mt('Save').'" '.
                   4722:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4723:         '</form>'."\n";
1.71      ng       4724:     $request->print($studentTable);
                   4725: 
                   4726:     return '';
1.119     ng       4727: }
                   4728: 
                   4729: sub displaySubByDates {
1.148     albertel 4730:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4731:     my $isCODE=0;
1.335     albertel 4732:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4733:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4734:     my $studentTable=&Apache::loncommon::start_data_table().
                   4735: 	&Apache::loncommon::start_data_table_header_row().
                   4736: 	'<th>'.&mt('Date/Time').'</th>'.
                   4737: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4738:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4739: 	'<th>'.&mt('Submission').'</th>'.
                   4740: 	'<th>'.&mt('Status').'</th>'.
                   4741: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4742:     my ($version);
                   4743:     my %mark;
1.148     albertel 4744:     my %orders;
1.119     ng       4745:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4746:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4747: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4748:     }
1.335     albertel 4749: 
                   4750:     my $interaction;
1.525     raeburn  4751:     my $no_increment = 1;
1.640     raeburn  4752:     my %lastrndseed;
1.119     ng       4753:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4754: 	my $timestamp = 
                   4755: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4756: 	if (exists($$record{$version.':resource.0.version'})) {
                   4757: 	    $interaction = $$record{$version.':resource.0.version'};
                   4758: 	}
1.671     raeburn  4759:         if ($isTask && $env{'form.previousversion'}) {
                   4760:             next unless ($interaction == $env{'form.previousversion'});
                   4761:         }
1.335     albertel 4762: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4763: 		             : "$version:resource");
1.467     albertel 4764: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4765: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4766: 	if ($isCODE) {
                   4767: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4768: 	}
1.671     raeburn  4769:         if ($isTask) {
                   4770:             $studentTable.='<td>'.$interaction.'</td>';
                   4771:         }
1.119     ng       4772: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4773: 	my @displaySub = ();
                   4774: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4775:             my ($hidden,$type);
                   4776:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4777:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4778:                 $hidden = 1;
                   4779:             }
1.335     albertel 4780: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4781: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4782: 	    
1.122     ng       4783: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4784: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4785: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4786: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4787: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4788:                     
1.335     albertel 4789: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4790: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4791:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4792:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4793:                                    .' <span class="LC_internal_info">'
1.625     www      4794:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4795:                                    .'</span>'
                   4796:                                    .' <b>';
1.596     raeburn  4797:                     if ($hidden) {
                   4798:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4799:                     } else {
1.640     raeburn  4800:                         my ($trial,$rndseed,$newvariation);
                   4801:                         if ($type eq 'randomizetry') {
                   4802:                             $trial = $$record{"$where.$partid.tries"};
                   4803:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4804:                         }
1.596     raeburn  4805: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4806: 			    $displaySub[0].=&mt('Trial not counted');
                   4807: 		        } else {
                   4808: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4809: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4810:                             if ($rndseed || $lastrndseed{$partid}) {
                   4811:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4812:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4813:                                 }
                   4814:                             }
                   4815:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4816: 		        }
                   4817: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4818:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4819: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4820: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4821: 			    $orders{$partid}->{$responseId}=
                   4822: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4823:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4824: 		        }
1.640     raeburn  4825: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4826: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4827: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4828:                     }
1.147     albertel 4829: 		}
                   4830: 	    }
1.335     albertel 4831: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4832: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4833: 				    $$record{"$where.$partid.checkedin"},
                   4834: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4835: 					'<br />';
1.335     albertel 4836: 	    }
                   4837: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4838: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4839: 		    lc($$record{"$where.$partid.award"}).' '.
                   4840: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4841: 		    '<br />';
                   4842: 	    }
1.335     albertel 4843: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4844: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4845: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4846: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4847: 		$displaySub[2].=
                   4848: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4849: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4850: 	    }
                   4851: 	}
                   4852: 	# needed because old essay regrader has not parts info
                   4853: 	if (exists $$record{"$version:resource.regrader"}) {
                   4854: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4855: 	}
                   4856: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4857: 	if ($displaySub[2]) {
1.467     albertel 4858: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4859: 	}
1.467     albertel 4860: 	$studentTable.='&nbsp;</td>'.
                   4861: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4862:     }
1.467     albertel 4863:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4864:     return $studentTable;
1.71      ng       4865: }
                   4866: 
                   4867: sub updateGradeByPage {
1.608     www      4868:     my ($request,$symb) = @_;
1.71      ng       4869: 
1.257     albertel 4870:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4871:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4872:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4873:     my $pageTitle = $env{'form.page'};
1.103     albertel 4874:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4875:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4876:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4877:     if (!&canmodify($usec)) {
1.526     raeburn  4878: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4879: 	return;
                   4880:     }
1.398     albertel 4881:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4882:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4883: 	'</h3>'."\n";
1.70      ng       4884: 
1.68      ng       4885:     $request->print($result);
                   4886: 
1.582     raeburn  4887: 
1.132     bowersj2 4888:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4889:     unless (ref($navmap)) {
                   4890:         $request->print(&navmap_errormsg());
                   4891:         return;
                   4892:     }
1.257     albertel 4893:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4894:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4895:     if (!$map) {
1.527     raeburn  4896: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4897: 	return; 
                   4898:     }
1.71      ng       4899:     my $iterator = $navmap->getIterator($map->map_start(),
                   4900: 					$map->map_finish());
1.70      ng       4901: 
1.484     albertel 4902:     my $studentTable=
                   4903: 	&Apache::loncommon::start_data_table().
                   4904: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4905: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4906: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4907: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4908: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4909: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4910: 
                   4911:     $iterator->next(); # skip the first BEGIN_MAP
                   4912:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4913:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4914:     while ($depth > 0) {
1.71      ng       4915:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4916:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4917: 
1.385     albertel 4918:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4919: 	    my $parts = $curRes->parts();
1.71      ng       4920:             my $title = $curRes->compTitle();
                   4921: 	    my $symbx = $curRes->symb();
1.484     albertel 4922: 	    $studentTable.=
                   4923: 		&Apache::loncommon::start_data_table_row().
                   4924: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4925: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4926:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4927: 		.')').'</td>';
1.71      ng       4928: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4929: 
                   4930: 	    my %newrecord=();
                   4931: 	    my @displayPts=();
1.269     raeburn  4932:             my %aggregate = ();
                   4933:             my $aggregateflag = 0;
1.71      ng       4934: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4935: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4936: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4937: 
1.257     albertel 4938: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4939: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4940: 		my $partial = $newpts/$wgt;
                   4941: 		my $score;
                   4942: 		if ($partial > 0) {
                   4943: 		    $score = 'correct_by_override';
1.125     ng       4944: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4945: 		    $score = 'incorrect_by_override';
                   4946: 		}
1.257     albertel 4947: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4948: 		if ($dropMenu eq 'excused') {
1.71      ng       4949: 		    $partial = '';
                   4950: 		    $score = 'excused';
1.125     ng       4951: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4952: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4953: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4954: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4955: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4956: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4957: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4958: 		    $changeflag++;
                   4959: 		    $newpts = '';
1.269     raeburn  4960:                     
                   4961:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4962:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4963:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4964:                     if ($aggtries > 0) {
                   4965:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4966:                         $aggregateflag = 1;
                   4967:                     }
1.71      ng       4968: 		}
1.324     albertel 4969: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4970: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4971: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4972: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4973: 		    '&nbsp;<br />';
1.526     raeburn  4974: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4975: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4976: 		    '&nbsp;<br />';
1.71      ng       4977: 		$question++;
1.380     albertel 4978: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4979: 
1.71      ng       4980: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4981: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4982: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4983: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4984: 
                   4985: 		$changeflag++;
                   4986: 	    }
                   4987: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4988: 		my %record = 
                   4989: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4990: 					     $udom,$uname);
                   4991: 
                   4992: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4993: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4994: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4995: 		    $newrecord{'resource.CODE'} = '';
                   4996: 		}
1.257     albertel 4997: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4998: 					$udom,$uname);
1.382     albertel 4999: 		%record = &Apache::lonnet::restore($symbx,
                   5000: 						   $env{'request.course.id'},
                   5001: 						   $udom,$uname);
1.380     albertel 5002: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5003: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5004: 	    }
1.380     albertel 5005: 	    
1.269     raeburn  5006:             if ($aggregateflag) {
                   5007:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5008:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5009:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5010:             }
1.125     ng       5011: 
1.71      ng       5012: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5013: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5014: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5015: 
1.196     albertel 5016: 	    $prob++;
1.68      ng       5017: 	}
1.71      ng       5018:         $curRes = $iterator->next();
1.68      ng       5019:     }
1.98      albertel 5020: 
1.484     albertel 5021:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5022:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5023: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5024: 		  $changeflag));
1.76      ng       5025:     $request->print($grademsg.$studentTable);
1.68      ng       5026: 
1.70      ng       5027:     return '';
                   5028: }
                   5029: 
1.72      ng       5030: #-------- end of section for handling grading by page/sequence ---------
                   5031: #
                   5032: #-------------------------------------------------------------------
                   5033: 
1.581     www      5034: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5035: #
                   5036: #------ start of section for handling grading by page/sequence ---------
                   5037: 
1.423     albertel 5038: =pod
                   5039: 
                   5040: =head1 Bubble sheet grading routines
                   5041: 
1.424     albertel 5042:   For this documentation:
                   5043: 
                   5044:    'scanline' refers to the full line of characters
                   5045:    from the file that we are parsing that represents one entire sheet
                   5046: 
                   5047:    'bubble line' refers to the data
1.659     raeburn  5048:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5049: 
                   5050: 
1.659     raeburn  5051: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5052: into a course. When a user wants to grade, they select a
1.659     raeburn  5053: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5054: one of the predefined configurations for what each scanline looks
                   5055: like.
                   5056: 
                   5057: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5058: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5059: because too light bubbling), 'double bubble' (each bubble line should
                   5060: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  5061: invalid student/employee ID
1.424     albertel 5062: 
                   5063: If the CODE option is used that determines the randomization of the
1.556     weissno  5064: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5065: username:domain.
                   5066: 
                   5067: During the validation phase the instructor can choose to skip scanlines. 
                   5068: 
1.659     raeburn  5069: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5070: 
                   5071:   scantron_original_filename (unmodified original file)
                   5072:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5073:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5074: 
                   5075: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5076: correction information that isn't representable in the bubblesheet
1.424     albertel 5077: file (see &scantron_getfile() for more information)
                   5078: 
                   5079: After all scanlines are either valid, marked as valid or skipped, then
                   5080: foreach line foreach problem in the picked sequence, an ssi request is
                   5081: made that simulates a user submitting their selected letter(s) against
                   5082: the homework problem.
1.423     albertel 5083: 
                   5084: =over 4
                   5085: 
                   5086: 
                   5087: 
                   5088: =item defaultFormData
                   5089: 
                   5090:   Returns html hidden inputs used to hold context/default values.
                   5091: 
                   5092:  Arguments:
                   5093:   $symb - $symb of the current resource 
                   5094: 
                   5095: =cut
1.422     foxr     5096: 
1.81      albertel 5097: sub defaultFormData {
1.324     albertel 5098:     my ($symb)=@_;
1.613     www      5099:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5100: }
                   5101: 
1.447     foxr     5102: 
1.423     albertel 5103: =pod 
                   5104: 
                   5105: =item getSequenceDropDown
                   5106: 
                   5107:    Return html dropdown of possible sequences to grade
                   5108:  
                   5109:  Arguments:
1.582     raeburn  5110:    $symb - $symb of the current resource
                   5111:    $map_error - ref to scalar which will container error if
                   5112:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5113: 
                   5114: =cut
1.422     foxr     5115: 
1.75      albertel 5116: sub getSequenceDropDown {
1.582     raeburn  5117:     my ($symb,$map_error)=@_;
1.75      albertel 5118:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5119:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5120:     if (ref($map_error)) {
                   5121:         return if ($$map_error);
                   5122:     }
1.137     albertel 5123:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5124:     my $ctr=0;
                   5125:     foreach (@$titles) {
                   5126: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5127: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5128: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5129: 	    '>'.$showtitle.'</option>'."\n";
                   5130: 	$ctr++;
                   5131:     }
                   5132:     $result.= '</select>';
                   5133:     return $result;
                   5134: }
                   5135: 
1.495     albertel 5136: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5137:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5138: 
                   5139: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5140: 
1.509     raeburn  5141: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5142:                                    # matchresponse or rankresponse, where 
                   5143:                                    # an individual response can have multiple 
                   5144:                                    # lines
1.503     raeburn  5145: 
                   5146: my %responsetype_per_response;     # responsetype for each response
                   5147: 
1.691     raeburn  5148: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5149:                                    # numbered response. Needed when randomorder
                   5150:                                    # or randompick are in use. Key is ID, value 
                   5151:                                    # is response number.
                   5152: 
1.495     albertel 5153: # Save and restore the bubble lines array to the form env.
                   5154: 
                   5155: 
                   5156: sub save_bubble_lines {
                   5157:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5158: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5159: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5160: 	    $first_bubble_line{$line};
1.503     raeburn  5161:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5162:             $subdivided_bubble_lines{$line};
                   5163:         $env{"form.scantron.responsetype.$line"} =
                   5164:             $responsetype_per_response{$line};
1.495     albertel 5165:     }
1.691     raeburn  5166:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5167:         my $line = $masterseq_id_responsenum{$resid};
                   5168:         $env{"form.scantron.residpart.$line"} = $resid;
                   5169:     }
1.495     albertel 5170: }
                   5171: 
                   5172: 
                   5173: sub restore_bubble_lines {
                   5174:     my $line = 0;
                   5175:     %bubble_lines_per_response = ();
1.691     raeburn  5176:     %masterseq_id_responsenum = ();
1.495     albertel 5177:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5178: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5179: 	$bubble_lines_per_response{$line} = $value;
                   5180: 	$first_bubble_line{$line}  =
                   5181: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5182:         $subdivided_bubble_lines{$line} =
                   5183:             $env{"form.scantron.sub_bubblelines.$line"};
                   5184:         $responsetype_per_response{$line} =
                   5185:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5186:         my $id = $env{"form.scantron.residpart.$line"};
                   5187:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5188: 	$line++;
                   5189:     }
                   5190: }
                   5191: 
1.423     albertel 5192: =pod 
                   5193: 
                   5194: =item scantron_filenames
                   5195: 
                   5196:    Returns a list of the scantron files in the current course 
                   5197: 
                   5198: =cut
1.422     foxr     5199: 
1.202     albertel 5200: sub scantron_filenames {
1.257     albertel 5201:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5202:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5203:     my $getpropath = 1;
1.662     raeburn  5204:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5205:                                                         $cname,$getpropath);
1.202     albertel 5206:     my @possiblenames;
1.662     raeburn  5207:     if (ref($dirlist) eq 'ARRAY') {
                   5208:         foreach my $filename (sort(@{$dirlist})) {
                   5209: 	    ($filename)=split(/&/,$filename);
                   5210: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5211: 	    $filename=~s/^scantron_orig_//;
                   5212: 	    push(@possiblenames,$filename);
                   5213:         }
1.202     albertel 5214:     }
                   5215:     return @possiblenames;
                   5216: }
                   5217: 
1.423     albertel 5218: =pod 
                   5219: 
                   5220: =item scantron_uploads
                   5221: 
                   5222:    Returns  html drop-down list of scantron files in current course.
                   5223: 
                   5224:  Arguments:
                   5225:    $file2grade - filename to set as selected in the dropdown
                   5226: 
                   5227: =cut
1.422     foxr     5228: 
1.202     albertel 5229: sub scantron_uploads {
1.209     ng       5230:     my ($file2grade) = @_;
1.202     albertel 5231:     my $result=	'<select name="scantron_selectfile">';
                   5232:     $result.="<option></option>";
                   5233:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5234: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5235:     }
                   5236:     $result.="</select>";
                   5237:     return $result;
                   5238: }
                   5239: 
1.423     albertel 5240: =pod 
                   5241: 
                   5242: =item scantron_scantab
                   5243: 
                   5244:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5245:   file.
                   5246: 
                   5247: =cut
1.422     foxr     5248: 
1.82      albertel 5249: sub scantron_scantab {
                   5250:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5251:     $result.='<option></option>'."\n";
1.518     raeburn  5252:     my @lines = &get_scantronformat_file();
                   5253:     if (@lines > 0) {
                   5254:         foreach my $line (@lines) {
                   5255:             next if (($line =~ /^\#/) || ($line eq ''));
                   5256: 	    my ($name,$descrip)=split(/:/,$line);
                   5257: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5258:         }
1.82      albertel 5259:     }
                   5260:     $result.='</select>'."\n";
1.518     raeburn  5261:     return $result;
                   5262: }
                   5263: 
                   5264: =pod
                   5265: 
                   5266: =item get_scantronformat_file
                   5267: 
                   5268:   Returns an array containing lines from the scantron format file for
                   5269:   the domain of the course.
                   5270: 
                   5271:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5272:   lines are from this file.
                   5273: 
                   5274:   Otherwise, if a default.tab has been published in RES space by the 
                   5275:   domainconfig user, lines are from this file.
                   5276: 
                   5277:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5278:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5279: 
1.518     raeburn  5280: =cut
                   5281: 
                   5282: sub get_scantronformat_file {
                   5283:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5284:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5285:     my $gottab = 0;
                   5286:     my @lines;
                   5287:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5288:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5289:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5290:             if ($formatfile ne '-1') {
                   5291:                 @lines = split("\n",$formatfile,-1);
                   5292:                 $gottab = 1;
                   5293:             }
                   5294:         }
                   5295:     }
                   5296:     if (!$gottab) {
                   5297:         my $confname = $cdom.'-domainconfig';
                   5298:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5299:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5300:         if ($formatfile ne '-1') {
                   5301:             @lines = split("\n",$formatfile,-1);
                   5302:             $gottab = 1;
                   5303:         }
                   5304:     }
                   5305:     if (!$gottab) {
1.519     raeburn  5306:         my @domains = &Apache::lonnet::current_machine_domains();
                   5307:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5308:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5309:             @lines = <$fh>;
                   5310:             close($fh);
                   5311:         } else {
                   5312:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5313:             @lines = <$fh>;
                   5314:             close($fh);
                   5315:         }
1.518     raeburn  5316:     }
                   5317:     return @lines;
1.82      albertel 5318: }
                   5319: 
1.423     albertel 5320: =pod 
                   5321: 
                   5322: =item scantron_CODElist
                   5323: 
                   5324:   Returns html drop down of the saved CODE lists from current course,
                   5325:   generated from earlier printings.
                   5326: 
                   5327: =cut
1.422     foxr     5328: 
1.186     albertel 5329: sub scantron_CODElist {
1.257     albertel 5330:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5331:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5332:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5333:     my $namechoice='<option></option>';
1.225     albertel 5334:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5335: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5336: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5337: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5338:     }
                   5339:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5340:     return $namechoice;
                   5341: }
                   5342: 
1.423     albertel 5343: =pod 
                   5344: 
                   5345: =item scantron_CODEunique
                   5346: 
                   5347:   Returns the html for "Each CODE to be used once" radio.
                   5348: 
                   5349: =cut
1.422     foxr     5350: 
1.186     albertel 5351: sub scantron_CODEunique {
1.532     bisitz   5352:     my $result='<span class="LC_nobreak">
1.272     albertel 5353:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5354:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5355:                 </span>
1.532     bisitz   5356:                 <span class="LC_nobreak">
1.272     albertel 5357:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5358:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5359:                 </span>';
1.186     albertel 5360:     return $result;
                   5361: }
1.423     albertel 5362: 
                   5363: =pod 
                   5364: 
                   5365: =item scantron_selectphase
                   5366: 
1.659     raeburn  5367:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5368:   Allows for - starting a grading run.
1.424     albertel 5369:              - downloading existing scan data (original, corrected
1.423     albertel 5370:                                                 or skipped info)
                   5371: 
                   5372:              - uploading new scan data
                   5373: 
                   5374:  Arguments:
                   5375:   $r          - The Apache request object
                   5376:   $file2grade - name of the file that contain the scanned data to score
                   5377: 
                   5378: =cut
1.186     albertel 5379: 
1.75      albertel 5380: sub scantron_selectphase {
1.608     www      5381:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5382:     if (!$symb) {return '';}
1.582     raeburn  5383:     my $map_error;
                   5384:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5385:     if ($map_error) {
                   5386:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5387:         return;
                   5388:     }
1.324     albertel 5389:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5390:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5391:     my $format_selector=&scantron_scantab();
1.186     albertel 5392:     my $CODE_selector=&scantron_CODElist();
                   5393:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5394:     my $result;
1.422     foxr     5395: 
1.513     foxr     5396:     $ssi_error = 0;
                   5397: 
1.606     wenzelju 5398:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5399:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5400: 
                   5401: 	# Chunk of form to prompt for a scantron file upload.
                   5402: 
                   5403:         $r->print('
                   5404:     <br />
                   5405:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5406:        '.&Apache::loncommon::start_data_table_header_row().'
                   5407:             <th>
                   5408:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5409:             </th>
                   5410:        '.&Apache::loncommon::end_data_table_header_row().'
                   5411:        '.&Apache::loncommon::start_data_table_row().'
                   5412:             <td>
                   5413: ');
1.608     www      5414:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5415:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5416:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5417:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5418:     function checkUpload(formname) {
                   5419: 	if (formname.upfile.value == "") {
                   5420: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5421: 	    return false;
                   5422: 	}
                   5423: 	formname.submit();
                   5424:     }'));
                   5425:     $r->print('
                   5426:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5427:                 '.$default_form_data.'
                   5428:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5429:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5430:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5431:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5432:                 <br />
                   5433:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5434:               </form>
                   5435: ');
                   5436: 
                   5437:         $r->print('
                   5438:             </td>
                   5439:        '.&Apache::loncommon::end_data_table_row().'
                   5440:        '.&Apache::loncommon::end_data_table().'
                   5441: ');
                   5442:     }
                   5443: 
1.422     foxr     5444:     # Chunk of form to prompt for a file to grade and how:
                   5445: 
1.489     albertel 5446:     $result.= '
                   5447:     <br />
                   5448:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5449:     <input type="hidden" name="command" value="scantron_warning" />
                   5450:     '.$default_form_data.'
                   5451:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5452:        '.&Apache::loncommon::start_data_table_header_row().'
                   5453:             <th colspan="2">
1.492     albertel 5454:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5455:             </th>
                   5456:        '.&Apache::loncommon::end_data_table_header_row().'
                   5457:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5458:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5459:        '.&Apache::loncommon::end_data_table_row().'
                   5460:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5461:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5462:        '.&Apache::loncommon::end_data_table_row().'
                   5463:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5464:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5465:        '.&Apache::loncommon::end_data_table_row().'
                   5466:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5467:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5468:        '.&Apache::loncommon::end_data_table_row().'
                   5469:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5470:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5471:        '.&Apache::loncommon::end_data_table_row().'
                   5472:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5473: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5474:             <td>
1.492     albertel 5475: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5476:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5477:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5478: 	    </td>
1.489     albertel 5479:        '.&Apache::loncommon::end_data_table_row().'
                   5480:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5481:             <td colspan="2">
1.572     www      5482:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5483:             </td>
1.489     albertel 5484:        '.&Apache::loncommon::end_data_table_row().'
                   5485:     '.&Apache::loncommon::end_data_table().'
                   5486:     </form>
                   5487: ';
1.162     albertel 5488:    
                   5489:     $r->print($result);
                   5490: 
1.422     foxr     5491: 
                   5492: 
                   5493:     # Chunk of the form that prompts to view a scoring office file,
                   5494:     # corrected file, skipped records in a file.
                   5495: 
1.489     albertel 5496:     $r->print('
                   5497:    <br />
                   5498:    <form action="/adm/grades" name="scantron_download">
                   5499:      '.$default_form_data.'
                   5500:      <input type="hidden" name="command" value="scantron_download" />
                   5501:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5502:        '.&Apache::loncommon::start_data_table_header_row().'
                   5503:               <th>
1.492     albertel 5504:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5505:               </th>
                   5506:        '.&Apache::loncommon::end_data_table_header_row().'
                   5507:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5508:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5509:                 <br />
1.492     albertel 5510:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5511:        '.&Apache::loncommon::end_data_table_row().'
                   5512:      '.&Apache::loncommon::end_data_table().'
                   5513:    </form>
                   5514:    <br />
                   5515: ');
1.162     albertel 5516: 
1.457     banghart 5517:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5518: 
1.694     bisitz   5519:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5520:              $default_form_data."\n".
                   5521:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5522:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5523:              '<th colspan="2">
1.572     www      5524:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5525:              '</th>'."\n".
                   5526:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5527:               &Apache::loncommon::start_data_table_row()."\n".
                   5528:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5529:               '<td> '.$sequence_selector.' </td>'.
                   5530:               &Apache::loncommon::end_data_table_row()."\n".
                   5531:               &Apache::loncommon::start_data_table_row()."\n".
                   5532:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5533:               '<td> '.$file_selector.' </td>'."\n".
                   5534:               &Apache::loncommon::end_data_table_row()."\n".
                   5535:               &Apache::loncommon::start_data_table_row()."\n".
                   5536:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5537:               '<td> '.$format_selector.' </td>'."\n".
                   5538:               &Apache::loncommon::end_data_table_row()."\n".
                   5539:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5540:               '<td> '.&mt('Options').' </td>'."\n".
                   5541:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5542:               &Apache::loncommon::end_data_table_row()."\n".
                   5543:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5544:               '<td colspan="2">'."\n".
                   5545:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5546:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5547:               '</td>'."\n".
                   5548:               &Apache::loncommon::end_data_table_row()."\n".
                   5549:               &Apache::loncommon::end_data_table()."\n".
                   5550:               '</form><br />');
                   5551:     return;
1.75      albertel 5552: }
                   5553: 
1.423     albertel 5554: =pod
                   5555: 
                   5556: =item get_scantron_config
                   5557: 
                   5558:    Parse and return the scantron configuration line selected as a
                   5559:    hash of configuration file fields.
                   5560: 
                   5561:  Arguments:
                   5562:     which - the name of the configuration to parse from the file.
                   5563: 
                   5564: 
                   5565:  Returns:
                   5566:             If the named configuration is not in the file, an empty
                   5567:             hash is returned.
                   5568:     a hash with the fields
                   5569:       name         - internal name for the this configuration setup
                   5570:       description  - text to display to operator that describes this config
                   5571:       CODElocation - if 0 or the string 'none'
                   5572:                           - no CODE exists for this config
                   5573:                      if -1 || the string 'letter'
                   5574:                           - a CODE exists for this config and is
                   5575:                             a string of letters
                   5576:                      Unsupported value (but planned for future support)
                   5577:                           if a positive integer
                   5578:                                - The CODE exists as the first n items from
                   5579:                                  the question section of the form
                   5580:                           if the string 'number'
                   5581:                                - The CODE exists for this config and is
                   5582:                                  a string of numbers
                   5583:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5584:                      the CODE starts
                   5585:       CODElength  - length of the CODE
1.573     bisitz   5586:       IDstart     - column where the student/employee ID starts
1.556     weissno  5587:       IDlength    - length of the student/employee ID info
1.423     albertel 5588:       Qstart      - column where the information from the bubbled
                   5589:                     'questions' start
                   5590:       Qlength     - number of columns comprising a single bubble line from
                   5591:                     the sheet. (usually either 1 or 10)
1.424     albertel 5592:       Qon         - either a single character representing the character used
1.423     albertel 5593:                     to signal a bubble was chosen in the positional setup, or
                   5594:                     the string 'letter' if the letter of the chosen bubble is
                   5595:                     in the final, or 'number' if a number representing the
                   5596:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5597:       Qoff        - the character used to represent that a bubble was
                   5598:                     left blank
1.423     albertel 5599:       PaperID     - if the scanning process generates a unique number for each
                   5600:                     sheet scanned the column that this ID number starts in
                   5601:       PaperIDlength - number of columns that comprise the unique ID number
                   5602:                       for the sheet of paper
1.424     albertel 5603:       FirstName   - column that the first name starts in
1.423     albertel 5604:       FirstNameLength - number of columns that the first name spans
                   5605:  
                   5606:       LastName    - column that the last name starts in
                   5607:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5608:       BubblesPerRow - number of bubbles available in each row used to 
                   5609:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5610: 
1.423     albertel 5611: =cut
1.422     foxr     5612: 
1.82      albertel 5613: sub get_scantron_config {
                   5614:     my ($which) = @_;
1.518     raeburn  5615:     my @lines = &get_scantronformat_file();
1.82      albertel 5616:     my %config;
1.157     albertel 5617:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5618:     foreach my $line (@lines) {
1.82      albertel 5619: 	my ($name,$descrip)=split(/:/,$line);
                   5620: 	if ($name ne $which ) { next; }
                   5621: 	chomp($line);
                   5622: 	my @config=split(/:/,$line);
                   5623: 	$config{'name'}=$config[0];
                   5624: 	$config{'description'}=$config[1];
                   5625: 	$config{'CODElocation'}=$config[2];
                   5626: 	$config{'CODEstart'}=$config[3];
                   5627: 	$config{'CODElength'}=$config[4];
                   5628: 	$config{'IDstart'}=$config[5];
                   5629: 	$config{'IDlength'}=$config[6];
                   5630: 	$config{'Qstart'}=$config[7];
1.497     foxr     5631:  	$config{'Qlength'}=$config[8];
1.82      albertel 5632: 	$config{'Qoff'}=$config[9];
                   5633: 	$config{'Qon'}=$config[10];
1.157     albertel 5634: 	$config{'PaperID'}=$config[11];
                   5635: 	$config{'PaperIDlength'}=$config[12];
                   5636: 	$config{'FirstName'}=$config[13];
                   5637: 	$config{'FirstNamelength'}=$config[14];
                   5638: 	$config{'LastName'}=$config[15];
                   5639: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5640:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5641: 	last;
                   5642:     }
                   5643:     return %config;
                   5644: }
                   5645: 
1.423     albertel 5646: =pod 
                   5647: 
                   5648: =item username_to_idmap
                   5649: 
1.556     weissno  5650:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5651:     student username:domain.
                   5652: 
                   5653:   Arguments:
                   5654: 
                   5655:     $classlist - reference to the class list hash. This is a hash
                   5656:                  keyed by student name:domain  whose elements are references
1.424     albertel 5657:                  to arrays containing various chunks of information
1.423     albertel 5658:                  about the student. (See loncoursedata for more info).
                   5659: 
                   5660:   Returns
                   5661:     %idmap - the constructed hash
                   5662: 
                   5663: =cut
                   5664: 
1.82      albertel 5665: sub username_to_idmap {
                   5666:     my ($classlist)= @_;
                   5667:     my %idmap;
                   5668:     foreach my $student (keys(%$classlist)) {
                   5669: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5670: 	    $student;
                   5671:     }
                   5672:     return %idmap;
                   5673: }
1.423     albertel 5674: 
                   5675: =pod
                   5676: 
1.424     albertel 5677: =item scantron_fixup_scanline
1.423     albertel 5678: 
                   5679:    Process a requested correction to a scanline.
                   5680: 
                   5681:   Arguments:
                   5682:     $scantron_config   - hash from &get_scantron_config()
                   5683:     $scan_data         - hash of correction information 
                   5684:                           (see &scantron_getfile())
                   5685:     $line              - existing scanline
                   5686:     $whichline         - line number of the passed in scanline
                   5687:     $field             - type of change to process 
                   5688:                          (either 
1.573     bisitz   5689:                           'ID'     -> correct the student/employee ID
1.423     albertel 5690:                           'CODE'   -> correct the CODE
                   5691:                           'answer' -> fixup the submitted answers)
                   5692:     
                   5693:    $args               - hash of additional info,
                   5694:                           - 'ID' 
                   5695:                                'newid' -> studentID to use in replacement
1.424     albertel 5696:                                           of existing one
1.423     albertel 5697:                           - 'CODE' 
                   5698:                                'CODE_ignore_dup' - set to true if duplicates
                   5699:                                                    should be ignored.
                   5700: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5701:                                         if the existing unfound code should
1.423     albertel 5702:                                         be used as is
                   5703:                           - 'answer'
                   5704:                                'response' - new answer or 'none' if blank
                   5705:                                'question' - the bubble line to change
1.503     raeburn  5706:                                'questionnum' - the question identifier,
                   5707:                                                may include subquestion. 
1.423     albertel 5708: 
                   5709:   Returns:
                   5710:     $line - the modified scanline
                   5711: 
                   5712:   Side effects: 
                   5713:     $scan_data - may be updated
                   5714: 
                   5715: =cut
                   5716: 
1.82      albertel 5717: 
1.157     albertel 5718: sub scantron_fixup_scanline {
                   5719:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5720:     if ($field eq 'ID') {
                   5721: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5722: 	    return ($line,1,'New value too large');
1.157     albertel 5723: 	}
                   5724: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5725: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5726: 				     $args->{'newid'});
                   5727: 	}
                   5728: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5729: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5730: 	if ($args->{'newid'}=~/^\s*$/) {
                   5731: 	    &scan_data($scan_data,"$whichline.user",
                   5732: 		       $args->{'username'}.':'.$args->{'domain'});
                   5733: 	}
1.186     albertel 5734:     } elsif ($field eq 'CODE') {
1.192     albertel 5735: 	if ($args->{'CODE_ignore_dup'}) {
                   5736: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5737: 	}
                   5738: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5739: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5740: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5741: 		return ($line,1,'New CODE value too large');
                   5742: 	    }
                   5743: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5744: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5745: 	    }
                   5746: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5747: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5748: 	}
1.157     albertel 5749:     } elsif ($field eq 'answer') {
1.497     foxr     5750: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5751: 	my $off=$scantron_config->{'Qoff'};
                   5752: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5753: 	my $answer=${off}x$length;
                   5754: 	if ($args->{'response'} eq 'none') {
                   5755: 	    &scan_data($scan_data,
1.503     raeburn  5756: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5757: 	} else {
                   5758: 	    if ($on eq 'letter') {
                   5759: 		my @alphabet=('A'..'Z');
                   5760: 		$answer=$alphabet[$args->{'response'}];
                   5761: 	    } elsif ($on eq 'number') {
                   5762: 		$answer=$args->{'response'}+1;
                   5763: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5764: 	    } else {
1.497     foxr     5765: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5766: 	    }
1.497     foxr     5767: 	    &scan_data($scan_data,
1.503     raeburn  5768: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5769: 	}
1.497     foxr     5770: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5771: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5772:     }
                   5773:     return $line;
                   5774: }
1.423     albertel 5775: 
                   5776: =pod
                   5777: 
                   5778: =item scan_data
                   5779: 
                   5780:     Edit or look up  an item in the scan_data hash.
                   5781: 
                   5782:   Arguments:
                   5783:     $scan_data  - The hash (see scantron_getfile)
                   5784:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5785:                   scantronfilename_key).
1.423     albertel 5786:     $data        - New value of the hash entry.
                   5787:     $delete      - If true, the entry is removed from the hash.
                   5788: 
                   5789:   Returns:
                   5790:     The new value of the hash table field (undefined if deleted).
                   5791: 
                   5792: =cut
                   5793: 
                   5794: 
1.157     albertel 5795: sub scan_data {
                   5796:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5797:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5798:     if (defined($value)) {
                   5799: 	$scan_data->{$filename.'_'.$key} = $value;
                   5800:     }
                   5801:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5802:     return $scan_data->{$filename.'_'.$key};
                   5803: }
1.423     albertel 5804: 
1.495     albertel 5805: # ----- These first few routines are general use routines.----
                   5806: 
                   5807: # Return the number of occurences of a pattern in a string.
                   5808: 
                   5809: sub occurence_count {
                   5810:     my ($string, $pattern) = @_;
                   5811: 
                   5812:     my @matches = ($string =~ /$pattern/g);
                   5813: 
                   5814:     return scalar(@matches);
                   5815: }
                   5816: 
                   5817: 
                   5818: # Take a string known to have digits and convert all the
                   5819: # digits into letters in the range J,A..I.
                   5820: 
                   5821: sub digits_to_letters {
                   5822:     my ($input) = @_;
                   5823: 
                   5824:     my @alphabet = ('J', 'A'..'I');
                   5825: 
                   5826:     my @input    = split(//, $input);
                   5827:     my $output ='';
                   5828:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5829: 	if ($input[$i] =~ /\d/) {
                   5830: 	    $output .= $alphabet[$input[$i]];
                   5831: 	} else {
                   5832: 	    $output .= $input[$i];
                   5833: 	}
                   5834:     }
                   5835:     return $output;
                   5836: }
                   5837: 
1.423     albertel 5838: =pod 
                   5839: 
                   5840: =item scantron_parse_scanline
                   5841: 
                   5842:   Decodes a scanline from the selected scantron file
                   5843: 
                   5844:  Arguments:
                   5845:     line             - The text of the scantron file line to process
                   5846:     whichline        - Line number
                   5847:     scantron_config  - Hash describing the format of the scantron lines.
                   5848:     scan_data        - Hash of extra information about the scanline
                   5849:                        (see scantron_getfile for more information)
                   5850:     just_header      - True if should not process question answers but only
                   5851:                        the stuff to the left of the answers.
1.691     raeburn  5852:     randomorder      - True if randomorder in use
                   5853:     randompick       - True if randompick in use
                   5854:     sequence         - Exam folder URL
                   5855:     master_seq       - Ref to array containing symbs in exam folder
                   5856:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5857:                        (corresponding values are resource objects)
                   5858:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5859:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5860:                        are refs to an array of resource objects, ordered
                   5861:                        according to order used for CODE, when randomorder
                   5862:                        and or randompick are in use.
                   5863:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5864:                        for current line to question number used for same question
                   5865:                         in "Master Sequence" (as seen by Course Coordinator).
                   5866:     startline        - Ref to hash where key is question number (0 is first)
                   5867:                        and value is number of first bubble line for current 
                   5868:                        student or code-based randompick and/or randomorder.
                   5869:     totalref         - Ref of scalar used to score total number of bubble
                   5870:                        lines needed for responses in a scan line (used when
                   5871:                        randompick in use. 
                   5872:     
1.423     albertel 5873:  Returns:
                   5874:    Hash containing the result of parsing the scanline
                   5875: 
                   5876:    Keys are all proceeded by the string 'scantron.'
                   5877: 
                   5878:        CODE    - the CODE in use for this scanline
                   5879:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5880:                  by the operator
                   5881:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5882:                             CODEs were selected, but the usage has been
                   5883:                             forced by the operator
1.556     weissno  5884:        ID  - student/employee ID
1.423     albertel 5885:        PaperID - if used, the ID number printed on the sheet when the 
                   5886:                  paper was scanned
                   5887:        FirstName - first name from the sheet
                   5888:        LastName  - last name from the sheet
                   5889: 
                   5890:      if just_header was not true these key may also exist
                   5891: 
1.447     foxr     5892:        missingerror - a list of bubble ranges that are considered to be answers
                   5893:                       to a single question that don't have any bubbles filled in.
                   5894:                       Of the form questionnumber:firstbubblenumber:count.
                   5895:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5896:                       to a single question that have more than one bubble filled in.
                   5897:                       Of the form questionnumber::firstbubblenumber:count
                   5898:    
                   5899:                 In the above, count is the number of bubble responses in the
                   5900:                 input line needed to represent the possible answers to the question.
                   5901:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5902:                 per line would have count = 2.
                   5903: 
1.423     albertel 5904:        maxquest     - the number of the last bubble line that was parsed
                   5905: 
                   5906:        (<number> starts at 1)
                   5907:        <number>.answer - zero or more letters representing the selected
                   5908:                          letters from the scanline for the bubble line 
                   5909:                          <number>.
                   5910:                          if blank there was either no bubble or there where
                   5911:                          multiple bubbles, (consult the keys missingerror and
                   5912:                          doubleerror if this is an error condition)
                   5913: 
                   5914: =cut
                   5915: 
1.82      albertel 5916: sub scantron_parse_scanline {
1.691     raeburn  5917:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5918:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5919:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5920: 
1.82      albertel 5921:     my %record;
1.691     raeburn  5922:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 5923:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5924: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5925: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5926: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5927: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5928: 	    $record{'scantron.CODE'}=substr($data,
                   5929: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5930: 					    $$scantron_config{'CODElength'});
1.191     albertel 5931: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5932: 		$record{'scantron.useCODE'}=1;
                   5933: 	    }
1.192     albertel 5934: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5935: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5936: 	    }
1.82      albertel 5937: 	} else {
                   5938: 	    #FIXME interpret first N questions
                   5939: 	}
                   5940:     }
1.83      albertel 5941:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5942: 				  $$scantron_config{'IDlength'});
1.157     albertel 5943:     $record{'scantron.PaperID'}=
                   5944: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5945: 	       $$scantron_config{'PaperIDlength'});
                   5946:     $record{'scantron.FirstName'}=
                   5947: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5948: 	       $$scantron_config{'FirstNamelength'});
                   5949:     $record{'scantron.LastName'}=
                   5950: 	substr($data,$$scantron_config{'LastName'}-1,
                   5951: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5952:     if ($just_header) { return \%record; }
1.194     albertel 5953: 
1.82      albertel 5954:     my @alphabet=('A'..'Z');
                   5955:     my $questnum=0;
1.447     foxr     5956:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5957: 
1.691     raeburn  5958:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5959:     if ($randompick || $randomorder) {
                   5960:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   5961:                                          $master_seq,$symb_to_resource,
                   5962:                                          $partids_by_symb,$orderedforcode,
                   5963:                                          $respnumlookup,$startline);
                   5964:         if ($total) {
                   5965:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   5966:         }
                   5967:         if (ref($totalref)) {
                   5968:             $$totalref = $total;
                   5969:         }
                   5970:     }
                   5971:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     5972:     chomp($questions);		# Get rid of any trailing \n.
                   5973:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5974:     while (length($questions)) {
1.691     raeburn  5975:         my $answers_needed;
                   5976:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   5977:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   5978:         } else {
                   5979: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   5980:         }
1.503     raeburn  5981:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5982:                              || 1;
                   5983:         $questnum++;
                   5984:         my $quest_id = $questnum;
                   5985:         my $currentquest = substr($questions,0,$answer_length);
                   5986:         $questions       = substr($questions,$answer_length);
                   5987:         if (length($currentquest) < $answer_length) { next; }
                   5988: 
1.691     raeburn  5989:         my $subdivided;
                   5990:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   5991:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   5992:         } else {
                   5993:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   5994:         }
                   5995:         if ($subdivided =~ /,/) {
1.503     raeburn  5996:             my $subquestnum = 1;
                   5997:             my $subquestions = $currentquest;
1.691     raeburn  5998:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  5999:             foreach my $subans (@subanswers_needed) {
                   6000:                 my $subans_length =
                   6001:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6002:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6003:                 $subquestions   = substr($subquestions,$subans_length);
                   6004:                 $quest_id = "$questnum.$subquestnum";
                   6005:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6006:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6007:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6008:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6009:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6010:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6011:                 } else {
                   6012:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6013:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6014:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6015:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6016:                 }
                   6017:                 $subquestnum ++;
                   6018:             }
                   6019:         } else {
                   6020:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6021:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6022:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6023:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6024:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6025:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6026:             } else {
                   6027:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6028:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6029:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6030:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6031:             }
                   6032:         }
                   6033:     }
                   6034:     $record{'scantron.maxquest'}=$questnum;
                   6035:     return \%record;
                   6036: }
1.447     foxr     6037: 
1.691     raeburn  6038: sub get_master_seq {
                   6039:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6040:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6041:                    (ref($symb_to_resource) eq 'HASH'));
                   6042:     my $resource_error;
                   6043:     foreach my $resource (@{$resources}) {
                   6044:         my $ressymb;
                   6045:         if (ref($resource)) {
                   6046:             $ressymb = $resource->symb();
                   6047:             push(@{$master_seq},$ressymb);
                   6048:             $symb_to_resource->{$ressymb} = $resource;
                   6049:         } else {
                   6050:             $resource_error = 1;
                   6051:             last;
                   6052:         }
                   6053:     }
                   6054:     return $resource_error;
                   6055: }
                   6056: 
                   6057: sub get_respnum_lookups {
                   6058:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6059:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6060:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6061:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6062:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6063:                    (ref($startline) eq 'HASH'));
                   6064:     my ($user,$scancode);
                   6065:     if ((exists($record->{'scantron.CODE'})) &&
                   6066:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6067:         $scancode = $record->{'scantron.CODE'};
                   6068:     } else {
                   6069:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6070:     }
                   6071:     my @mapresources =
                   6072:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6073:                      $orderedforcode);
                   6074:     my $total = 0;
                   6075:     my $count = 0;
                   6076:     foreach my $resource (@mapresources) {
                   6077:         my $id = $resource->id();
                   6078:         my $symb = $resource->symb();
                   6079:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6080:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6081:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6082:                 if ($respnum ne '') {
                   6083:                     $respnumlookup->{$count} = $respnum;
                   6084:                     $startline->{$count} = $total;
                   6085:                     $total += $bubble_lines_per_response{$respnum};
                   6086:                     $count ++;
                   6087:                 }
                   6088:             }
                   6089:         }
                   6090:     }
                   6091:     return $total;
                   6092: }
                   6093: 
1.503     raeburn  6094: sub scantron_validator_lettnum {
                   6095:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6096:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6097:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6098: 
                   6099:     # Qon 'letter' implies for each slot in currquest we have:
                   6100:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6101:     #    about anything else (esp. a value of Qoff) for missing
                   6102:     #    bubbles.
                   6103:     #
                   6104:     # Qon 'number' implies each slot gives a digit that indexes the
                   6105:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6106:     #    and * or ? for double bubbles on a single line.
                   6107:     #
1.447     foxr     6108: 
1.503     raeburn  6109:     my $matchon;
                   6110:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6111:         $matchon = '[A-Z]';
                   6112:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6113:         $matchon = '\d';
                   6114:     }
                   6115:     my $occurrences = 0;
1.691     raeburn  6116:     my $responsenum = $questnum-1;
                   6117:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6118:        $responsenum = $respnumlookup->{$questnum-1} 
                   6119:     }
                   6120:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6121:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6122:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6123:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6124:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6125:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6126:         my @singlelines = split('',$currquest);
                   6127:         foreach my $entry (@singlelines) {
                   6128:             $occurrences = &occurence_count($entry,$matchon);
                   6129:             if ($occurrences > 1) {
                   6130:                 last;
                   6131:             }
1.691     raeburn  6132:         }
1.503     raeburn  6133:     } else {
                   6134:         $occurrences = &occurence_count($currquest,$matchon); 
                   6135:     }
                   6136:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6137:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6138:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6139:             my $bubble = substr($currquest,$ans,1);
                   6140:             if ($bubble =~ /$matchon/ ) {
                   6141:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6142:                     if ($bubble == 0) {
                   6143:                         $bubble = 10; 
                   6144:                     }
                   6145:                     $record->{"scantron.$ansnum.answer"} = 
                   6146:                         $alphabet->[$bubble-1];
                   6147:                 } else {
                   6148:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6149:                 }
                   6150:             } else {
                   6151:                 $record->{"scantron.$ansnum.answer"}='';
                   6152:             }
                   6153:             $ansnum++;
                   6154:         }
                   6155:     } elsif (!defined($currquest)
                   6156:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6157:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6158:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6159:             $record->{"scantron.$ansnum.answer"}='';
                   6160:             $ansnum++;
                   6161:         }
                   6162:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6163:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6164:         }
                   6165:     } else {
                   6166:         if ($$scantron_config{'Qon'} eq 'number') {
                   6167:             $currquest = &digits_to_letters($currquest);            
                   6168:         }
                   6169:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6170:             my $bubble = substr($currquest,$ans,1);
                   6171:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6172:             $ansnum++;
                   6173:         }
                   6174:     }
                   6175:     return $ansnum;
                   6176: }
1.447     foxr     6177: 
1.503     raeburn  6178: sub scantron_validator_positional {
                   6179:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6180:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6181:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6182: 
1.503     raeburn  6183:     # Otherwise there's a positional notation;
                   6184:     # each bubble line requires Qlength items, and there are filled in
                   6185:     # bubbles for each case where there 'Qon' characters.
                   6186:     #
1.447     foxr     6187: 
1.503     raeburn  6188:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6189: 
1.503     raeburn  6190:     # If the split only gives us one element.. the full length of the
                   6191:     # answer string, no bubbles are filled in:
1.447     foxr     6192: 
1.507     raeburn  6193:     if ($answers_needed eq '') {
                   6194:         return;
                   6195:     }
                   6196: 
1.503     raeburn  6197:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6198:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6199:             $record->{"scantron.$ansnum.answer"}='';
                   6200:             $ansnum++;
                   6201:         }
                   6202:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6203:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6204:         }
                   6205:     } elsif (scalar(@array) == 2) {
                   6206:         my $location = length($array[0]);
                   6207:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6208:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6209:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6210:             if ($ans eq $line_num) {
                   6211:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6212:             } else {
                   6213:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6214:             }
                   6215:             $ansnum++;
                   6216:          }
                   6217:     } else {
                   6218:         #  If there's more than one instance of a bubble character
                   6219:         #  That's a double bubble; with positional notation we can
                   6220:         #  record all the bubbles filled in as well as the
                   6221:         #  fact this response consists of multiple bubbles.
                   6222:         #
1.691     raeburn  6223:         my $responsenum = $questnum-1;
                   6224:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6225:             $responsenum = $respnumlookup->{$questnum-1}
                   6226:         }
                   6227:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6228:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6229:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6230:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6231:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6232:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6233:             my $doubleerror = 0;
                   6234:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6235:                    (!$doubleerror)) {
                   6236:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6237:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6238:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6239:                if (length(@currarray) > 2) {
                   6240:                    $doubleerror = 1;
                   6241:                } 
                   6242:             }
                   6243:             if ($doubleerror) {
                   6244:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6245:             }
                   6246:         } else {
                   6247:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6248:         }
                   6249:         my $item = $ansnum;
                   6250:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6251:             $record->{"scantron.$item.answer"} = '';
                   6252:             $item ++;
                   6253:         }
1.447     foxr     6254: 
1.503     raeburn  6255:         my @ans=@array;
                   6256:         my $i=0;
                   6257:         my $increment = 0;
                   6258:         while ($#ans) {
                   6259:             $i+=length($ans[0]) + $increment;
                   6260:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6261:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6262:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6263:             shift(@ans);
                   6264:             $increment = 1;
                   6265:         }
                   6266:         $ansnum += $answers_needed;
1.82      albertel 6267:     }
1.503     raeburn  6268:     return $ansnum;
1.82      albertel 6269: }
                   6270: 
1.423     albertel 6271: =pod
                   6272: 
                   6273: =item scantron_add_delay
                   6274: 
                   6275:    Adds an error message that occurred during the grading phase to a
                   6276:    queue of messages to be shown after grading pass is complete
                   6277: 
                   6278:  Arguments:
1.424     albertel 6279:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6280:    $scanline    - the scanline that caused the error
                   6281:    $errormesage - the error message
                   6282:    $errorcode   - a numeric code for the error
                   6283: 
                   6284:  Side Effects:
1.424     albertel 6285:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6286: 
                   6287: =cut
                   6288: 
1.82      albertel 6289: sub scantron_add_delay {
1.140     albertel 6290:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6291:     push(@$delayqueue,
                   6292: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6293: 	  'ecode' => $errorcode }
                   6294: 	 );
1.82      albertel 6295: }
                   6296: 
1.423     albertel 6297: =pod
                   6298: 
                   6299: =item scantron_find_student
                   6300: 
1.424     albertel 6301:    Finds the username for the current scanline
                   6302: 
                   6303:   Arguments:
                   6304:    $scantron_record - hash result from scantron_parse_scanline
                   6305:    $scan_data       - hash of correction information 
                   6306:                       (see &scantron_getfile() form more information)
                   6307:    $idmap           - hash from &username_to_idmap()
                   6308:    $line            - number of current scanline
                   6309:  
                   6310:   Returns:
                   6311:    Either 'username:domain' or undef if unknown
                   6312: 
1.423     albertel 6313: =cut
                   6314: 
1.82      albertel 6315: sub scantron_find_student {
1.157     albertel 6316:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6317:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6318:     if ($scanID =~ /^\s*$/) {
                   6319:  	return &scan_data($scan_data,"$line.user");
                   6320:     }
1.83      albertel 6321:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6322:  	if (lc($id) eq lc($scanID)) {
                   6323:  	    return $$idmap{$id};
                   6324:  	}
1.83      albertel 6325:     }
                   6326:     return undef;
                   6327: }
                   6328: 
1.423     albertel 6329: =pod
                   6330: 
                   6331: =item scantron_filter
                   6332: 
1.424     albertel 6333:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6334:    hidden resources was selected
                   6335: 
1.423     albertel 6336: =cut
                   6337: 
1.83      albertel 6338: sub scantron_filter {
                   6339:     my ($curres)=@_;
1.331     albertel 6340: 
                   6341:     if (ref($curres) && $curres->is_problem()) {
                   6342: 	# if the user has asked to not have either hidden
                   6343: 	# or 'randomout' controlled resources to be graded
                   6344: 	# don't include them
                   6345: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6346: 	    && $curres->randomout) {
                   6347: 	    return 0;
                   6348: 	}
1.83      albertel 6349: 	return 1;
                   6350:     }
                   6351:     return 0;
1.82      albertel 6352: }
                   6353: 
1.423     albertel 6354: =pod
                   6355: 
                   6356: =item scantron_process_corrections
                   6357: 
1.424     albertel 6358:    Gets correction information out of submitted form data and corrects
                   6359:    the scanline
                   6360: 
1.423     albertel 6361: =cut
                   6362: 
1.157     albertel 6363: sub scantron_process_corrections {
                   6364:     my ($r) = @_;
1.257     albertel 6365:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6366:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6367:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6368:     my $which=$env{'form.scantron_line'};
1.200     albertel 6369:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6370:     my ($skip,$err,$errmsg);
1.257     albertel 6371:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6372: 	$skip=1;
1.257     albertel 6373:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6374: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6375: 	    $env{'form.scantron_domain'};
1.157     albertel 6376: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6377: 	($line,$err,$errmsg)=
                   6378: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6379: 				     'ID',{'newid'=>$newid,
1.257     albertel 6380: 				    'username'=>$env{'form.scantron_username'},
                   6381: 				    'domain'=>$env{'form.scantron_domain'}});
                   6382:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6383: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6384: 	my $newCODE;
1.192     albertel 6385: 	my %args;
1.190     albertel 6386: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6387: 	    $newCODE='use_unfound';
1.190     albertel 6388: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6389: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6390: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6391: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6392: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6393: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6394: 	}
1.257     albertel 6395: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6396: 	    $args{'CODE_ignore_dup'}=1;
                   6397: 	}
                   6398: 	$args{'CODE'}=$newCODE;
1.186     albertel 6399: 	($line,$err,$errmsg)=
                   6400: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6401: 				     'CODE',\%args);
1.257     albertel 6402:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6403: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6404: 	    ($line,$err,$errmsg)=
                   6405: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6406: 					 $which,'answer',
                   6407: 					 { 'question'=>$question,
1.503     raeburn  6408: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6409:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6410: 	    if ($err) { last; }
                   6411: 	}
                   6412:     }
                   6413:     if ($err) {
1.398     albertel 6414: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6415:     } else {
1.200     albertel 6416: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6417: 	&scantron_putfile($scanlines,$scan_data);
                   6418:     }
                   6419: }
                   6420: 
1.423     albertel 6421: =pod
                   6422: 
                   6423: =item reset_skipping_status
                   6424: 
1.424     albertel 6425:    Forgets the current set of remember skipped scanlines (and thus
                   6426:    reverts back to considering all lines in the
                   6427:    scantron_skipped_<filename> file)
                   6428: 
1.423     albertel 6429: =cut
                   6430: 
1.200     albertel 6431: sub reset_skipping_status {
                   6432:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6433:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6434:     &scantron_putfile(undef,$scan_data);
                   6435: }
                   6436: 
1.423     albertel 6437: =pod
                   6438: 
                   6439: =item start_skipping
                   6440: 
1.424     albertel 6441:    Marks a scanline to be skipped. 
                   6442: 
1.423     albertel 6443: =cut
                   6444: 
1.376     albertel 6445: sub start_skipping {
1.200     albertel 6446:     my ($scan_data,$i)=@_;
                   6447:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6448:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6449: 	$remembered{$i}=2;
                   6450:     } else {
                   6451: 	$remembered{$i}=1;
                   6452:     }
1.200     albertel 6453:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6454: }
                   6455: 
1.423     albertel 6456: =pod
                   6457: 
                   6458: =item should_be_skipped
                   6459: 
1.424     albertel 6460:    Checks whether a scanline should be skipped.
                   6461: 
1.423     albertel 6462: =cut
                   6463: 
1.200     albertel 6464: sub should_be_skipped {
1.376     albertel 6465:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6466:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6467: 	# not redoing old skips
1.376     albertel 6468: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6469: 	return 0;
                   6470:     }
                   6471:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6472: 
                   6473:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6474: 	return 0;
                   6475:     }
1.200     albertel 6476:     return 1;
                   6477: }
                   6478: 
1.423     albertel 6479: =pod
                   6480: 
                   6481: =item remember_current_skipped
                   6482: 
1.424     albertel 6483:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6484:    file and remembers them into scan_data for later use.
                   6485: 
1.423     albertel 6486: =cut
                   6487: 
1.200     albertel 6488: sub remember_current_skipped {
                   6489:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6490:     my %to_remember;
                   6491:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6492: 	if ($scanlines->{'skipped'}[$i]) {
                   6493: 	    $to_remember{$i}=1;
                   6494: 	}
                   6495:     }
1.376     albertel 6496: 
1.200     albertel 6497:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6498:     &scantron_putfile(undef,$scan_data);
                   6499: }
                   6500: 
1.423     albertel 6501: =pod
                   6502: 
                   6503: =item check_for_error
                   6504: 
1.424     albertel 6505:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6506:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6507:     something went wrong.
                   6508: 
1.423     albertel 6509: =cut
                   6510: 
1.200     albertel 6511: sub check_for_error {
                   6512:     my ($r,$result)=@_;
                   6513:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6514: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6515:     }
                   6516: }
1.157     albertel 6517: 
1.423     albertel 6518: =pod
                   6519: 
                   6520: =item scantron_warning_screen
                   6521: 
1.424     albertel 6522:    Interstitial screen to make sure the operator has selected the
                   6523:    correct options before we start the validation phase.
                   6524: 
1.423     albertel 6525: =cut
                   6526: 
1.203     albertel 6527: sub scantron_warning_screen {
1.650     raeburn  6528:     my ($button_text,$symb)=@_;
1.257     albertel 6529:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6530:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6531:     my $CODElist;
1.284     albertel 6532:     if ($scantron_config{'CODElocation'} &&
                   6533: 	$scantron_config{'CODEstart'} &&
                   6534: 	$scantron_config{'CODElength'}) {
                   6535: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6536: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6537: 	$CODElist=
1.492     albertel 6538: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6539: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6540:     }
1.663     raeburn  6541:     my $lastbubblepoints;
                   6542:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6543:         $lastbubblepoints =
                   6544:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6545:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6546:     }
1.492     albertel 6547:     return ('
1.203     albertel 6548: <p>
1.492     albertel 6549: <span class="LC_warning">
                   6550: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6551: </p>
                   6552: <table>
1.492     albertel 6553: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6554: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6555: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6556: </table>
1.680     raeburn  6557: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6558: '.&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 6559: 
                   6560: <br />
1.492     albertel 6561: ');
1.203     albertel 6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item scantron_do_warning
                   6567: 
1.424     albertel 6568:    Check if the operator has picked something for all required
                   6569:    fields. Error out if something is missing.
                   6570: 
1.423     albertel 6571: =cut
                   6572: 
1.203     albertel 6573: sub scantron_do_warning {
1.608     www      6574:     my ($r,$symb)=@_;
1.203     albertel 6575:     if (!$symb) {return '';}
1.324     albertel 6576:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6577:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6578:     if ( $env{'form.selectpage'} eq '' ||
                   6579: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6580: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6581: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6582: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6583: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6584: 	} 
1.257     albertel 6585: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6586: 	    $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 6587: 	} 
1.257     albertel 6588: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6589: 	    $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 6590: 	} 
                   6591:     } else {
1.650     raeburn  6592: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6593:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6594: 	$r->print('
1.663     raeburn  6595: '.$warning.$bubbledbyhand.'
1.492     albertel 6596: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6597: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6598: ');
1.237     albertel 6599:     }
1.614     www      6600:     $r->print("</form><br />");
1.203     albertel 6601:     return '';
                   6602: }
                   6603: 
1.423     albertel 6604: =pod
                   6605: 
                   6606: =item scantron_form_start
                   6607: 
1.424     albertel 6608:     html hidden input for remembering all selected grading options
                   6609: 
1.423     albertel 6610: =cut
                   6611: 
1.203     albertel 6612: sub scantron_form_start {
                   6613:     my ($max_bubble)=@_;
                   6614:     my $result= <<SCANTRONFORM;
                   6615: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6616:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6617:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6618:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6619:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6620:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6621:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6622:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6623:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6624:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6625: SCANTRONFORM
1.447     foxr     6626: 
                   6627:   my $line = 0;
                   6628:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6629:        my $chunk =
                   6630: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6631:        $chunk .=
                   6632: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6633:        $chunk .= 
                   6634:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6635:        $chunk .=
                   6636:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6637:        $chunk .=
                   6638:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6639:        $result .= $chunk;
                   6640:        $line++;
1.691     raeburn  6641:     }
1.203     albertel 6642:     return $result;
                   6643: }
                   6644: 
1.423     albertel 6645: =pod
                   6646: 
                   6647: =item scantron_validate_file
                   6648: 
1.659     raeburn  6649:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6650: 
                   6651:     Also processes any necessary information resets that need to
                   6652:     occur before validation begins (ignore previous corrections,
                   6653:     restarting the skipped records processing)
                   6654: 
1.423     albertel 6655: =cut
                   6656: 
1.157     albertel 6657: sub scantron_validate_file {
1.608     www      6658:     my ($r,$symb) = @_;
1.157     albertel 6659:     if (!$symb) {return '';}
1.324     albertel 6660:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6661:     
                   6662:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6663:     # them when doing the corrections reset
1.257     albertel 6664:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6665: 	&reset_skipping_status();
                   6666:     }
1.257     albertel 6667:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6668: 	&remember_current_skipped();
1.257     albertel 6669: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6670:     }
                   6671: 
1.257     albertel 6672:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6673: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6674: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6675: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6676: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6677:     }
1.200     albertel 6678: 
1.257     albertel 6679:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6680: 	&scantron_process_corrections($r);
                   6681:     }
1.503     raeburn  6682:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6683:     #get the student pick code ready
                   6684:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6685:     my $nav_error;
1.649     raeburn  6686:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6687:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6688:     if ($nav_error) {
                   6689:         $r->print(&navmap_errormsg());
                   6690:         return '';
                   6691:     }
1.203     albertel 6692:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6693:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6694:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6695:     }
1.157     albertel 6696:     $r->print($result);
                   6697:     
1.334     albertel 6698:     my @validate_phases=( 'sequence',
                   6699: 			  'ID',
1.157     albertel 6700: 			  'CODE',
                   6701: 			  'doublebubble',
                   6702: 			  'missingbubbles');
1.257     albertel 6703:     if (!$env{'form.validatepass'}) {
                   6704: 	$env{'form.validatepass'} = 0;
1.157     albertel 6705:     }
1.257     albertel 6706:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6707: 
1.448     foxr     6708: 
1.157     albertel 6709:     my $stop=0;
                   6710:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6711: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6712: 	$r->rflush();
1.691     raeburn  6713:      
1.157     albertel 6714: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6715: 	{
                   6716: 	    no strict 'refs';
                   6717: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6718: 	}
                   6719:     }
                   6720:     if (!$stop) {
1.650     raeburn  6721: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6722: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6723:                   $warning.
                   6724:                   &mt('Perform verification for each student after storage of submissions?').
                   6725:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6726:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6727:                   ('&nbsp;'x3).'<label>'.
                   6728:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6729:                   '</label></span><br />'.
                   6730:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6731:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6732:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6733:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6734:     } else {
                   6735: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6736: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6737:     }
                   6738:     if ($stop) {
1.334     albertel 6739: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6740: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6741: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6742: 
1.650     raeburn  6743: 	    $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 6744: 	} else {
1.503     raeburn  6745:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6746: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6747:             } else {
1.539     riegler  6748:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6749:             }
1.492     albertel 6750: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6751: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6752: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6753: 	}
1.157     albertel 6754:     }
1.614     www      6755:     $r->print(" </form><br />");
1.157     albertel 6756:     return '';
                   6757: }
                   6758: 
1.423     albertel 6759: 
                   6760: =pod
                   6761: 
                   6762: =item scantron_remove_file
                   6763: 
1.659     raeburn  6764:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6765:    scantron_original_<filename> is never removed
                   6766: 
                   6767: 
1.423     albertel 6768: =cut
                   6769: 
1.200     albertel 6770: sub scantron_remove_file {
1.192     albertel 6771:     my ($which)=@_;
1.257     albertel 6772:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6773:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6774:     my $file='scantron_';
1.200     albertel 6775:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6776: 	$file.=$which.'_';
1.192     albertel 6777:     } else {
                   6778: 	return 'refused';
                   6779:     }
1.257     albertel 6780:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6781:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6782: }
                   6783: 
1.423     albertel 6784: 
                   6785: =pod
                   6786: 
                   6787: =item scantron_remove_scan_data
                   6788: 
1.659     raeburn  6789:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6790:    data file.  (In the case that both the are doing skipped records we need
                   6791:    to remember the old skipped lines for the time being so that element
                   6792:    persists for a while.)
                   6793: 
1.423     albertel 6794: =cut
                   6795: 
1.200     albertel 6796: sub scantron_remove_scan_data {
1.257     albertel 6797:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6798:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6799:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6800:     my @todelete;
1.257     albertel 6801:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6802:     foreach my $key (@keys) {
                   6803: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6804: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6805: 		$key=~/remember_skipping/) {
                   6806: 		next;
                   6807: 	    }
1.192     albertel 6808: 	    push(@todelete,$key);
                   6809: 	}
                   6810:     }
1.200     albertel 6811:     my $result;
1.192     albertel 6812:     if (@todelete) {
1.491     albertel 6813: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6814: 				       \@todelete,$cdom,$cname);
                   6815:     } else {
                   6816: 	$result = 'ok';
1.192     albertel 6817:     }
                   6818:     return $result;
                   6819: }
                   6820: 
1.423     albertel 6821: 
                   6822: =pod
                   6823: 
                   6824: =item scantron_getfile
                   6825: 
1.659     raeburn  6826:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6827:     the scan_data hash
                   6828:   
                   6829:   Arguments:
                   6830:     None
                   6831: 
                   6832:   Returns:
                   6833:     2 hash references
                   6834: 
                   6835:      - first one has 
                   6836:          orig      -
                   6837:          corrected -
                   6838:          skipped   -  each of which points to an array ref of the specified
                   6839:                       file broken up into individual lines
                   6840:          count     - number of scanlines
                   6841:  
                   6842:      - second is the scan_data hash possible keys are
1.425     albertel 6843:        ($number refers to scanline numbered $number and thus the key affects
                   6844:         only that scanline
                   6845:         $bubline refers to the specific bubble line element and the aspects
                   6846:         refers to that specific bubble line element)
                   6847: 
                   6848:        $number.user - username:domain to use
                   6849:        $number.CODE_ignore_dup 
                   6850:                     - ignore the duplicate CODE error 
                   6851:        $number.useCODE
                   6852:                     - use the CODE in the scanline as is
                   6853:        $number.no_bubble.$bubline
                   6854:                     - it is valid that there is no bubbled in bubble
                   6855:                       at $number $bubline
                   6856:        remember_skipping
                   6857:                     - a frozen hash containing keys of $number and values
                   6858:                       of either 
                   6859:                         1 - we are on a 'do skipped records pass' and plan
                   6860:                             on processing this line
                   6861:                         2 - we are on a 'do skipped records pass' and this
                   6862:                             scanline has been marked to skip yet again
1.424     albertel 6863: 
1.423     albertel 6864: =cut
                   6865: 
1.157     albertel 6866: sub scantron_getfile {
1.200     albertel 6867:     #FIXME really would prefer a scantron directory
1.257     albertel 6868:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6869:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6870:     my $lines;
                   6871:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6872: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6873:     my %scanlines;
                   6874:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6875:     my $temp=$scanlines{'orig'};
                   6876:     $scanlines{'count'}=$#$temp;
                   6877: 
                   6878:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6879: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6880:     if ($lines eq '-1') {
                   6881: 	$scanlines{'corrected'}=[];
                   6882:     } else {
                   6883: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6884:     }
                   6885:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6886: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6887:     if ($lines eq '-1') {
                   6888: 	$scanlines{'skipped'}=[];
                   6889:     } else {
                   6890: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6891:     }
1.175     albertel 6892:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6893:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6894:     my %scan_data = @tmp;
                   6895:     return (\%scanlines,\%scan_data);
                   6896: }
                   6897: 
1.423     albertel 6898: =pod
                   6899: 
                   6900: =item lonnet_putfile
                   6901: 
1.424     albertel 6902:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6903: 
                   6904:  Arguments:
                   6905:    $contents - data to store
                   6906:    $filename - filename to store $contents into
                   6907: 
                   6908:  Returns:
                   6909:    result value from &Apache::lonnet::finishuserfileupload
                   6910: 
1.423     albertel 6911: =cut
                   6912: 
1.157     albertel 6913: sub lonnet_putfile {
                   6914:     my ($contents,$filename)=@_;
1.257     albertel 6915:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6916:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6917:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6918:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6919: 
                   6920: }
                   6921: 
1.423     albertel 6922: =pod
                   6923: 
                   6924: =item scantron_putfile
                   6925: 
1.659     raeburn  6926:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6927:     scan_data hash. (Does not modify the original version only the
                   6928:     corrected and skipped versions.
                   6929: 
                   6930:  Arguments:
                   6931:     $scanlines - hash ref that looks like the first return value from
                   6932:                  &scantron_getfile()
                   6933:     $scan_data - hash ref that looks like the second return value from
                   6934:                  &scantron_getfile()
                   6935: 
1.423     albertel 6936: =cut
                   6937: 
1.157     albertel 6938: sub scantron_putfile {
                   6939:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6940:     #FIXME really would prefer a scantron directory
1.257     albertel 6941:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6942:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6943:     if ($scanlines) {
                   6944: 	my $prefix='scantron_';
1.157     albertel 6945: # no need to update orig, shouldn't change
                   6946: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6947: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6948: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6949: 			$prefix.'corrected_'.
1.257     albertel 6950: 			$env{'form.scantron_selectfile'});
1.200     albertel 6951: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6952: 			$prefix.'skipped_'.
1.257     albertel 6953: 			$env{'form.scantron_selectfile'});
1.200     albertel 6954:     }
1.175     albertel 6955:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6956: }
                   6957: 
1.423     albertel 6958: =pod
                   6959: 
                   6960: =item scantron_get_line
                   6961: 
1.424     albertel 6962:    Returns the correct version of the scanline
                   6963: 
                   6964:  Arguments:
                   6965:     $scanlines - hash ref that looks like the first return value from
                   6966:                  &scantron_getfile()
                   6967:     $scan_data - hash ref that looks like the second return value from
                   6968:                  &scantron_getfile()
                   6969:     $i         - number of the requested line (starts at 0)
                   6970: 
                   6971:  Returns:
                   6972:    A scanline, (either the original or the corrected one if it
                   6973:    exists), or undef if the requested scanline should be
                   6974:    skipped. (Either because it's an skipped scanline, or it's an
                   6975:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6976:    pass.
                   6977: 
1.423     albertel 6978: =cut
                   6979: 
1.157     albertel 6980: sub scantron_get_line {
1.200     albertel 6981:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6982:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6983:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6984:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6985:     return $scanlines->{'orig'}[$i]; 
                   6986: }
                   6987: 
1.423     albertel 6988: =pod
                   6989: 
                   6990: =item scantron_todo_count
                   6991: 
1.424     albertel 6992:     Counts the number of scanlines that need processing.
                   6993: 
                   6994:  Arguments:
                   6995:     $scanlines - hash ref that looks like the first return value from
                   6996:                  &scantron_getfile()
                   6997:     $scan_data - hash ref that looks like the second return value from
                   6998:                  &scantron_getfile()
                   6999: 
                   7000:  Returns:
                   7001:     $count - number of scanlines to process
                   7002: 
1.423     albertel 7003: =cut
                   7004: 
1.200     albertel 7005: sub get_todo_count {
                   7006:     my ($scanlines,$scan_data)=@_;
                   7007:     my $count=0;
                   7008:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7009: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7010: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7011: 	$count++;
                   7012:     }
                   7013:     return $count;
                   7014: }
                   7015: 
1.423     albertel 7016: =pod
                   7017: 
                   7018: =item scantron_put_line
                   7019: 
1.659     raeburn  7020:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7021:     data file.
                   7022: 
                   7023:  Arguments:
                   7024:     $scanlines - hash ref that looks like the first return value from
                   7025:                  &scantron_getfile()
                   7026:     $scan_data - hash ref that looks like the second return value from
                   7027:                  &scantron_getfile()
                   7028:     $i         - line number to update
                   7029:     $newline   - contents of the updated scanline
                   7030:     $skip      - if true make the line for skipping and update the
                   7031:                  'skipped' file
                   7032: 
1.423     albertel 7033: =cut
                   7034: 
1.157     albertel 7035: sub scantron_put_line {
1.200     albertel 7036:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7037:     if ($skip) {
                   7038: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7039: 	&start_skipping($scan_data,$i);
1.157     albertel 7040: 	return;
                   7041:     }
                   7042:     $scanlines->{'corrected'}[$i]=$newline;
                   7043: }
                   7044: 
1.423     albertel 7045: =pod
                   7046: 
                   7047: =item scantron_clear_skip
                   7048: 
1.424     albertel 7049:    Remove a line from the 'skipped' file
                   7050: 
                   7051:  Arguments:
                   7052:     $scanlines - hash ref that looks like the first return value from
                   7053:                  &scantron_getfile()
                   7054:     $scan_data - hash ref that looks like the second return value from
                   7055:                  &scantron_getfile()
                   7056:     $i         - line number to update
                   7057: 
1.423     albertel 7058: =cut
                   7059: 
1.376     albertel 7060: sub scantron_clear_skip {
                   7061:     my ($scanlines,$scan_data,$i)=@_;
                   7062:     if (exists($scanlines->{'skipped'}[$i])) {
                   7063: 	undef($scanlines->{'skipped'}[$i]);
                   7064: 	return 1;
                   7065:     }
                   7066:     return 0;
                   7067: }
                   7068: 
1.423     albertel 7069: =pod
                   7070: 
                   7071: =item scantron_filter_not_exam
                   7072: 
1.424     albertel 7073:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7074:    filter out resources that are not marked as 'exam' mode
                   7075: 
1.423     albertel 7076: =cut
                   7077: 
1.334     albertel 7078: sub scantron_filter_not_exam {
                   7079:     my ($curres)=@_;
                   7080:     
                   7081:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7082: 	# if the user has asked to not have either hidden
                   7083: 	# or 'randomout' controlled resources to be graded
                   7084: 	# don't include them
                   7085: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7086: 	    && $curres->randomout) {
                   7087: 	    return 0;
                   7088: 	}
                   7089: 	return 1;
                   7090:     }
                   7091:     return 0;
                   7092: }
                   7093: 
1.423     albertel 7094: =pod
                   7095: 
                   7096: =item scantron_validate_sequence
                   7097: 
1.424     albertel 7098:     Validates the selected sequence, checking for resource that are
                   7099:     not set to exam mode.
                   7100: 
1.423     albertel 7101: =cut
                   7102: 
1.334     albertel 7103: sub scantron_validate_sequence {
                   7104:     my ($r,$currentphase) = @_;
                   7105: 
                   7106:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7107:     unless (ref($navmap)) {
                   7108:         $r->print(&navmap_errormsg());
                   7109:         return (1,$currentphase);
                   7110:     }
1.334     albertel 7111:     my (undef,undef,$sequence)=
                   7112: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7113: 
                   7114:     my $map=$navmap->getResourceByUrl($sequence);
                   7115: 
                   7116:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7117:                                     value="ignore" />');
                   7118:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7119: 	my @resources=
                   7120: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7121: 	if (@resources) {
1.675     bisitz   7122: 	    $r->print(
                   7123:                 '<p class="LC_warning">'
                   7124:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7125:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7126:                    .' work correctly.')
                   7127:                .'</p>'
                   7128:             );
1.334     albertel 7129: 	    return (1,$currentphase);
                   7130: 	}
                   7131:     }
                   7132: 
                   7133:     return (0,$currentphase+1);
                   7134: }
                   7135: 
1.423     albertel 7136: 
                   7137: 
1.157     albertel 7138: sub scantron_validate_ID {
                   7139:     my ($r,$currentphase) = @_;
                   7140:     
                   7141:     #get student info
                   7142:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7143:     my %idmap=&username_to_idmap($classlist);
                   7144: 
                   7145:     #get scantron line setup
1.257     albertel 7146:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7147:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7148: 
                   7149:     my $nav_error;
1.649     raeburn  7150:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7151:     if ($nav_error) {
                   7152:         $r->print(&navmap_errormsg());
                   7153:         return(1,$currentphase);
                   7154:     }
1.157     albertel 7155: 
                   7156:     my %found=('ids'=>{},'usernames'=>{});
                   7157:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7158: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7159: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7160: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7161: 						 $scan_data);
                   7162: 	my $id=$$scan_record{'scantron.ID'};
                   7163: 	my $found;
                   7164: 	foreach my $checkid (keys(%idmap)) {
                   7165: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7166: 	}
                   7167: 	if ($found) {
                   7168: 	    my $username=$idmap{$found};
                   7169: 	    if ($found{'ids'}{$found}) {
                   7170: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7171: 					 $line,'duplicateID',$found);
1.194     albertel 7172: 		return(1,$currentphase);
1.157     albertel 7173: 	    } elsif ($found{'usernames'}{$username}) {
                   7174: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7175: 					 $line,'duplicateID',$username);
1.194     albertel 7176: 		return(1,$currentphase);
1.157     albertel 7177: 	    }
1.186     albertel 7178: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7179: 	    $found{'ids'}{$found}++;
                   7180: 	    $found{'usernames'}{$username}++;
                   7181: 	} else {
                   7182: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7183: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7184: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7185: 		    &scantron_get_correction($r,$i,$scan_record,
                   7186: 					     \%scantron_config,
                   7187: 					     $line,'duplicateID',$username);
1.194     albertel 7188: 		    return(1,$currentphase);
1.157     albertel 7189: 		} elsif (!defined($username)) {
                   7190: 		    &scantron_get_correction($r,$i,$scan_record,
                   7191: 					     \%scantron_config,
                   7192: 					     $line,'incorrectID');
1.194     albertel 7193: 		    return(1,$currentphase);
1.157     albertel 7194: 		}
                   7195: 		$found{'usernames'}{$username}++;
                   7196: 	    } else {
                   7197: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7198: 					 $line,'incorrectID');
1.194     albertel 7199: 		return(1,$currentphase);
1.157     albertel 7200: 	    }
                   7201: 	}
                   7202:     }
                   7203: 
                   7204:     return (0,$currentphase+1);
                   7205: }
                   7206: 
1.423     albertel 7207: 
1.157     albertel 7208: sub scantron_get_correction {
1.691     raeburn  7209:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7210:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7211: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7212: #to show both the current line and the previous one and allow skipping
                   7213: #the previous one or the current one
                   7214: 
1.333     albertel 7215:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7216:         $r->print(
                   7217:             '<p class="LC_warning">'
                   7218:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7219:                 "<b>$error</b>",
                   7220:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7221:            ."</p> \n");
1.157     albertel 7222:     } else {
1.658     bisitz   7223:         $r->print(
                   7224:             '<p class="LC_warning">'
                   7225:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7226:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7227:            ."</p> \n");
                   7228:     }
                   7229:     my $message =
                   7230:         '<p>'
                   7231:        .&mt('The ID on the form is [_1]',
                   7232:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7233:        .'<br />'
1.665     raeburn  7234:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7235:             $$scan_record{'scantron.LastName'},
                   7236:             $$scan_record{'scantron.FirstName'})
                   7237:        .'</p>';
1.242     albertel 7238: 
1.157     albertel 7239:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7240:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7241:                            # Array populated for doublebubble or
                   7242:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7243:                            # to validate radio button checking   
                   7244: 
1.157     albertel 7245:     if ($error =~ /ID$/) {
1.186     albertel 7246: 	if ($error eq 'incorrectID') {
1.658     bisitz   7247:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7248: 		      "</p>\n");
1.157     albertel 7249: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7250:             $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 7251: 	}
1.242     albertel 7252: 	$r->print($message);
1.492     albertel 7253: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7254: 	$r->print("\n<ul><li> ");
                   7255: 	#FIXME it would be nice if this sent back the user ID and
                   7256: 	#could do partial userID matches
                   7257: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7258: 				       'scantron_username','scantron_domain'));
                   7259: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7260: 	$r->print("\n:\n".
1.257     albertel 7261: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7262: 
                   7263: 	$r->print('</li>');
1.186     albertel 7264:     } elsif ($error =~ /CODE$/) {
                   7265: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7266: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7267: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7268: 	    $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 7269: 	}
1.658     bisitz   7270: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7271: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7272:                  ."</p>\n");
1.242     albertel 7273: 	$r->print($message);
1.658     bisitz   7274: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7275: 	$r->print("\n<br /> ");
1.194     albertel 7276: 	my $i=0;
1.273     albertel 7277: 	if ($error eq 'incorrectCODE' 
                   7278: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7279: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7280: 	    if ($closest > 0) {
                   7281: 		foreach my $testcode (@{$closest}) {
                   7282: 		    my $checked='';
1.569     bisitz   7283: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7284: 		    $r->print("
                   7285:    <label>
1.569     bisitz   7286:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7287:        ".&mt("Use the similar CODE [_1] instead.",
                   7288: 	    "<b><tt>".$testcode."</tt></b>")."
                   7289:     </label>
                   7290:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7291: 		    $r->print("\n<br />");
                   7292: 		    $i++;
                   7293: 		}
1.194     albertel 7294: 	    }
                   7295: 	}
1.273     albertel 7296: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7297: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7298: 	    $r->print("
                   7299:     <label>
1.569     bisitz   7300:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7301:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7302: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7303:     </label>");
1.273     albertel 7304: 	    $r->print("\n<br />");
                   7305: 	}
1.194     albertel 7306: 
1.597     wenzelju 7307: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7308: function change_radio(field) {
1.190     albertel 7309:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7310:     var i;
                   7311:     for (i=0;i<slct.length;i++) {
                   7312:         if (slct[i].value==field) { slct[i].checked=true; }
                   7313:     }
                   7314: }
                   7315: ENDSCRIPT
1.187     albertel 7316: 	my $href="/adm/pickcode?".
1.359     www      7317: 	   "form=".&escape("scantronupload").
                   7318: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7319: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7320: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7321: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7322: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7323: 	    $r->print("
                   7324:     <label>
                   7325:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7326:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7327: 	     "<a target='_blank' href='$href'>","</a>")."
                   7328:     </label> 
1.558     bisitz   7329:     ".&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 7330: 	    $r->print("\n<br />");
                   7331: 	}
1.492     albertel 7332: 	$r->print("
                   7333:     <label>
                   7334:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7335:        ".&mt("Use [_1] as the CODE.",
                   7336: 	     "</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 7337: 	$r->print("\n<br /><br />");
1.157     albertel 7338:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7339: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7340: 
                   7341: 	# The form field scantron_questions is acutally a list of line numbers.
                   7342: 	# represented by this form so:
                   7343: 
1.691     raeburn  7344: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7345:                                                 $respnumlookup,$startline);
1.497     foxr     7346: 
1.157     albertel 7347: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7348: 		  $line_list.'" />');
1.242     albertel 7349: 	$r->print($message);
1.492     albertel 7350: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7351: 	foreach my $question (@{$arg}) {
1.503     raeburn  7352: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7353:                                                    $scan_record, $error,
                   7354:                                                    $randomorder,$randompick,
                   7355:                                                    $respnumlookup,$startline);
1.524     raeburn  7356:             push(@lines_to_correct,@linenums);
1.157     albertel 7357: 	}
1.503     raeburn  7358:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7359:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7360: 	$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 7361: 	$r->print($message);
1.492     albertel 7362: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7363: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7364: 
1.503     raeburn  7365: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7366: 	# a list of question numbers. Therefore:
                   7367: 	#
1.691     raeburn  7368: 
                   7369: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7370:                                                 $respnumlookup,$startline);
1.497     foxr     7371: 
1.157     albertel 7372: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7373: 		  $line_list.'" />');
1.157     albertel 7374: 	foreach my $question (@{$arg}) {
1.503     raeburn  7375: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7376:                                                    $scan_record, $error,
                   7377:                                                    $randomorder,$randompick,
                   7378:                                                    $respnumlookup,$startline);
1.524     raeburn  7379:             push(@lines_to_correct,@linenums);
1.157     albertel 7380: 	}
1.503     raeburn  7381:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7382:     } else {
                   7383: 	$r->print("\n<ul>");
                   7384:     }
                   7385:     $r->print("\n</li></ul>");
1.497     foxr     7386: }
                   7387: 
1.503     raeburn  7388: sub verify_bubbles_checked {
                   7389:     my (@ansnums) = @_;
                   7390:     my $ansnumstr = join('","',@ansnums);
                   7391:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7392:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7393: function verify_bubble_radio(form) {
                   7394:     var ansnumArray = new Array ("$ansnumstr");
                   7395:     var need_bubble_count = 0;
                   7396:     for (var i=0; i<ansnumArray.length; i++) {
                   7397:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7398:             var bubble_picked = 0; 
                   7399:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7400:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7401:                     bubble_picked = 1;
                   7402:                 }
                   7403:             }
                   7404:             if (bubble_picked == 0) {
                   7405:                 need_bubble_count ++;
                   7406:             }
                   7407:         }
                   7408:     }
                   7409:     if (need_bubble_count) {
                   7410:         alert("$warning");
                   7411:         return;
                   7412:     }
                   7413:     form.submit(); 
                   7414: }
                   7415: ENDSCRIPT
                   7416:     return $output;
                   7417: }
                   7418: 
1.497     foxr     7419: =pod
                   7420: 
                   7421: =item  questions_to_line_list
1.157     albertel 7422: 
1.497     foxr     7423: Converts a list of questions into a string of comma separated
                   7424: line numbers in the answer sheet used by the questions.  This is
                   7425: used to fill in the scantron_questions form field.
                   7426: 
                   7427:   Arguments:
                   7428:      questions    - Reference to an array of questions.
1.691     raeburn  7429:      randomorder  - True if randomorder in use.
                   7430:      randompick   - True if randompick in use.
                   7431:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7432:                      for current line to question number used for same question
                   7433:                      in "Master Seqence" (as seen by Course Coordinator).
                   7434:      startline    - Reference to hash where key is question number (0 is first)
                   7435:                     and key is number of first bubble line for current student
                   7436:                     or code-based randompick and/or randomorder.
1.693     raeburn  7437: 
1.497     foxr     7438: =cut
                   7439: 
                   7440: 
                   7441: sub questions_to_line_list {
1.691     raeburn  7442:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7443:     my @lines;
                   7444: 
1.503     raeburn  7445:     foreach my $item (@{$questions}) {
                   7446:         my $question = $item;
                   7447:         my ($first,$count,$last);
                   7448:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7449:             $question = $1;
                   7450:             my $subquestion = $2;
1.691     raeburn  7451:             my $responsenum = $question-1;
                   7452:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7453:                 $responsenum = $respnumlookup->{$question-1};
                   7454:                 if (ref($startline) eq 'HASH') {
                   7455:                     $first = $startline->{$question-1} + 1;
                   7456:                 }
                   7457:             } else {
                   7458:                 $first = $first_bubble_line{$responsenum} + 1;
                   7459:             }
                   7460:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7461:             my $subcount = 1;
                   7462:             while ($subcount<$subquestion) {
                   7463:                 $first += $subans[$subcount-1];
                   7464:                 $subcount ++;
                   7465:             }
                   7466:             $count = $subans[$subquestion-1];
                   7467:         } else {
1.691     raeburn  7468:             my $responsenum = $question-1;
                   7469:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7470:                 $responsenum = $respnumlookup->{$question-1};
                   7471:                 if (ref($startline) eq 'HASH') {
                   7472:                     $first = $startline->{$question-1} + 1;
                   7473:                 }
                   7474:             } else {
                   7475:                 $first = $first_bubble_line{$responsenum} + 1;
                   7476:             }
                   7477: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7478:         }
1.506     raeburn  7479:         $last = $first+$count-1;
1.503     raeburn  7480:         push(@lines, ($first..$last));
1.497     foxr     7481:     }
                   7482:     return join(',', @lines);
                   7483: }
                   7484: 
                   7485: =pod 
                   7486: 
                   7487: =item prompt_for_corrections
                   7488: 
                   7489: Prompts for a potentially multiline correction to the
                   7490: user's bubbling (factors out common code from scantron_get_correction
                   7491: for multi and missing bubble cases).
                   7492: 
                   7493:  Arguments:
                   7494:    $r           - Apache request object.
                   7495:    $question    - The question number to prompt for.
                   7496:    $scan_config - The scantron file configuration hash.
                   7497:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7498:    $error       - Type of error
1.691     raeburn  7499:    $randomorder - True if randomorder in use.
                   7500:    $randompick  - True if randompick in use.
                   7501:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7502:                     for current line to question number used for same question
                   7503:                     in "Master Seqence" (as seen by Course Coordinator).
                   7504:    $startline   - Reference to hash where key is question number (0 is first)
                   7505:                   and value is number of first bubble line for current student
                   7506:                   or code-based randompick and/or randomorder.
                   7507: 
1.497     foxr     7508: 
                   7509:  Implicit inputs:
                   7510:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7511:                                   Numbered from 0 (but question numbers are from
                   7512:                                   1.
                   7513:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7514:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7515:                                   type problems render as separate sub-questions, 
1.503     raeburn  7516:                                   in exam mode. This hash contains a 
                   7517:                                   comma-separated list of the lines per 
                   7518:                                   sub-question.
1.510     raeburn  7519:    %responsetype_per_response   - essayresponse, formularesponse,
                   7520:                                   stringresponse, imageresponse, reactionresponse,
                   7521:                                   and organicresponse type problem parts can have
1.503     raeburn  7522:                                   multiple lines per response if the weight
                   7523:                                   assigned exceeds 10.  In this case, only
                   7524:                                   one bubble per line is permitted, but more 
                   7525:                                   than one line might contain bubbles, e.g.
                   7526:                                   bubbling of: line 1 - J, line 2 - J, 
                   7527:                                   line 3 - B would assign 22 points.  
1.497     foxr     7528: 
                   7529: =cut
                   7530: 
                   7531: sub prompt_for_corrections {
1.691     raeburn  7532:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7533:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7534:     my ($current_line,$lines);
                   7535:     my @linenums;
                   7536:     my $questionnum = $question;
1.691     raeburn  7537:     my ($first,$responsenum);
1.503     raeburn  7538:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7539:         $question = $1;
                   7540:         my $subquestion = $2;
1.691     raeburn  7541:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7542:             $responsenum = $respnumlookup->{$question-1};
                   7543:             if (ref($startline) eq 'HASH') {
                   7544:                 $first = $startline->{$question-1};
                   7545:             }
                   7546:         } else {
                   7547:             $responsenum = $question-1;
                   7548:             $first = $first_bubble_line{$responsenum} + 1;
                   7549:         }
                   7550:         $current_line = $first + 1 ;
                   7551:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7552:         my $subcount = 1;
                   7553:         while ($subcount<$subquestion) {
                   7554:             $current_line += $subans[$subcount-1];
                   7555:             $subcount ++;
                   7556:         }
                   7557:         $lines = $subans[$subquestion-1];
                   7558:     } else {
1.691     raeburn  7559:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7560:             $responsenum = $respnumlookup->{$question-1};
                   7561:             if (ref($startline) eq 'HASH') { 
                   7562:                 $first = $startline->{$question-1};
                   7563:             }
                   7564:         } else {
                   7565:             $responsenum = $question-1;
                   7566:             $first = $first_bubble_line{$responsenum};
                   7567:         }
                   7568:         $current_line = $first + 1;
                   7569:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7570:     }
1.497     foxr     7571:     if ($lines > 1) {
1.503     raeburn  7572:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7573:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7574:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7575:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7576:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7577:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7578:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7579:             $r->print(
                   7580:                 &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)
                   7581:                .'<br /><br />'
                   7582:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7583:                .'<br />'
                   7584:                .&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.')
                   7585:                .'<br />'
                   7586:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7587:                .'<br /><br />'
                   7588:             );
1.503     raeburn  7589:         } else {
                   7590:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7591:         }
1.497     foxr     7592:     }
                   7593:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7594:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7595: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7596: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7597:         push(@linenums,$current_line);
1.497     foxr     7598: 	$current_line++;
                   7599:     }
                   7600:     if ($lines > 1) {
                   7601: 	$r->print("<hr /><br />");
                   7602:     }
1.503     raeburn  7603:     return @linenums;
1.157     albertel 7604: }
1.423     albertel 7605: 
                   7606: =pod
                   7607: 
                   7608: =item scantron_bubble_selector
                   7609:   
                   7610:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7611:    possibly showing the existing the selected bubbles if known
1.423     albertel 7612: 
                   7613:  Arguments:
                   7614:     $r           - Apache request object
                   7615:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7616:     $line        - Number of the line being displayed.
1.503     raeburn  7617:     $questionnum - Question number (may include subquestion)
                   7618:     $error       - Type of error.
1.497     foxr     7619:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7620: 
                   7621: =cut
                   7622: 
1.157     albertel 7623: sub scantron_bubble_selector {
1.503     raeburn  7624:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7625:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7626: 
                   7627:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7628:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7629:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7630:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7631:             $max=$$scan_config{'BubblesPerRow'};
                   7632:             if (($scmode eq 'number') && ($max > 10)) {
                   7633:                 $max = 10;
                   7634:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7635:                 $max = 26;
                   7636:             }
                   7637:         } else {
                   7638:             $max = 10;
                   7639:         }
                   7640:     }
1.274     albertel 7641: 
1.157     albertel 7642:     my @alphabet=('A'..'Z');
1.503     raeburn  7643:     $r->print(&Apache::loncommon::start_data_table().
                   7644:               &Apache::loncommon::start_data_table_row());
                   7645:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7646:     for (my $i=0;$i<$max+1;$i++) {
                   7647: 	$r->print("\n".'<td align="center">');
                   7648: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7649: 	else { $r->print('&nbsp;'); }
                   7650: 	$r->print('</td>');
                   7651:     }
1.503     raeburn  7652:     $r->print(&Apache::loncommon::end_data_table_row().
                   7653:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7654:     for (my $i=0;$i<$max;$i++) {
                   7655: 	$r->print("\n".
                   7656: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7657: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7658:     }
1.503     raeburn  7659:     my $nobub_checked = ' ';
                   7660:     if ($error eq 'missingbubble') {
                   7661:         $nobub_checked = ' checked = "checked" ';
                   7662:     }
                   7663:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7664: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7665:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7666:               $line.'" value="'.$questionnum.'" /></td>');
                   7667:     $r->print(&Apache::loncommon::end_data_table_row().
                   7668:               &Apache::loncommon::end_data_table());
1.157     albertel 7669: }
                   7670: 
1.423     albertel 7671: =pod
                   7672: 
                   7673: =item num_matches
                   7674: 
1.424     albertel 7675:    Counts the number of characters that are the same between the two arguments.
                   7676: 
                   7677:  Arguments:
                   7678:    $orig - CODE from the scanline
                   7679:    $code - CODE to match against
                   7680: 
                   7681:  Returns:
                   7682:    $count - integer count of the number of same characters between the
                   7683:             two arguments
                   7684: 
1.423     albertel 7685: =cut
                   7686: 
1.194     albertel 7687: sub num_matches {
                   7688:     my ($orig,$code) = @_;
                   7689:     my @code=split(//,$code);
                   7690:     my @orig=split(//,$orig);
                   7691:     my $same=0;
                   7692:     for (my $i=0;$i<scalar(@code);$i++) {
                   7693: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7694:     }
                   7695:     return $same;
                   7696: }
                   7697: 
1.423     albertel 7698: =pod
                   7699: 
                   7700: =item scantron_get_closely_matching_CODEs
                   7701: 
1.424     albertel 7702:    Cycles through all CODEs and finds the set that has the greatest
                   7703:    number of same characters as the provided CODE
                   7704: 
                   7705:  Arguments:
                   7706:    $allcodes - hash ref returned by &get_codes()
                   7707:    $CODE     - CODE from the current scanline
                   7708: 
                   7709:  Returns:
                   7710:    2 element list
                   7711:     - first elements is number of how closely matching the best fit is 
                   7712:       (5 means best set has 5 matching characters)
                   7713:     - second element is an arrary ref containing the set of valid CODEs
                   7714:       that best fit the passed in CODE
                   7715: 
1.423     albertel 7716: =cut
                   7717: 
1.194     albertel 7718: sub scantron_get_closely_matching_CODEs {
                   7719:     my ($allcodes,$CODE)=@_;
                   7720:     my @CODEs;
                   7721:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7722: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7723:     }
                   7724: 
                   7725:     return ($#CODEs,$CODEs[-1]);
                   7726: }
                   7727: 
1.423     albertel 7728: =pod
                   7729: 
                   7730: =item get_codes
                   7731: 
1.424     albertel 7732:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7733:    set of remembered CODEs.
                   7734: 
                   7735:  Arguments:
                   7736:   $old_name - name of the set of remembered CODEs
                   7737:   $cdom     - domain of the course
                   7738:   $cnum     - internal course name
                   7739: 
                   7740:  Returns:
                   7741:   %allcodes - keys are the valid CODEs, values are all 1
                   7742: 
1.423     albertel 7743: =cut
                   7744: 
1.194     albertel 7745: sub get_codes {
1.280     foxr     7746:     my ($old_name, $cdom, $cnum) = @_;
                   7747:     if (!$old_name) {
                   7748: 	$old_name=$env{'form.scantron_CODElist'};
                   7749:     }
                   7750:     if (!$cdom) {
                   7751: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7752:     }
                   7753:     if (!$cnum) {
                   7754: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7755:     }
1.278     albertel 7756:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7757: 				    $cdom,$cnum);
                   7758:     my %allcodes;
                   7759:     if ($result{"type\0$old_name"} eq 'number') {
                   7760: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7761:     } else {
                   7762: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7763:     }
1.194     albertel 7764:     return %allcodes;
                   7765: }
                   7766: 
1.423     albertel 7767: =pod
                   7768: 
                   7769: =item scantron_validate_CODE
                   7770: 
1.424     albertel 7771:    Validates all scanlines in the selected file to not have any
                   7772:    invalid or underspecified CODEs and that none of the codes are
                   7773:    duplicated if this was requested.
                   7774: 
1.423     albertel 7775: =cut
                   7776: 
1.157     albertel 7777: sub scantron_validate_CODE {
                   7778:     my ($r,$currentphase) = @_;
1.257     albertel 7779:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7780:     if ($scantron_config{'CODElocation'} &&
                   7781: 	$scantron_config{'CODEstart'} &&
                   7782: 	$scantron_config{'CODElength'}) {
1.257     albertel 7783: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7784: 	    &FIXME_blow_up()
                   7785: 	}
                   7786:     } else {
                   7787: 	return (0,$currentphase+1);
                   7788:     }
                   7789:     
                   7790:     my %usedCODEs;
                   7791: 
1.194     albertel 7792:     my %allcodes=&get_codes();
1.186     albertel 7793: 
1.582     raeburn  7794:     my $nav_error;
1.649     raeburn  7795:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7796:     if ($nav_error) {
                   7797:         $r->print(&navmap_errormsg());
                   7798:         return(1,$currentphase);
                   7799:     }
1.447     foxr     7800: 
1.186     albertel 7801:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7802:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7803: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7804: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7805: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7806: 						 $scan_data);
                   7807: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7808: 	my $error=0;
1.224     albertel 7809: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7810: 	    &scantron_get_correction($r,$i,$scan_record,
                   7811: 				     \%scantron_config,
                   7812: 				     $line,'incorrectCODE',\%allcodes);
                   7813: 	    return(1,$currentphase);
                   7814: 	}
1.221     albertel 7815: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7816: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7817: 	    &scantron_get_correction($r,$i,$scan_record,
                   7818: 				     \%scantron_config,
1.194     albertel 7819: 				     $line,'incorrectCODE',\%allcodes);
                   7820: 	    return(1,$currentphase);
1.186     albertel 7821: 	}
1.214     albertel 7822: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7823: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7824: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7825: 	    &scantron_get_correction($r,$i,$scan_record,
                   7826: 				     \%scantron_config,
1.194     albertel 7827: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7828: 	    return(1,$currentphase);
1.186     albertel 7829: 	}
1.524     raeburn  7830: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7831:     }
1.157     albertel 7832:     return (0,$currentphase+1);
                   7833: }
                   7834: 
1.423     albertel 7835: =pod
                   7836: 
                   7837: =item scantron_validate_doublebubble
                   7838: 
1.424     albertel 7839:    Validates all scanlines in the selected file to not have any
                   7840:    bubble lines with multiple bubbles marked.
                   7841: 
1.423     albertel 7842: =cut
                   7843: 
1.157     albertel 7844: sub scantron_validate_doublebubble {
                   7845:     my ($r,$currentphase) = @_;
                   7846:     #get student info
                   7847:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7848:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7849:     my (undef,undef,$sequence)=
                   7850:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7851: 
                   7852:     #get scantron line setup
1.257     albertel 7853:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7854:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7855: 
                   7856:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7857:     unless (ref($navmap)) {
                   7858:         $r->print(&navmap_errormsg());
                   7859:         return(1,$currentphase);
                   7860:     }
                   7861:     my $map=$navmap->getResourceByUrl($sequence);
                   7862:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7863:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7864:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7865:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7866: 
1.583     raeburn  7867:     my $nav_error;
1.691     raeburn  7868:     if (ref($map)) {
                   7869:         $randomorder = $map->randomorder();
                   7870:         $randompick = $map->randompick();
                   7871:         if ($randomorder || $randompick) {
                   7872:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7873:             if ($nav_error) {
                   7874:                 $r->print(&navmap_errormsg());
                   7875:                 return(1,$currentphase);
                   7876:             }
                   7877:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7878:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7879:         }
                   7880:     } else {
                   7881:         $r->print(&navmap_errormsg());
                   7882:         return(1,$currentphase);
                   7883:     }
                   7884: 
1.649     raeburn  7885:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7886:     if ($nav_error) {
                   7887:         $r->print(&navmap_errormsg());
                   7888:         return(1,$currentphase);
                   7889:     }
1.447     foxr     7890: 
1.157     albertel 7891:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7892: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7893: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7894: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7895: 						 $scan_data,undef,\%idmap,$randomorder,
                   7896:                                                  $randompick,$sequence,\@master_seq,
                   7897:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7898:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7899: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7900: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7901: 				 'doublebubble',
1.691     raeburn  7902: 				 $$scan_record{'scantron.doubleerror'},
                   7903:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7904:     	return (1,$currentphase);
                   7905:     }
                   7906:     return (0,$currentphase+1);
                   7907: }
                   7908: 
1.423     albertel 7909: 
1.503     raeburn  7910: sub scantron_get_maxbubble {
1.649     raeburn  7911:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7912:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7913: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7914: 	&restore_bubble_lines();
1.257     albertel 7915: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7916:     }
1.330     albertel 7917: 
1.447     foxr     7918:     my (undef, undef, $sequence) =
1.257     albertel 7919: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7920: 
1.447     foxr     7921:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7922:     unless (ref($navmap)) {
                   7923:         if (ref($nav_error)) {
                   7924:             $$nav_error = 1;
                   7925:         }
1.591     raeburn  7926:         return;
1.582     raeburn  7927:     }
1.191     albertel 7928:     my $map=$navmap->getResourceByUrl($sequence);
                   7929:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7930:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7931: 
                   7932:     &Apache::lonxml::clear_problem_counter();
                   7933: 
1.557     raeburn  7934:     my $uname       = $env{'user.name'};
                   7935:     my $udom        = $env{'user.domain'};
1.435     foxr     7936:     my $cid         = $env{'request.course.id'};
                   7937:     my $total_lines = 0;
                   7938:     %bubble_lines_per_response = ();
1.447     foxr     7939:     %first_bubble_line         = ();
1.503     raeburn  7940:     %subdivided_bubble_lines   = ();
                   7941:     %responsetype_per_response = ();
1.691     raeburn  7942:     %masterseq_id_responsenum  = ();
1.554     raeburn  7943: 
1.447     foxr     7944:     my $response_number = 0;
                   7945:     my $bubble_line     = 0;
1.191     albertel 7946:     foreach my $resource (@resources) {
1.691     raeburn  7947:         my $resid = $resource->id(); 
1.672     raeburn  7948:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7949:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  7950:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7951: 	    foreach my $part_id (@{$parts}) {
                   7952:                 my $lines;
                   7953: 
                   7954: 	        # TODO - make this a persistent hash not an array.
                   7955: 
                   7956:                 # optionresponse, matchresponse and rankresponse type items 
                   7957:                 # render as separate sub-questions in exam mode.
                   7958:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7959:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7960:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7961:                     my ($numbub,$numshown);
                   7962:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7963:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7964:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7965:                         }
                   7966:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7967:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7968:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7969:                         }
                   7970:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7971:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7972:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7973:                         }
                   7974:                     }
                   7975:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7976:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7977:                     }
1.649     raeburn  7978:                     my $bubbles_per_row =
                   7979:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7980:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7981:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7982:                         $inner_bubble_lines++;
                   7983:                     }
                   7984:                     for (my $i=0; $i<$numshown; $i++) {
                   7985:                         $subdivided_bubble_lines{$response_number} .= 
                   7986:                             $inner_bubble_lines.',';
                   7987:                     }
                   7988:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7989:                     $lines = $numshown * $inner_bubble_lines;
                   7990:                 } else {
                   7991:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7992:                 }
1.542     raeburn  7993: 
                   7994:                 $first_bubble_line{$response_number} = $bubble_line;
                   7995: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7996:                 $responsetype_per_response{$response_number} = 
                   7997:                     $analysis->{$part_id.'.type'};
1.691     raeburn  7998:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  7999: 	        $response_number++;
                   8000: 
                   8001: 	        $bubble_line +=  $lines;
                   8002: 	        $total_lines +=  $lines;
                   8003: 	    }
                   8004:         }
                   8005:     }
1.552     raeburn  8006:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8007: 
                   8008:     &save_bubble_lines();
                   8009:     $env{'form.scantron_maxbubble'} =
                   8010: 	$total_lines;
                   8011:     return $env{'form.scantron_maxbubble'};
                   8012: }
1.523     raeburn  8013: 
1.649     raeburn  8014: sub bubblesheet_bubbles_per_row {
                   8015:     my ($scantron_config) = @_;
                   8016:     my $bubbles_per_row;
                   8017:     if (ref($scantron_config) eq 'HASH') {
                   8018:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8019:     }
                   8020:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8021:         $bubbles_per_row = 10;
                   8022:     }
                   8023:     return $bubbles_per_row;
                   8024: }
                   8025: 
1.157     albertel 8026: sub scantron_validate_missingbubbles {
                   8027:     my ($r,$currentphase) = @_;
                   8028:     #get student info
                   8029:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8030:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8031:     my (undef,undef,$sequence)=
                   8032:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8033: 
                   8034:     #get scantron line setup
1.257     albertel 8035:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8036:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8037: 
                   8038:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8039:     unless (ref($navmap)) {
                   8040:         $r->print(&navmap_errormsg());
                   8041:         return(1,$currentphase);
                   8042:     }
                   8043: 
                   8044:     my $map=$navmap->getResourceByUrl($sequence);
                   8045:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8046:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8047:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8048:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8049: 
1.582     raeburn  8050:     my $nav_error;
1.691     raeburn  8051:     if (ref($map)) {
                   8052:         $randomorder = $map->randomorder();
                   8053:         $randompick = $map->randompick();
                   8054:         if ($randomorder || $randompick) {
                   8055:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8056:             if ($nav_error) {
                   8057:                 $r->print(&navmap_errormsg());
                   8058:                 return(1,$currentphase);
                   8059:             }
                   8060:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8061:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8062:         }
                   8063:     } else {
                   8064:         $r->print(&navmap_errormsg());
                   8065:         return(1,$currentphase);
                   8066:     }
                   8067: 
                   8068: 
1.649     raeburn  8069:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8070:     if ($nav_error) {
1.691     raeburn  8071:         $r->print(&navmap_errormsg());
1.693     raeburn  8072:         return(1,$currentphase);
1.582     raeburn  8073:     }
1.691     raeburn  8074: 
1.157     albertel 8075:     if (!$max_bubble) { $max_bubble=2**31; }
                   8076:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8077: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8078: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8079: 	my $scan_record =
                   8080:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8081: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8082:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8083:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8084: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8085: 	my @to_correct;
1.470     foxr     8086: 	
                   8087: 	# Probably here's where the error is...
                   8088: 
1.157     albertel 8089: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8090:             my $lastbubble;
                   8091:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8092:                my $question = $1;
                   8093:                my $subquestion = $2;
1.691     raeburn  8094:                my ($first,$responsenum);
                   8095:                if ($randomorder || $randompick) {
                   8096:                    $responsenum = $respnumlookup{$question-1};
                   8097:                    $first = $startline{$question-1};
                   8098:                } else {
                   8099:                    $responsenum = $question-1; 
                   8100:                    $first = $first_bubble_line{$responsenum};
                   8101:                }
                   8102:                if (!defined($first)) { next; }
                   8103:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8104:                my $subcount = 1;
                   8105:                while ($subcount<$subquestion) {
                   8106:                    $first += $subans[$subcount-1];
                   8107:                    $subcount ++;
                   8108:                }
                   8109:                my $count = $subans[$subquestion-1];
                   8110:                $lastbubble = $first + $count;
                   8111:             } else {
1.691     raeburn  8112:                my ($first,$responsenum);
                   8113:                if ($randomorder || $randompick) {
                   8114:                    $responsenum = $respnumlookup{$missing-1};
                   8115:                    $first = $startline{$missing-1};
                   8116:                } else {
                   8117:                    $responsenum = $missing-1;
                   8118:                    $first = $first_bubble_line{$responsenum};
                   8119:                }
                   8120:                if (!defined($first)) { next; }
                   8121:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8122:             }
                   8123:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8124: 	    push(@to_correct,$missing);
                   8125: 	}
                   8126: 	if (@to_correct) {
                   8127: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8128: 				     $line,'missingbubble',\@to_correct,
                   8129:                                      $randomorder,$randompick,\%respnumlookup,
                   8130:                                      \%startline);
1.157     albertel 8131: 	    return (1,$currentphase);
                   8132: 	}
                   8133: 
                   8134:     }
                   8135:     return (0,$currentphase+1);
                   8136: }
                   8137: 
1.663     raeburn  8138: sub hand_bubble_option {
                   8139:     my (undef, undef, $sequence) =
                   8140:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8141:     return if ($sequence eq '');
                   8142:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8143:     unless (ref($navmap)) {
                   8144:         return;
                   8145:     }
                   8146:     my $needs_hand_bubbles;
                   8147:     my $map=$navmap->getResourceByUrl($sequence);
                   8148:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8149:     foreach my $res (@resources) {
                   8150:         if (ref($res)) {
                   8151:             if ($res->is_problem()) {
                   8152:                 my $partlist = $res->parts();
                   8153:                 foreach my $part (@{ $partlist }) {
                   8154:                     my @types = $res->responseType($part);
                   8155:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8156:                         $needs_hand_bubbles = 1;
                   8157:                         last;
                   8158:                     }
                   8159:                 }
                   8160:             }
                   8161:         }
                   8162:     }
                   8163:     if ($needs_hand_bubbles) {
                   8164:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8165:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8166:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8167:                &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 />').
                   8168:                '<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;'.
                   8169:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   8170:     }
                   8171:     return;
                   8172: }
1.423     albertel 8173: 
1.82      albertel 8174: sub scantron_process_students {
1.608     www      8175:     my ($r,$symb) = @_;
1.513     foxr     8176: 
1.257     albertel 8177:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8178:     if (!$symb) {
                   8179: 	return '';
                   8180:     }
1.324     albertel 8181:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8182: 
1.257     albertel 8183:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8184:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8185:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8186:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8187:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8188:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8189:     unless (ref($navmap)) {
                   8190:         $r->print(&navmap_errormsg());
                   8191:         return '';
1.691     raeburn  8192:     }
1.83      albertel 8193:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8194:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8195:         %grader_randomlists_by_symb);
1.677     raeburn  8196:     if (ref($map)) {
                   8197:         $randomorder = $map->randomorder();
1.689     raeburn  8198:         $randompick = $map->randompick();
1.691     raeburn  8199:     } else {
                   8200:         $r->print(&navmap_errormsg());
                   8201:         return '';
1.677     raeburn  8202:     }
1.691     raeburn  8203:     my $nav_error;
1.83      albertel 8204:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8205:     if ($randomorder || $randompick) {
                   8206:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8207:         if ($nav_error) {
                   8208:             $r->print(&navmap_errormsg());
                   8209:             return '';
                   8210:         }
                   8211:     }
1.557     raeburn  8212:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8213:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8214: 
1.554     raeburn  8215:     my ($uname,$udom);
1.82      albertel 8216:     my $result= <<SCANTRONFORM;
1.81      albertel 8217: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8218:   <input type="hidden" name="command" value="scantron_configphase" />
                   8219:   $default_form_data
                   8220: SCANTRONFORM
1.82      albertel 8221:     $r->print($result);
                   8222: 
                   8223:     my @delayqueue;
1.542     raeburn  8224:     my (%completedstudents,%scandata);
1.140     albertel 8225:     
1.520     www      8226:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8227:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8228:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8229:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8230:     $r->print('<br />');
1.140     albertel 8231:     my $start=&Time::HiRes::time();
1.158     albertel 8232:     my $i=-1;
1.542     raeburn  8233:     my $started;
1.447     foxr     8234: 
1.649     raeburn  8235:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8236:     if ($nav_error) {
                   8237:         $r->print(&navmap_errormsg());
                   8238:         return '';
                   8239:     }
                   8240: 
1.513     foxr     8241:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8242:     # the user and return.
                   8243: 
                   8244:     if ($ssi_error) {
                   8245: 	$r->print("</form>");
                   8246: 	&ssi_print_error($r);
1.520     www      8247:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8248: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8249:     }
1.447     foxr     8250: 
1.542     raeburn  8251:     my %lettdig = &letter_to_digits();
                   8252:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8253:     my %orderedforcode;
1.542     raeburn  8254: 
1.157     albertel 8255:     while ($i<$scanlines->{'count'}) {
                   8256:  	($uname,$udom)=('','');
                   8257:  	$i++;
1.200     albertel 8258:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8259:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8260: 	if ($started) {
1.667     www      8261: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8262: 	}
                   8263: 	$started=1;
1.691     raeburn  8264:         my %respnumlookup = ();
                   8265:         my %startline = ();
                   8266:         my $total;
1.157     albertel 8267:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8268:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8269:                                                  $randompick,$sequence,\@master_seq,
                   8270:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8271:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8272:                                                  \$total);
1.157     albertel 8273:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8274:  					      \%idmap,$i)) {
                   8275:   	    &scantron_add_delay(\@delayqueue,$line,
                   8276:  				'Unable to find a student that matches',1);
                   8277:  	    next;
                   8278:   	}
                   8279:  	if (exists $completedstudents{$uname}) {
                   8280:  	    &scantron_add_delay(\@delayqueue,$line,
                   8281:  				'Student '.$uname.' has multiple sheets',2);
                   8282:  	    next;
                   8283:  	}
1.677     raeburn  8284:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8285:         my $user = $uname.':'.$usec;
1.157     albertel 8286:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8287: 
1.677     raeburn  8288:         my $scancode;
                   8289:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8290:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8291:             $scancode = $scan_record->{'scantron.CODE'};
                   8292:         } else {
                   8293:             $scancode = '';
                   8294:         }
                   8295: 
                   8296:         my @mapresources = @resources;
1.689     raeburn  8297:         if ($randomorder || $randompick) {
1.678     raeburn  8298:             @mapresources = 
1.691     raeburn  8299:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8300:                              \%orderedforcode);
1.677     raeburn  8301:         }
1.586     raeburn  8302:         my (%partids_by_symb,$res_error);
1.677     raeburn  8303:         foreach my $resource (@mapresources) {
1.586     raeburn  8304:             my $ressymb;
                   8305:             if (ref($resource)) {
                   8306:                 $ressymb = $resource->symb();
                   8307:             } else {
                   8308:                 $res_error = 1;
                   8309:                 last;
                   8310:             }
1.557     raeburn  8311:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8312:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8313:                 my ($analysis,$parts) =
1.672     raeburn  8314:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8315:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8316:                 $partids_by_symb{$ressymb} = $parts;
                   8317:             } else {
                   8318:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8319:             }
1.554     raeburn  8320:         }
                   8321: 
1.586     raeburn  8322:         if ($res_error) {
                   8323:             &scantron_add_delay(\@delayqueue,$line,
                   8324:                                 'An error occurred while grading student '.$uname,2);
                   8325:             next;
                   8326:         }
                   8327: 
1.330     albertel 8328: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8329:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8330: 
                   8331: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8332: 	    &scantron_putfile($scanlines,$scan_data);
                   8333: 	}
1.161     albertel 8334: 	
1.542     raeburn  8335:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8336:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8337:                                    $bubbles_per_row,$randomorder,$randompick,
                   8338:                                    \%respnumlookup,\%startline) 
                   8339:             eq 'ssi_error') {
1.542     raeburn  8340:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8341:             $r->print("</form>");
                   8342:             &ssi_print_error($r);
                   8343:             &Apache::lonnet::remove_lock($lock);
                   8344:             return '';      # Why return ''?  Beats me.
                   8345:         }
1.513     foxr     8346: 
1.692     raeburn  8347:         if (($scancode) && ($randomorder || $randompick)) {
                   8348:             my $parmresult =
                   8349:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8350:                                                        '0_examcode',2,$scancode,
                   8351:                                                        'string_examcode',$uname,
                   8352:                                                        $udom);
                   8353:         }
1.140     albertel 8354: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8355:         if ($env{'form.verifyrecord'}) {
                   8356:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8357:             if ($randompick) {
                   8358:                 if ($total) {
                   8359:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8360:                 }
                   8361:             }
                   8362: 
1.542     raeburn  8363:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8364:             chomp($studentdata);
                   8365:             $studentdata =~ s/\r$//;
                   8366:             my $studentrecord = '';
                   8367:             my $counter = -1;
1.677     raeburn  8368:             foreach my $resource (@mapresources) {
1.554     raeburn  8369:                 my $ressymb = $resource->symb();
1.542     raeburn  8370:                 ($counter,my $recording) =
                   8371:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8372:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8373:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8374:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8375:                 $studentrecord .= $recording;
                   8376:             }
                   8377:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8378:                 &Apache::lonxml::clear_problem_counter();
                   8379:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8380:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8381:                                            $bubbles_per_row,$randomorder,$randompick,
                   8382:                                            \%respnumlookup,\%startline) 
                   8383:                     eq 'ssi_error') {
1.554     raeburn  8384:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8385:                     $r->print("</form>");
                   8386:                     &ssi_print_error($r);
                   8387:                     &Apache::lonnet::remove_lock($lock);
                   8388:                     delete($completedstudents{$uname});
                   8389:                     return '';
                   8390:                 }
1.542     raeburn  8391:                 $counter = -1;
                   8392:                 $studentrecord = '';
1.677     raeburn  8393:                 foreach my $resource (@mapresources) {
1.554     raeburn  8394:                     my $ressymb = $resource->symb();
1.542     raeburn  8395:                     ($counter,my $recording) =
                   8396:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8397:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8398:                                                  \%scantron_config,\%lettdig,$numletts,
                   8399:                                                  $randomorder,$randompick,\%respnumlookup,
                   8400:                                                  \%startline);
1.542     raeburn  8401:                     $studentrecord .= $recording;
                   8402:                 }
                   8403:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8404:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8405:                     if ($scancode eq '') {
1.658     bisitz   8406:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8407:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8408:                     } else {
1.658     bisitz   8409:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8410:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8411:                     }
                   8412:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8413:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8414:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8415:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8416:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8417:                               '<td>'.&mt('Bubblesheet').'</td>'.
                   8418:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8419:                               &Apache::loncommon::end_data_table_row().
                   8420:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8421:                               '<td>'.&mt('Stored submissions').'</td>'.
                   8422:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8423:                               &Apache::loncommon::end_data_table_row().
                   8424:                               &Apache::loncommon::end_data_table().'</p>');
                   8425:                 } else {
                   8426:                     $r->print('<br /><span class="LC_warning">'.
                   8427:                              &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 />'.
                   8428:                              &mt("As a consequence, this user's submission history records two tries.").
                   8429:                                  '</span><br />');
                   8430:                 }
                   8431:             }
                   8432:         }
1.543     raeburn  8433:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8434:     } continue {
1.330     albertel 8435: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8436: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8437:     }
1.140     albertel 8438:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8439:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8440: #    my $lasttime = &Time::HiRes::time()-$start;
                   8441: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8442: 
1.200     albertel 8443:     $r->print("</form>");
1.157     albertel 8444:     return '';
1.75      albertel 8445: }
1.157     albertel 8446: 
1.557     raeburn  8447: sub graders_resources_pass {
1.649     raeburn  8448:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8449:         $bubbles_per_row) = @_;
1.557     raeburn  8450:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8451:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8452:         foreach my $resource (@{$resources}) {
                   8453:             my $ressymb = $resource->symb();
                   8454:             my ($analysis,$parts) =
                   8455:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8456:                                           $env{'user.name'},$env{'user.domain'},
                   8457:                                           1,$bubbles_per_row);
1.557     raeburn  8458:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8459:             if (ref($analysis) eq 'HASH') {
                   8460:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8461:                     $grader_randomlists_by_symb->{$ressymb} =
                   8462:                         $analysis->{'parts_withrandomlist'};
                   8463:                 }
                   8464:             }
                   8465:         }
                   8466:     }
                   8467:     return;
                   8468: }
                   8469: 
1.678     raeburn  8470: =pod
                   8471: 
                   8472: =item users_order
                   8473: 
                   8474:   Returns array of resources in current map, ordered based on either CODE,
                   8475:   if this is a CODEd exam, or based on student's identity if this is a 
                   8476:   "NAMEd" exam.
                   8477: 
1.691     raeburn  8478:   Should be used when randomorder and/or randompick applied when the 
                   8479:   corresponding exam was printed, prior to students completing bubblesheets 
                   8480:   for the version of the exam the student received.
1.678     raeburn  8481: 
                   8482: =cut
                   8483: 
                   8484: sub users_order  {
1.691     raeburn  8485:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8486:     my @mapresources;
1.691     raeburn  8487:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8488:         return @mapresources;
1.691     raeburn  8489:     }
                   8490:     if ($scancode) {
                   8491:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8492:             @mapresources = @{$orderedforcode->{$scancode}};
                   8493:         } else {
                   8494:             $env{'form.CODE'} = $scancode;
                   8495:             my $actual_seq =
                   8496:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8497:                                                                $master_seq,
                   8498:                                                                $user,$scancode,1);
                   8499:             if (ref($actual_seq) eq 'ARRAY') {
                   8500:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8501:                 if (ref($orderedforcode) eq 'HASH') {
                   8502:                     if (@mapresources > 0) { 
                   8503:                         $orderedforcode->{$scancode} = \@mapresources;
                   8504:                     }
                   8505:                 }
                   8506:             }
                   8507:             delete($env{'form.CODE'});
1.678     raeburn  8508:         }
                   8509:     } else {
                   8510:         my $actual_seq =
                   8511:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8512:                                                            $master_seq,
1.688     raeburn  8513:                                                            $user,undef,1);
1.678     raeburn  8514:         if (ref($actual_seq) eq 'ARRAY') {
                   8515:             @mapresources = 
                   8516:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8517:         }
1.691     raeburn  8518:     }
                   8519:     return @mapresources;
1.678     raeburn  8520: }
                   8521: 
1.542     raeburn  8522: sub grade_student_bubbles {
1.691     raeburn  8523:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8524:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8525:     my $uselookup = 0;
                   8526:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8527:         (ref($startline) eq 'HASH')) {
                   8528:         $uselookup = 1;
                   8529:     }
                   8530: 
1.554     raeburn  8531:     if (ref($resources) eq 'ARRAY') {
                   8532:         my $count = 0;
                   8533:         foreach my $resource (@{$resources}) {
                   8534:             my $ressymb = $resource->symb();
                   8535:             my %form = ('submitted'      => 'scantron',
                   8536:                         'grade_target'   => 'grade',
                   8537:                         'grade_username' => $uname,
                   8538:                         'grade_domain'   => $udom,
                   8539:                         'grade_courseid' => $env{'request.course.id'},
                   8540:                         'grade_symb'     => $ressymb,
                   8541:                         'CODE'           => $scancode
                   8542:                        );
1.649     raeburn  8543:             if ($bubbles_per_row ne '') {
                   8544:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8545:             }
1.663     raeburn  8546:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8547:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8548:             }
1.554     raeburn  8549:             if (ref($parts) eq 'HASH') {
                   8550:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8551:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8552:                         if ($uselookup) {
                   8553:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8554:                         } else {
                   8555:                             $form{'scantron_questnum_start.'.$part} =
                   8556:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8557:                         }
1.554     raeburn  8558:                         $count++;
                   8559:                     }
                   8560:                 }
                   8561:             }
                   8562:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8563:             return 'ssi_error' if ($ssi_error);
                   8564:             last if (&Apache::loncommon::connection_aborted($r));
                   8565:         }
1.542     raeburn  8566:     }
                   8567:     return;
                   8568: }
                   8569: 
1.157     albertel 8570: sub scantron_upload_scantron_data {
1.608     www      8571:     my ($r,$symb)=@_;
1.565     raeburn  8572:     my $dom = $env{'request.role.domain'};
                   8573:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8574:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8575:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8576: 							  'domainid',
1.565     raeburn  8577: 							  'coursename',$dom);
                   8578:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8579:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8580:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8581:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8582:     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 8583:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8584:     function checkUpload(formname) {
                   8585: 	if (formname.upfile.value == "") {
1.579     raeburn  8586: 	    alert("'.$nofile_alert.'");
1.157     albertel 8587: 	    return false;
                   8588: 	}
1.565     raeburn  8589:         if (formname.courseid.value == "") {
1.579     raeburn  8590:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8591:             return false;
                   8592:         }
1.157     albertel 8593: 	formname.submit();
                   8594:     }
1.565     raeburn  8595: 
                   8596:     function ToSyllabus() {
                   8597:         var cdom = '."'$dom'".';
                   8598:         var cnum = document.rules.courseid.value;
                   8599:         if (cdom == "" || cdom == null) {
                   8600:             return;
                   8601:         }
                   8602:         if (cnum == "" || cnum == null) {
                   8603:            return;
                   8604:         }
                   8605:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8606:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8607:         return;
                   8608:     }
                   8609: 
1.597     wenzelju 8610: '));
                   8611:     $r->print('
1.648     bisitz   8612: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8613: 
1.492     albertel 8614: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8615: '.$default_form_data.
                   8616:   &Apache::lonhtmlcommon::start_pick_box().
                   8617:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8618:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8619:   &Apache::lonhtmlcommon::row_closure().
                   8620:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8621:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8622:   &Apache::lonhtmlcommon::row_closure().
                   8623:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8624:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8625:   &Apache::lonhtmlcommon::row_closure().
                   8626:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8627:   '<input type="file" name="upfile" size="50" />'.
                   8628:   &Apache::lonhtmlcommon::row_closure(1).
                   8629:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8630: 
1.492     albertel 8631: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8632: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8633: </form>
1.492     albertel 8634: ');
1.157     albertel 8635:     return '';
                   8636: }
                   8637: 
1.423     albertel 8638: 
1.157     albertel 8639: sub scantron_upload_scantron_data_save {
1.608     www      8640:     my($r,$symb)=@_;
1.182     albertel 8641:     my $doanotherupload=
                   8642: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8643: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8644: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8645: 	'</form>'."\n";
1.257     albertel 8646:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8647: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8648: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8649: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8650: 	unless ($symb) {
1.182     albertel 8651: 	    $r->print($doanotherupload);
                   8652: 	}
1.162     albertel 8653: 	return '';
                   8654:     }
1.257     albertel 8655:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8656:     my $uploadedfile;
1.567     raeburn  8657:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8658:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8659:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8660:     } else {
1.568     raeburn  8661:         my $result = 
                   8662:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8663:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8664: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8665: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8666:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8667: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8668:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8669:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8670:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8671: 	} else {
1.567     raeburn  8672: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8673:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8674: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8675: 	}
                   8676:     }
1.174     albertel 8677:     if ($symb) {
1.612     www      8678: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8679:     } else {
1.182     albertel 8680: 	$r->print($doanotherupload);
1.174     albertel 8681:     }
1.157     albertel 8682:     return '';
                   8683: }
                   8684: 
1.567     raeburn  8685: sub validate_uploaded_scantron_file {
                   8686:     my ($cdom,$cname,$fname) = @_;
                   8687:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8688:     my @lines;
                   8689:     if ($scanlines ne '-1') {
                   8690:         @lines=split("\n",$scanlines,-1);
                   8691:     }
                   8692:     my $output;
                   8693:     if (@lines) {
                   8694:         my (%counts,$max_match_format);
                   8695:         my ($max_match_count,$max_match_pct) = (0,0);
                   8696:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8697:         my %idmap = &username_to_idmap($classlist);
                   8698:         foreach my $key (keys(%idmap)) {
                   8699:             my $lckey = lc($key);
                   8700:             $idmap{$lckey} = $idmap{$key};
                   8701:         }
                   8702:         my %unique_formats;
                   8703:         my @formatlines = &get_scantronformat_file();
                   8704:         foreach my $line (@formatlines) {
                   8705:             chomp($line);
                   8706:             my @config = split(/:/,$line);
                   8707:             my $idstart = $config[5];
                   8708:             my $idlength = $config[6];
                   8709:             if (($idstart ne '') && ($idlength > 0)) {
                   8710:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8711:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8712:                 } else {
                   8713:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8714:                 }
                   8715:             }
                   8716:         }
                   8717:         foreach my $key (keys(%unique_formats)) {
                   8718:             my ($idstart,$idlength) = split(':',$key);
                   8719:             %{$counts{$key}} = (
                   8720:                                'found'   => 0,
                   8721:                                'total'   => 0,
                   8722:                               );
                   8723:             foreach my $line (@lines) {
                   8724:                 next if ($line =~ /^#/);
                   8725:                 next if ($line =~ /^[\s\cz]*$/);
                   8726:                 my $id = substr($line,$idstart-1,$idlength);
                   8727:                 $id = lc($id);
                   8728:                 if (exists($idmap{$id})) {
                   8729:                     $counts{$key}{'found'} ++;
                   8730:                 }
                   8731:                 $counts{$key}{'total'} ++;
                   8732:             }
                   8733:             if ($counts{$key}{'total'}) {
                   8734:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8735:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8736:                     $max_match_pct = $percent_match;
                   8737:                     $max_match_format = $key;
                   8738:                     $max_match_count = $counts{$key}{'total'};
                   8739:                 }
                   8740:             }
                   8741:         }
                   8742:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8743:             my $format_descs;
                   8744:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8745:             for (my $i=0; $i<$numwithformat; $i++) {
                   8746:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8747:                 if ($i<$numwithformat-2) {
                   8748:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8749:                 } elsif ($i==$numwithformat-2) {
                   8750:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8751:                 } elsif ($i==$numwithformat-1) {
                   8752:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8753:                 }
                   8754:             }
                   8755:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8756:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8757:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8758:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8759:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8760:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8761:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8762:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8763:                        '</ul>';
                   8764:         }
                   8765:     } else {
                   8766:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8767:     }
                   8768:     return $output;
                   8769: }
                   8770: 
1.202     albertel 8771: sub valid_file {
                   8772:     my ($requested_file)=@_;
                   8773:     foreach my $filename (sort(&scantron_filenames())) {
                   8774: 	if ($requested_file eq $filename) { return 1; }
                   8775:     }
                   8776:     return 0;
                   8777: }
                   8778: 
                   8779: sub scantron_download_scantron_data {
1.608     www      8780:     my ($r,$symb)=@_;
                   8781:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8782:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8783:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8784:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8785:     if (! &valid_file($file)) {
1.492     albertel 8786: 	$r->print('
1.202     albertel 8787: 	<p>
1.686     bisitz   8788: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8789:         </p>
1.492     albertel 8790: ');
1.202     albertel 8791: 	return;
                   8792:     }
                   8793:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8794:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8795:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8796:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8797:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8798:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8799:     $r->print('
1.202     albertel 8800:     <p>
1.492     albertel 8801: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8802: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8803:     </p>
                   8804:     <p>
1.492     albertel 8805: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8806: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8807:     </p>
                   8808:     <p>
1.492     albertel 8809: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8810: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8811:     </p>
1.492     albertel 8812: ');
1.202     albertel 8813:     return '';
                   8814: }
1.157     albertel 8815: 
1.523     raeburn  8816: sub checkscantron_results {
1.608     www      8817:     my ($r,$symb) = @_;
1.523     raeburn  8818:     if (!$symb) {return '';}
                   8819:     my $cid = $env{'request.course.id'};
1.542     raeburn  8820:     my %lettdig = &letter_to_digits();
1.523     raeburn  8821:     my $numletts = scalar(keys(%lettdig));
                   8822:     my $cnum = $env{'course.'.$cid.'.num'};
                   8823:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8824:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8825:     my %record;
                   8826:     my %scantron_config =
                   8827:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8828:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8829:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8830:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8831:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8832:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8833:     unless (ref($navmap)) {
                   8834:         $r->print(&navmap_errormsg());
                   8835:         return '';
                   8836:     }
1.523     raeburn  8837:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8838:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8839:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8840:     if (ref($map)) { 
                   8841:         $randomorder=$map->randomorder();
1.689     raeburn  8842:         $randompick=$map->randompick();
1.677     raeburn  8843:     }
1.557     raeburn  8844:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8845:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8846:     if ($nav_error) {
                   8847:         $r->print(&navmap_errormsg());
                   8848:         return '';
1.678     raeburn  8849:     }
1.673     raeburn  8850:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8851:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8852:     my ($uname,$udom);
1.523     raeburn  8853:     my (%scandata,%lastname,%bylast);
                   8854:     $r->print('
                   8855: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8856: 
                   8857:     my @delayqueue;
                   8858:     my %completedstudents;
                   8859: 
1.691     raeburn  8860:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8861:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.678     raeburn  8862:     my ($username,$domain,$started,%ordered);
1.649     raeburn  8863:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8864:     if ($nav_error) {
                   8865:         $r->print(&navmap_errormsg());
                   8866:         return '';
                   8867:     }
1.523     raeburn  8868: 
1.667     www      8869:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8870:     my $start=&Time::HiRes::time();
                   8871:     my $i=-1;
                   8872: 
                   8873:     while ($i<$scanlines->{'count'}) {
                   8874:         ($username,$domain,$uname)=('','','');
                   8875:         $i++;
                   8876:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8877:         if ($line=~/^[\s\cz]*$/) { next; }
                   8878:         if ($started) {
1.667     www      8879:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8880:         }
                   8881:         $started=1;
                   8882:         my $scan_record=
                   8883:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8884:                                                      $scan_data);
1.693     raeburn  8885:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8886:                                               \%idmap,$i)) {
1.523     raeburn  8887:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8888:                                 'Unable to find a student that matches',1);
                   8889:             next;
                   8890:         }
                   8891:         if (exists $completedstudents{$uname}) {
                   8892:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8893:                                 'Student '.$uname.' has multiple sheets',2);
                   8894:             next;
                   8895:         }
                   8896:         my $pid = $scan_record->{'scantron.ID'};
                   8897:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8898:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  8899:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8900:         my $user = $uname.':'.$usec;
1.523     raeburn  8901:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  8902: 
1.678     raeburn  8903:         my $scancode;
1.677     raeburn  8904:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8905:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8906:             $scancode = $scan_record->{'scantron.CODE'};
                   8907:         } else {
                   8908:             $scancode = '';
                   8909:         }
                   8910: 
                   8911:         my @mapresources = @resources;
1.691     raeburn  8912:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8913:         my %respnumlookup=();
                   8914:         my %startline=();
1.689     raeburn  8915:         if ($randomorder || $randompick) {
1.678     raeburn  8916:             @mapresources =
1.691     raeburn  8917:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8918:                              \%orderedforcode);
                   8919:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   8920:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   8921:                                              \%grader_partids_by_symb,\%orderedforcode,
                   8922:                                              \%respnumlookup,\%startline);
                   8923:             if ($randompick && $total) {
                   8924:                 $lastpos = $total*$scantron_config{'Qlength'};
                   8925:             }
1.677     raeburn  8926:         }
1.691     raeburn  8927:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8928:         chomp($scandata{$pid});
                   8929:         $scandata{$pid} =~ s/\r$//;
                   8930: 
1.523     raeburn  8931:         my $counter = -1;
1.677     raeburn  8932:         foreach my $resource (@mapresources) {
1.557     raeburn  8933:             my $parts;
1.554     raeburn  8934:             my $ressymb = $resource->symb();
1.557     raeburn  8935:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8936:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8937:                 (my $analysis,$parts) =
1.672     raeburn  8938:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8939:                                               $username,$domain,undef,
                   8940:                                               $bubbles_per_row);
1.557     raeburn  8941:             } else {
                   8942:                 $parts = $grader_partids_by_symb{$ressymb};
                   8943:             }
1.542     raeburn  8944:             ($counter,my $recording) =
                   8945:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8946:                                          $scandata{$pid},$parts,
1.691     raeburn  8947:                                          \%scantron_config,\%lettdig,$numletts,
                   8948:                                          $randomorder,$randompick,
                   8949:                                          \%respnumlookup,\%startline);
1.542     raeburn  8950:             $record{$pid} .= $recording;
1.523     raeburn  8951:         }
                   8952:     }
                   8953:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8954:     $r->print('<br />');
                   8955:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8956:     $passed = 0;
                   8957:     $failed = 0;
                   8958:     $numstudents = 0;
                   8959:     foreach my $last (sort(keys(%bylast))) {
                   8960:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8961:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8962:                 my $showscandata = $scandata{$pid};
                   8963:                 my $showrecord = $record{$pid};
                   8964:                 $showscandata =~ s/\s/&nbsp;/g;
                   8965:                 $showrecord =~ s/\s/&nbsp;/g;
                   8966:                 if ($scandata{$pid} eq $record{$pid}) {
                   8967:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8968:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8969: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8970: '</tr>'."\n".
                   8971: '<tr class="'.$css_class.'">'."\n".
                   8972: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8973:                     $passed ++;
                   8974:                 } else {
                   8975:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8976:                     $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  8977: '</tr>'."\n".
                   8978: '<tr class="'.$css_class.'">'."\n".
                   8979: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8980: '</tr>'."\n";
                   8981:                     $failed ++;
                   8982:                 }
                   8983:                 $numstudents ++;
                   8984:             }
                   8985:         }
                   8986:     }
1.648     bisitz   8987:     $r->print(
                   8988:         '<p>'
                   8989:        .&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).',
                   8990:             '<b>',
                   8991:             $numstudents,
                   8992:             '</b>',
                   8993:             $env{'form.scantron_maxbubble'})
                   8994:        .'</p>'
                   8995:     );
1.682     raeburn  8996:     $r->print('<p>'
1.683     raeburn  8997:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  8998:              .'<br />'
                   8999:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9000:              .'</p>'
                   9001:     );
1.523     raeburn  9002:     if ($passed) {
1.572     www      9003:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9004:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9005:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9006:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9007:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9008:                  $okstudents."\n".
                   9009:                  &Apache::loncommon::end_data_table().'<br />');
                   9010:     }
                   9011:     if ($failed) {
1.572     www      9012:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9013:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9014:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9015:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9016:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9017:                  $badstudents."\n".
                   9018:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9019:                  &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  9020:     }
1.614     www      9021:     $r->print('</form><br />');
1.523     raeburn  9022:     return;
                   9023: }
                   9024: 
1.542     raeburn  9025: sub verify_scantron_grading {
1.554     raeburn  9026:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9027:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9028:         $respnumlookup,$startline) = @_;
1.542     raeburn  9029:     my ($record,%expected,%startpos);
                   9030:     return ($counter,$record) if (!ref($resource));
                   9031:     return ($counter,$record) if (!$resource->is_problem());
                   9032:     my $symb = $resource->symb();
1.554     raeburn  9033:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9034:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9035:         $counter ++;
                   9036:         $expected{$part_id} = 0;
1.691     raeburn  9037:         my $respnum = $counter;
                   9038:         if ($randomorder || $randompick) {
                   9039:             $respnum = $respnumlookup->{$counter};
                   9040:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9041:         } else {
                   9042:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9043:         }
                   9044:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9045:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9046:             foreach my $item (@sub_lines) {
                   9047:                 $expected{$part_id} += $item;
                   9048:             }
                   9049:         } else {
1.691     raeburn  9050:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9051:         }
                   9052:     }
                   9053:     if ($symb) {
                   9054:         my %recorded;
                   9055:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9056:         if ($returnhash{'version'}) {
                   9057:             my %lasthash=();
                   9058:             my $version;
                   9059:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9060:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9061:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9062:                 }
                   9063:             }
                   9064:             foreach my $key (keys(%lasthash)) {
                   9065:                 if ($key =~ /\.scantron$/) {
                   9066:                     my $value = &unescape($lasthash{$key});
                   9067:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9068:                     if ($value eq '') {
                   9069:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9070:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9071:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9072:                             }
                   9073:                         }
                   9074:                     } else {
                   9075:                         my @tocheck;
                   9076:                         my @items = split(//,$value);
                   9077:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9078:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9079:                             if (@items < $expected{$part_id}) {
                   9080:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9081:                                 my @singles = split(//,$fragment);
                   9082:                                 foreach my $pos (@singles) {
                   9083:                                     if ($pos eq ' ') {
                   9084:                                         push(@tocheck,$pos);
                   9085:                                     } else {
                   9086:                                         my $next = shift(@items);
                   9087:                                         push(@tocheck,$next);
                   9088:                                     }
                   9089:                                 }
                   9090:                             } else {
                   9091:                                 @tocheck = @items;
                   9092:                             }
                   9093:                             foreach my $letter (@tocheck) {
                   9094:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9095:                                     if ($letter !~ /^[A-J]$/) {
                   9096:                                         $letter = $scantron_config->{'Qoff'};
                   9097:                                     }
                   9098:                                     $recorded{$part_id} .= $letter;
                   9099:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9100:                                     my $digit;
                   9101:                                     if ($letter !~ /^[A-J]$/) {
                   9102:                                         $digit = $scantron_config->{'Qoff'};
                   9103:                                     } else {
                   9104:                                         $digit = $lettdig->{$letter};
                   9105:                                     }
                   9106:                                     $recorded{$part_id} .= $digit;
                   9107:                                 }
                   9108:                             }
                   9109:                         } else {
                   9110:                             @tocheck = @items;
                   9111:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9112:                                 my $curr_sub = shift(@tocheck);
                   9113:                                 my $digit;
                   9114:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9115:                                     $digit = $lettdig->{$curr_sub}-1;
                   9116:                                 }
                   9117:                                 if ($curr_sub eq 'J') {
                   9118:                                     $digit += scalar($numletts);
                   9119:                                 }
                   9120:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9121:                                     if ($j == $digit) {
                   9122:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9123:                                     } else {
                   9124:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9125:                                     }
                   9126:                                 }
                   9127:                             }
                   9128:                         }
                   9129:                     }
                   9130:                 }
                   9131:             }
                   9132:         }
1.554     raeburn  9133:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9134:             if ($recorded{$part_id} eq '') {
                   9135:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9136:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9137:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9138:                     }
                   9139:                 }
                   9140:             }
                   9141:             $record .= $recorded{$part_id};
                   9142:         }
                   9143:     }
                   9144:     return ($counter,$record);
                   9145: }
                   9146: 
1.691     raeburn  9147: sub letter_to_digits {
1.542     raeburn  9148:     my %lettdig = (
                   9149:                     A => 1,
                   9150:                     B => 2,
                   9151:                     C => 3,
                   9152:                     D => 4,
                   9153:                     E => 5,
                   9154:                     F => 6,
                   9155:                     G => 7,
                   9156:                     H => 8,
                   9157:                     I => 9,
                   9158:                     J => 0,
                   9159:                   );
                   9160:     return %lettdig;
                   9161: }
                   9162: 
1.423     albertel 9163: 
1.75      albertel 9164: #-------- end of section for handling grading scantron forms -------
                   9165: #
                   9166: #-------------------------------------------------------------------
                   9167: 
1.72      ng       9168: #-------------------------- Menu interface -------------------------
                   9169: #
1.614     www      9170: #--- Href with symb and command ---
                   9171: 
                   9172: sub href_symb_cmd {
                   9173:     my ($symb,$cmd)=@_;
1.669     raeburn  9174:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9175: }
                   9176: 
1.443     banghart 9177: sub grading_menu {
1.608     www      9178:     my ($request,$symb) = @_;
1.443     banghart 9179:     if (!$symb) {return '';}
                   9180: 
                   9181:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9182:                   'command'=>'individual');
1.538     schulted 9183:     
1.598     www      9184:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9185: 
                   9186:     $fields{'command'}='ungraded';
                   9187:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9188: 
                   9189:     $fields{'command'}='table';
                   9190:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9191: 
                   9192:     $fields{'command'}='all_for_one';
                   9193:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9194: 
1.621     www      9195:     $fields{'command'}='downloadfilesselect';
                   9196:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9197: 
1.443     banghart 9198:     $fields{'command'} = 'csvform';
1.538     schulted 9199:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9200:     
1.443     banghart 9201:     $fields{'command'} = 'processclicker';
1.538     schulted 9202:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9203:     
1.443     banghart 9204:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9205:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9206: 
                   9207:     $fields{'command'} = 'initialverifyreceipt';
                   9208:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9209:     
1.598     www      9210:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9211:             items =>[
1.598     www      9212:                         {	linktext => 'Select individual students to grade',
                   9213:                     		url => $url1a,
1.538     schulted 9214:                     		permission => 'F',
1.636     wenzelju 9215:                     		icon => 'grade_students.png',
1.598     www      9216:                     		linktitle => 'Grade current resource for a selection of students.'
                   9217:                         }, 
                   9218:                         {       linktext => 'Grade ungraded submissions.',
                   9219:                                 url => $url1b,
                   9220:                                 permission => 'F',
1.636     wenzelju 9221:                                 icon => 'ungrade_sub.png',
1.598     www      9222:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9223:                         },
1.598     www      9224: 
                   9225:                         {       linktext => 'Grading table',
                   9226:                                 url => $url1c,
                   9227:                                 permission => 'F',
1.636     wenzelju 9228:                                 icon => 'grading_table.png',
1.598     www      9229:                                 linktitle => 'Grade current resource for all students.'
                   9230:                         },
1.615     www      9231:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9232:                                 url => $url1d,
                   9233:                                 permission => 'F',
1.636     wenzelju 9234:                                 icon => 'grade_PageFolder.png',
1.598     www      9235:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9236:                         },
                   9237:                         {       linktext => 'Download submissions',
                   9238:                                 url => $url1e,
                   9239:                                 permission => 'F',
1.636     wenzelju 9240:                                 icon => 'download_sub.png',
1.621     www      9241:                                 linktitle => 'Download all students submissions.'
1.598     www      9242:                         }]},
                   9243:                          { categorytitle=>'Automated Grading',
                   9244:                items =>[
                   9245: 
1.538     schulted 9246:                 	    {	linktext => 'Upload Scores',
                   9247:                     		url => $url2,
                   9248:                     		permission => 'F',
                   9249:                     		icon => 'uploadscores.png',
                   9250:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9251:                 	    },
                   9252:                 	    {	linktext => 'Process Clicker',
                   9253:                     		url => $url3,
                   9254:                     		permission => 'F',
                   9255:                     		icon => 'addClickerInfoFile.png',
                   9256:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9257:                 	    },
1.587     raeburn  9258:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9259:                     		url => $url4,
                   9260:                     		permission => 'F',
1.636     wenzelju 9261:                     		icon => 'bubblesheet.png',
1.648     bisitz   9262:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9263:                 	    },
1.616     www      9264:                             {   linktext => 'Verify Receipt Number',
1.602     www      9265:                                 url => $url5,
                   9266:                                 permission => 'F',
1.636     wenzelju 9267:                                 icon => 'receipt_number.png',
1.602     www      9268:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9269:                             }
                   9270: 
1.538     schulted 9271:                     ]
                   9272:             });
                   9273: 
1.443     banghart 9274:     # Create the menu
                   9275:     my $Str;
1.445     banghart 9276:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9277:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9278:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9279: 
1.602     www      9280:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9281:     return $Str;    
                   9282: }
                   9283: 
1.598     www      9284: 
                   9285: sub ungraded {
                   9286:     my ($request)=@_;
                   9287:     &submit_options($request);
                   9288: }
                   9289: 
1.599     www      9290: sub submit_options_sequence {
1.608     www      9291:     my ($request,$symb) = @_;
1.599     www      9292:     if (!$symb) {return '';}
1.600     www      9293:     &commonJSfunctions($request);
                   9294:     my $result;
1.599     www      9295: 
1.600     www      9296:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9297:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9298:     $result.=&selectfield(0).
1.601     www      9299:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9300:             <div>
                   9301:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9302:             </div>
                   9303:         </div>
                   9304:   </form>';
                   9305:     return $result;
                   9306: }
                   9307: 
                   9308: sub submit_options_table {
1.608     www      9309:     my ($request,$symb) = @_;
1.600     www      9310:     if (!$symb) {return '';}
1.599     www      9311:     &commonJSfunctions($request);
                   9312:     my $result;
                   9313: 
                   9314:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9315:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9316: 
1.632     www      9317:     $result.=&selectfield(0).
1.601     www      9318:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9319:             <div>
                   9320:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9321:             </div>
                   9322:         </div>
                   9323:   </form>';
                   9324:     return $result;
                   9325: }
1.443     banghart 9326: 
1.621     www      9327: sub submit_options_download {
                   9328:     my ($request,$symb) = @_;
                   9329:     if (!$symb) {return '';}
                   9330: 
                   9331:     &commonJSfunctions($request);
                   9332: 
                   9333:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9334:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9335:     $result.='
                   9336: <h2>
                   9337:   '.&mt('Select Students for Which to Download Submissions').'
                   9338: </h2>'.&selectfield(1).'
                   9339:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9340:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9341:             </div>
                   9342:           </div>
1.600     www      9343: 
                   9344: 
1.621     www      9345:   </form>';
                   9346:     return $result;
                   9347: }
                   9348: 
1.443     banghart 9349: #--- Displays the submissions first page -------
                   9350: sub submit_options {
1.608     www      9351:     my ($request,$symb) = @_;
1.72      ng       9352:     if (!$symb) {return '';}
                   9353: 
1.118     ng       9354:     &commonJSfunctions($request);
1.473     albertel 9355:     my $result;
1.533     bisitz   9356: 
1.72      ng       9357:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9358: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9359:     $result.=&selectfield(1).'
1.601     www      9360:                 <input type="hidden" name="command" value="submission" /> 
                   9361: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9362:             </div>
                   9363:           </div>
                   9364: 
                   9365: 
                   9366:   </form>';
                   9367:     return $result;
                   9368: }
1.533     bisitz   9369: 
1.601     www      9370: sub selectfield {
                   9371:    my ($full)=@_;
1.635     raeburn  9372:    my %options = 
                   9373:           (&Apache::lonlocal::texthash(
                   9374:              'yes'       => 'with submissions',
                   9375:              'queued'    => 'in grading queue',
                   9376:              'graded'    => 'with ungraded submissions',
                   9377:              'incorrect' => 'with incorrect submissions',
                   9378:              'all'       => 'with any status'),
                   9379:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9380:    my $result='<div class="LC_columnSection">
1.537     harmsja  9381:   
1.533     bisitz   9382:     <fieldset>
                   9383:       <legend>
                   9384:        '.&mt('Sections').'
                   9385:       </legend>
1.601     www      9386:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9387:     </fieldset>
1.537     harmsja  9388:   
1.533     bisitz   9389:     <fieldset>
                   9390:       <legend>
                   9391:         '.&mt('Groups').'
                   9392:       </legend>
                   9393:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9394:     </fieldset>
1.537     harmsja  9395:   
1.533     bisitz   9396:     <fieldset>
                   9397:       <legend>
                   9398:         '.&mt('Access Status').'
                   9399:       </legend>
1.601     www      9400:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9401:     </fieldset>';
                   9402:     if ($full) {
                   9403:        $result.='
1.533     bisitz   9404:     <fieldset>
                   9405:       <legend>
                   9406:         '.&mt('Submission Status').'
1.601     www      9407:       </legend>'.
1.635     raeburn  9408:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9409:    '</fieldset>';
                   9410:     }
                   9411:     $result.='</div><br />';
1.44      ng       9412:     return $result;
1.2       albertel 9413: }
                   9414: 
1.285     albertel 9415: sub reset_perm {
                   9416:     undef(%perm);
                   9417: }
                   9418: 
                   9419: sub init_perm {
                   9420:     &reset_perm();
1.300     albertel 9421:     foreach my $test_perm ('vgr','mgr','opa') {
                   9422: 
                   9423: 	my $scope = $env{'request.course.id'};
                   9424: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9425: 
                   9426: 	    $scope .= '/'.$env{'request.course.sec'};
                   9427: 	    if ( $perm{$test_perm}=
                   9428: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9429: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9430: 	    } else {
                   9431: 		delete($perm{$test_perm});
                   9432: 	    }
1.285     albertel 9433: 	}
                   9434:     }
                   9435: }
                   9436: 
1.674     raeburn  9437: sub init_old_essays {
                   9438:     my ($symb,$apath,$adom,$aname) = @_;
                   9439:     if ($symb ne '') {
                   9440:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9441:         if (keys(%essays) > 0) {
                   9442:             $old_essays{$symb} = \%essays;
                   9443:         }
                   9444:     }
                   9445:     return;
                   9446: }
                   9447: 
                   9448: sub reset_old_essays {
                   9449:     undef(%old_essays);
                   9450: }
                   9451: 
1.400     www      9452: sub gather_clicker_ids {
1.408     albertel 9453:     my %clicker_ids;
1.400     www      9454: 
                   9455:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9456: 
                   9457:     # Set up a couple variables.
1.407     albertel 9458:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9459:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9460:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9461: 
1.407     albertel 9462:     foreach my $student (keys(%$classlist)) {
1.438     www      9463:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9464:         my $username = $classlist->{$student}->[$username_idx];
                   9465:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9466:         my $clickers =
1.408     albertel 9467: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9468:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9469:             $id=~s/^[\#0]+//;
1.421     www      9470:             $id=~s/[\-\:]//g;
1.407     albertel 9471:             if (exists($clicker_ids{$id})) {
1.408     albertel 9472: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9473:             } else {
1.408     albertel 9474: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9475:             }
                   9476:         }
                   9477:     }
1.407     albertel 9478:     return %clicker_ids;
1.400     www      9479: }
                   9480: 
1.402     www      9481: sub gather_adv_clicker_ids {
1.408     albertel 9482:     my %clicker_ids;
1.402     www      9483:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9484:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9485:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9486:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9487:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9488:             my ($puname,$pudom)=split(/\:/,$person);
                   9489:             my $clickers =
1.408     albertel 9490: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9491:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9492: 		$id=~s/^[\#0]+//;
1.421     www      9493:                 $id=~s/[\-\:]//g;
1.408     albertel 9494: 		if (exists($clicker_ids{$id})) {
                   9495: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9496: 		} else {
                   9497: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9498: 		}
1.405     www      9499:             }
1.402     www      9500:         }
                   9501:     }
1.407     albertel 9502:     return %clicker_ids;
1.402     www      9503: }
                   9504: 
1.413     www      9505: sub clicker_grading_parameters {
                   9506:     return ('gradingmechanism' => 'scalar',
                   9507:             'upfiletype' => 'scalar',
                   9508:             'specificid' => 'scalar',
                   9509:             'pcorrect' => 'scalar',
                   9510:             'pincorrect' => 'scalar');
                   9511: }
                   9512: 
1.400     www      9513: sub process_clicker {
1.608     www      9514:     my ($r,$symb)=@_;
1.400     www      9515:     if (!$symb) {return '';}
                   9516:     my $result=&checkforfile_js();
1.632     www      9517:     $result.=&Apache::loncommon::start_data_table().
                   9518:              &Apache::loncommon::start_data_table_header_row().
                   9519:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9520:              &Apache::loncommon::end_data_table_header_row().
                   9521:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9522: # Attempt to restore parameters from last session, set defaults if not present
                   9523:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9524:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9525:                                                  \%Saveable_Parameters);
                   9526:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9527:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9528:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9529:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9530: 
                   9531:     my %checked;
1.521     www      9532:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9533:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9534:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9535:        }
                   9536:     }
                   9537: 
1.632     www      9538:     my $upload=&mt("Evaluate File");
1.400     www      9539:     my $type=&mt("Type");
1.402     www      9540:     my $attendance=&mt("Award points just for participation");
                   9541:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9542:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9543:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9544:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9545:     my $pcorrect=&mt("Percentage points for correct solution");
                   9546:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9547:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9548: 						   {'iclicker' => 'i>clicker',
1.666     www      9549:                                                     'interwrite' => 'interwrite PRS',
                   9550:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9551:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9552:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9553: function sanitycheck() {
                   9554: // Accept only integer percentages
                   9555:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9556:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9557: // Find out grading choice
                   9558:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9559:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9560:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9561:       }
                   9562:    }
                   9563: // By default, new choice equals user selection
                   9564:    newgradingchoice=gradingchoice;
                   9565: // Not good to give more points for false answers than correct ones
                   9566:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9567:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9568:    }
                   9569: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9570:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9571:       document.forms.gradesupload.pcorrect.value=100;
                   9572:       document.forms.gradesupload.pincorrect.value=100;
                   9573:    }
                   9574: // If the values are different, cannot be attendance only
                   9575:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9576:        (gradingchoice=='attendance')) {
                   9577:        newgradingchoice='personnel';
                   9578:    }
                   9579: // Change grading choice to new one
                   9580:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9581:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9582:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9583:       } else {
                   9584:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9585:       }
                   9586:    }
                   9587: // Remember the old state
                   9588:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9589: }
1.597     wenzelju 9590: ENDUPFORM
                   9591:     $result.= <<ENDUPFORM;
1.400     www      9592: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9593: <input type="hidden" name="symb" value="$symb" />
                   9594: <input type="hidden" name="command" value="processclickerfile" />
                   9595: <input type="file" name="upfile" size="50" />
                   9596: <br /><label>$type: $selectform</label>
1.632     www      9597: ENDUPFORM
                   9598:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9599:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9600:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9601: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9602: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9603: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9604: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9605: <br />&nbsp;&nbsp;&nbsp;
                   9606: <input type="text" name="givenanswer" size="50" />
1.413     www      9607: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9608: ENDGRADINGFORM
                   9609:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9610:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9611:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9612: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9613: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9614: </form>'
1.632     www      9615: ENDPERCFORM
                   9616:     $result.='</td>'.
                   9617:              &Apache::loncommon::end_data_table_row().
                   9618:              &Apache::loncommon::end_data_table();
1.400     www      9619:     return $result;
                   9620: }
                   9621: 
                   9622: sub process_clicker_file {
1.608     www      9623:     my ($r,$symb)=@_;
1.400     www      9624:     if (!$symb) {return '';}
1.413     www      9625: 
                   9626:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9627:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9628:                                               \%Saveable_Parameters);
1.598     www      9629:     my $result='';
1.404     www      9630:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9631: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9632: 	return $result;
1.404     www      9633:     }
1.522     www      9634:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9635:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9636:         return $result;
1.521     www      9637:     }
1.522     www      9638:     my $foundgiven=0;
1.521     www      9639:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9640:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9641:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9642:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9643:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9644:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9645:         $foundgiven=$#answers+1;
1.521     www      9646:     }
1.407     albertel 9647:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9648:     my %correct_ids;
1.404     www      9649:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9650: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9651:     }
                   9652:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9653: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9654: 	   $correct_id=~tr/a-z/A-Z/;
                   9655: 	   $correct_id=~s/\s//gs;
                   9656: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9657:            $correct_id=~s/[\-\:]//g;
1.414     www      9658:            if ($correct_id) {
                   9659: 	      $correct_ids{$correct_id}='specified';
                   9660:            }
                   9661:         }
1.400     www      9662:     }
1.404     www      9663:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9664: 	$result.=&mt('Score based on attendance only');
1.521     www      9665:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9666:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9667:     } else {
1.408     albertel 9668: 	my $number=0;
1.411     www      9669: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9670: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9671: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9672: 	    if ($correct_ids{$id} eq 'specified') {
                   9673: 		$result.=&mt('specified');
                   9674: 	    } else {
                   9675: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9676: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9677: 	    }
                   9678: 	    $number++;
                   9679: 	}
1.411     www      9680:         $result.="</p>\n";
1.408     albertel 9681: 	if ($number==0) {
                   9682: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      9683: 	    return $result;
1.408     albertel 9684: 	}
1.404     www      9685:     }
1.405     www      9686:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9687:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9688: 		     '<span class="LC_error">',
                   9689: 		     '</span>',
                   9690: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      9691:         return $result;
1.405     www      9692:     }
1.410     www      9693: 
                   9694: # Were able to get all the info needed, now analyze the file
                   9695: 
1.411     www      9696:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9697:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9698:     $result.=&Apache::loncommon::start_data_table().
                   9699:              &Apache::loncommon::start_data_table_header_row().
                   9700:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9701:              &Apache::loncommon::end_data_table_header_row().
                   9702:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9703: <td>
1.410     www      9704: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9705: <input type="hidden" name="symb" value="$symb" />
                   9706: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9707: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9708: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9709: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9710: ENDHEADER
1.522     www      9711:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9712:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9713:     } 
1.408     albertel 9714:     my %responses;
                   9715:     my @questiontitles;
1.405     www      9716:     my $errormsg='';
                   9717:     my $number=0;
                   9718:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9719: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9720:     }
1.419     www      9721:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9722:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9723:     }
1.666     www      9724:     if ($env{'form.upfiletype'} eq 'turning') {
                   9725:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9726:     }
1.411     www      9727:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9728:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9729:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9730:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9731:              '<br />';
1.522     www      9732:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9733:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9734:        return $result;
1.522     www      9735:     } 
1.414     www      9736: # Remember Question Titles
                   9737: # FIXME: Possibly need delimiter other than ":"
                   9738:     for (my $i=0;$i<$number;$i++) {
                   9739:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9740:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9741:     }
1.411     www      9742:     my $correct_count=0;
                   9743:     my $student_count=0;
                   9744:     my $unknown_count=0;
1.414     www      9745: # Match answers with usernames
                   9746: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9747:     foreach my $id (keys(%responses)) {
1.410     www      9748:        if ($correct_ids{$id}) {
1.414     www      9749:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9750:           $correct_count++;
1.410     www      9751:        } elsif ($clicker_ids{$id}) {
1.437     www      9752:           if ($clicker_ids{$id}=~/\,/) {
                   9753: # More than one user with the same clicker!
1.632     www      9754:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9755:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9756:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9757:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9758:                            "<select name='multi".$id."'>";
                   9759:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9760:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9761:              }
                   9762:              $result.='</select>';
                   9763:              $unknown_count++;
                   9764:           } else {
                   9765: # Good: found one and only one user with the right clicker
                   9766:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9767:              $student_count++;
                   9768:           }
1.410     www      9769:        } else {
1.632     www      9770:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9771:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9772:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9773:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9774:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9775:                    "\n".&mt("Domain").": ".
                   9776:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9777:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9778:           $unknown_count++;
1.410     www      9779:        }
1.405     www      9780:     }
1.412     www      9781:     $result.='<hr />'.
                   9782:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9783:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9784:        if ($correct_count==0) {
1.696     bisitz   9785:           $errormsg.="Found no correct answers for grading!";
1.412     www      9786:        } elsif ($correct_count>1) {
1.414     www      9787:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9788:        }
                   9789:     }
1.428     www      9790:     if ($number<1) {
                   9791:        $errormsg.="Found no questions.";
                   9792:     }
1.412     www      9793:     if ($errormsg) {
                   9794:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9795:     } else {
                   9796:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9797:     }
1.632     www      9798:     $result.='</form></td>'.
                   9799:              &Apache::loncommon::end_data_table_row().
                   9800:              &Apache::loncommon::end_data_table();
1.614     www      9801:     return $result;
1.400     www      9802: }
                   9803: 
1.405     www      9804: sub iclicker_eval {
1.406     www      9805:     my ($questiontitles,$responses)=@_;
1.405     www      9806:     my $number=0;
                   9807:     my $errormsg='';
                   9808:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9809:         my %components=&Apache::loncommon::record_sep($line);
                   9810:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9811: 	if ($entries[0] eq 'Question') {
                   9812: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9813: 		$$questiontitles[$number]=$entries[$i];
                   9814: 		$number++;
                   9815: 	    }
                   9816: 	}
                   9817: 	if ($entries[0]=~/^\#/) {
                   9818: 	    my $id=$entries[0];
                   9819: 	    my @idresponses;
                   9820: 	    $id=~s/^[\#0]+//;
                   9821: 	    for (my $i=0;$i<$number;$i++) {
                   9822: 		my $idx=3+$i*6;
1.644     www      9823:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9824: 		push(@idresponses,$entries[$idx]);
                   9825: 	    }
                   9826: 	    $$responses{$id}=join(',',@idresponses);
                   9827: 	}
1.405     www      9828:     }
                   9829:     return ($errormsg,$number);
                   9830: }
                   9831: 
1.419     www      9832: sub interwrite_eval {
                   9833:     my ($questiontitles,$responses)=@_;
                   9834:     my $number=0;
                   9835:     my $errormsg='';
1.420     www      9836:     my $skipline=1;
                   9837:     my $questionnumber=0;
                   9838:     my %idresponses=();
1.419     www      9839:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9840:         my %components=&Apache::loncommon::record_sep($line);
                   9841:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9842:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9843:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9844:         next if $skipline;
                   9845:         if ($entries[0]!=$questionnumber) {
                   9846:            $questionnumber=$entries[0];
                   9847:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9848:            $number++;
1.419     www      9849:         }
1.420     www      9850:         my $id=$entries[4];
                   9851:         $id=~s/^[\#0]+//;
1.421     www      9852:         $id=~s/^v\d*\://i;
                   9853:         $id=~s/[\-\:]//g;
1.420     www      9854:         $idresponses{$id}[$number]=$entries[6];
                   9855:     }
1.524     raeburn  9856:     foreach my $id (keys(%idresponses)) {
1.420     www      9857:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9858:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9859:     }
                   9860:     return ($errormsg,$number);
                   9861: }
                   9862: 
1.666     www      9863: sub turning_eval {
                   9864:     my ($questiontitles,$responses)=@_;
                   9865:     my $number=0;
                   9866:     my $errormsg='';
                   9867:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9868:         my %components=&Apache::loncommon::record_sep($line);
                   9869:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9870:         if ($#entries>$number) { $number=$#entries; }
                   9871:         my $id=$entries[0];
                   9872:         my @idresponses;
                   9873:         $id=~s/^[\#0]+//;
                   9874:         unless ($id) { next; }
                   9875:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9876:             $entries[$idx]=~s/\,/\;/g;
                   9877:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9878:             push(@idresponses,$entries[$idx]);
                   9879:         }
                   9880:         $$responses{$id}=join(',',@idresponses);
                   9881:     }
                   9882:     for (my $i=1; $i<=$number; $i++) {
                   9883:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9884:     }
                   9885:     return ($errormsg,$number);
                   9886: }
                   9887: 
                   9888: 
1.414     www      9889: sub assign_clicker_grades {
1.608     www      9890:     my ($r,$symb)=@_;
1.414     www      9891:     if (!$symb) {return '';}
1.416     www      9892: # See which part we are saving to
1.582     raeburn  9893:     my $res_error;
                   9894:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9895:     if ($res_error) {
                   9896:         return &navmap_errormsg();
                   9897:     }
1.416     www      9898: # FIXME: This should probably look for the first handgradeable part
                   9899:     my $part=$$partlist[0];
                   9900: # Start screen output
1.632     www      9901:     my $result=&Apache::loncommon::start_data_table().
                   9902:              &Apache::loncommon::start_data_table_header_row().
                   9903:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9904:              &Apache::loncommon::end_data_table_header_row().
                   9905:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9906: # Get correct result
                   9907: # FIXME: Possibly need delimiter other than ":"
                   9908:     my @correct=();
1.415     www      9909:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9910:     my $number=$env{'form.number'};
                   9911:     if ($gradingmechanism ne 'attendance') {
1.414     www      9912:        foreach my $key (keys(%env)) {
                   9913:           if ($key=~/^form\.correct\:/) {
                   9914:              my @input=split(/\,/,$env{$key});
                   9915:              for (my $i=0;$i<=$#input;$i++) {
                   9916:                  if (($correct[$i]) && ($input[$i]) &&
                   9917:                      ($correct[$i] ne $input[$i])) {
                   9918:                     $result.='<br /><span class="LC_warning">'.
                   9919:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9920:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9921:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9922:                     $correct[$i]=$input[$i];
                   9923:                  }
                   9924:              }
                   9925:           }
                   9926:        }
1.415     www      9927:        for (my $i=0;$i<$number;$i++) {
1.644     www      9928:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9929:              $result.='<br /><span class="LC_error">'.
                   9930:                       &mt('No correct result given for question "[_1]"!',
                   9931:                           $env{'form.question:'.$i}).'</span>';
                   9932:           }
                   9933:        }
1.644     www      9934:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9935:     }
                   9936: # Start grading
1.415     www      9937:     my $pcorrect=$env{'form.pcorrect'};
                   9938:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9939:     my $storecount=0;
1.632     www      9940:     my %users=();
1.415     www      9941:     foreach my $key (keys(%env)) {
1.420     www      9942:        my $user='';
1.415     www      9943:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9944:           $user=$1;
                   9945:        }
                   9946:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9947:           my $id=$1;
                   9948:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9949:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9950:           } elsif ($env{'form.multi'.$id}) {
                   9951:              $user=$env{'form.multi'.$id};
1.420     www      9952:           }
                   9953:        }
1.632     www      9954:        if ($user) {
                   9955:           if ($users{$user}) {
                   9956:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   9957:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      9958:                       '</span><br />';
                   9959:           }
                   9960:           $users{$user}=1; 
1.415     www      9961:           my @answer=split(/\,/,$env{$key});
                   9962:           my $sum=0;
1.522     www      9963:           my $realnumber=$number;
1.415     www      9964:           for (my $i=0;$i<$number;$i++) {
1.576     www      9965:              if  ($correct[$i] eq '-') {
                   9966:                 $realnumber--;
1.644     www      9967:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9968:                 if ($gradingmechanism eq 'attendance') {
                   9969:                    $sum+=$pcorrect;
1.576     www      9970:                 } elsif ($correct[$i] eq '*') {
1.522     www      9971:                    $sum+=$pcorrect;
1.415     www      9972:                 } else {
1.644     www      9973: # We actually grade if correct or not
                   9974:                    my $increment=$pincorrect;
                   9975: # Special case: numerical answer "0"
                   9976:                    if ($correct[$i] eq '0') {
                   9977:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9978:                          $increment=$pcorrect;
                   9979:                       }
                   9980: # General numerical answer, both evaluate to something non-zero
                   9981:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9982:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9983:                          $increment=$pcorrect;
                   9984:                       }
                   9985: # Must be just alphanumeric
                   9986:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9987:                       $increment=$pcorrect;
1.415     www      9988:                    }
1.644     www      9989:                    $sum+=$increment;
1.415     www      9990:                 }
                   9991:              }
                   9992:           }
1.522     www      9993:           my $ave=$sum/(100*$realnumber);
1.416     www      9994: # Store
                   9995:           my ($username,$domain)=split(/\:/,$user);
                   9996:           my %grades=();
                   9997:           $grades{"resource.$part.solved"}='correct_by_override';
                   9998:           $grades{"resource.$part.awarded"}=$ave;
                   9999:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10000:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10001:                                                  $env{'request.course.id'},
                   10002:                                                  $domain,$username);
                   10003:           if ($returncode ne 'ok') {
                   10004:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10005:           } else {
                   10006:              $storecount++;
                   10007:           }
1.415     www      10008:        }
                   10009:     }
                   10010: # We are done
1.549     hauer    10011:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10012:              '</td>'.
                   10013:              &Apache::loncommon::end_data_table_row().
                   10014:              &Apache::loncommon::end_data_table();
1.614     www      10015:     return $result;
1.414     www      10016: }
                   10017: 
1.582     raeburn  10018: sub navmap_errormsg {
                   10019:     return '<div class="LC_error">'.
                   10020:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10021:            &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  10022:            '</div>';
                   10023: }
1.607     droeschl 10024: 
1.609     www      10025: sub startpage {
1.671     raeburn  10026:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10027:     if ($nomenu) {
                   10028:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10029:     } else {
                   10030:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10031:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10032:                                                  {'bread_crumbs' => $crumbs}));
                   10033:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10034:     }
1.613     www      10035:     unless ($nodisplayflag) {
1.671     raeburn  10036:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10037:     }
1.607     droeschl 10038: }
1.582     raeburn  10039: 
1.622     www      10040: sub select_problem {
                   10041:     my ($r)=@_;
1.632     www      10042:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10043:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10044:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10045:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10046: }
                   10047: 
1.1       albertel 10048: sub handler {
1.41      ng       10049:     my $request=$_[0];
1.434     albertel 10050:     &reset_caches();
1.646     raeburn  10051:     if ($request->header_only) {
                   10052:         &Apache::loncommon::content_type($request,'text/html');
                   10053:         $request->send_http_header;
                   10054:         return OK;
                   10055:     }
                   10056:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10057: 
1.664     raeburn  10058: # see what command we need to execute
                   10059: 
                   10060:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10061:     my $command=$commands[0];
                   10062: 
1.646     raeburn  10063:     &init_perm();
                   10064:     if (!$env{'request.course.id'}) {
1.664     raeburn  10065:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10066:                 ($command =~ /^scantronupload/)) {
                   10067:             # Not in a course.
                   10068:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10069:             return HTTP_NOT_ACCEPTABLE;
                   10070:         }
1.646     raeburn  10071:     } elsif (!%perm) {
                   10072:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10073:         return OK;
1.41      ng       10074:     }
1.646     raeburn  10075:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10076:     $request->send_http_header;
1.646     raeburn  10077: 
1.160     albertel 10078:     if ($#commands > 0) {
                   10079: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10080:     }
1.608     www      10081: 
                   10082: # see what the symb is
                   10083: 
                   10084:     my $symb=$env{'form.symb'};
                   10085:     unless ($symb) {
                   10086:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10087:        $symb=&Apache::lonnet::symbread($url);
                   10088:     }
1.646     raeburn  10089:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10090: 
1.513     foxr     10091:     $ssi_error = 0;
1.637     www      10092:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10093: #
1.637     www      10094: # Not called from a resource, but inside a course
1.601     www      10095: #    
1.622     www      10096:         &startpage($request,undef,[],1,1);
                   10097:         &select_problem($request);
1.41      ng       10098:     } else {
1.104     albertel 10099: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10100:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10101:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10102:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10103:                     &choose_task_version_form($symb,$env{'form.student'},
                   10104:                                               $env{'form.userdom'});
                   10105:             }
                   10106:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10107:             if ($versionform) {
                   10108:                 $request->print($versionform);
                   10109:             }
                   10110:             $request->print('<br clear="all" />');
1.611     www      10111: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10112:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10113:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10114:                 &choose_task_version_form($symb,$env{'form.student'},
                   10115:                                           $env{'form.userdom'},
                   10116:                                           $env{'form.inhibitmenu'});
                   10117:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10118:             if ($versionform) {
                   10119:                 $request->print($versionform);
                   10120:             }
                   10121:             $request->print('<br clear="all" />');
                   10122:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10123: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10124:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10125:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10126: 	    &pickStudentPage($request,$symb);
1.103     albertel 10127: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10128:             &startpage($request,$symb,
                   10129:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10130:                                        {href=>'',text=>'Select student'},
                   10131:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10132: 	    &displayPage($request,$symb);
1.104     albertel 10133: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10134:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10135:                                        {href=>'',text=>'Select student'},
                   10136:                                        {href=>'',text=>'Grade student'},
                   10137:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10138: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10139: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10140:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10141:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10142: 	    &processGroup($request,$symb);
1.104     albertel 10143: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10144:             &startpage($request,$symb);
                   10145: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10146: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10147:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10148: 	    $request->print(&submit_options($request,$symb));
1.598     www      10149:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10150:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10151:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10152:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10153:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10154:             $request->print(&submit_options_table($request,$symb));
1.598     www      10155:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10156:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10157:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10158: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10159:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10160: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10161: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10162:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10163:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10164: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10165: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10166:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10167:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10168:                                                                              text=>"Modify grades"},
                   10169:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10170: 	    $request->print(&editgrades($request,$symb));
1.602     www      10171:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10172:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10173:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10174: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10175:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10176:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10177: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10178:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10179:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10180:             $request->print(&process_clicker($request,$symb));
1.400     www      10181:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10182:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10183:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10184:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10185:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10186:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10187:                                        {href=>'', text=>'Process clicker file'},
                   10188:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10189:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10190: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10191:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10192: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10193: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10194:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10195: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10196: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10197:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10198: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10199: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10200: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10201:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10202: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10203: 	    } else {
1.257     albertel 10204: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10205: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10206: 		} else {
1.257     albertel 10207: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10208: 		}
1.627     www      10209:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10210: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10211: 	    }
1.246     albertel 10212: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10213:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10214: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10215: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10216:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10217: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10218:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10219:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10220:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10221: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10222:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10223: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10224: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10225:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10226: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10227:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10228:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10229: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10230:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10231:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10232:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10233:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10234: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10235:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10236:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10237:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10238: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10239:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10240:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10241:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10242:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10243:             $request->print(&checkscantron_results($request,$symb));
                   10244:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10245:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10246:             $request->print(&submit_options_download($request,$symb));
                   10247:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10248:             &startpage($request,$symb,
                   10249:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10250:     {href=>'', text=>'Download submissions'}]);
                   10251:             &submit_download_link($request,$symb);
1.106     albertel 10252: 	} elsif ($command) {
1.620     www      10253:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10254: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10255: 	}
1.2       albertel 10256:     }
1.513     foxr     10257:     if ($ssi_error) {
                   10258: 	&ssi_print_error($request);
                   10259:     }
1.671     raeburn  10260:     if ($env{'form.inhibitmenu'}) {
                   10261:         $request->print(&Apache::loncommon::end_page());
                   10262:     } else {
                   10263:         &Apache::lonquickgrades::endGradeScreen($request);
                   10264:     }
1.434     albertel 10265:     &reset_caches();
1.646     raeburn  10266:     return OK;
1.44      ng       10267: }
                   10268: 
1.1       albertel 10269: 1;
                   10270: 
1.13      albertel 10271: __END__;
1.531     jms      10272: 
                   10273: 
                   10274: =head1 NAME
                   10275: 
                   10276: Apache::grades
                   10277: 
                   10278: =head1 SYNOPSIS
                   10279: 
                   10280: Handles the viewing of grades.
                   10281: 
                   10282: This is part of the LearningOnline Network with CAPA project
                   10283: described at http://www.lon-capa.org.
                   10284: 
                   10285: =head1 OVERVIEW
                   10286: 
                   10287: Do an ssi with retries:
                   10288: While I'd love to factor out this with the vesrion in lonprintout,
                   10289: 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
                   10290: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10291: 
                   10292: At least the logic that drives this has been pulled out into loncommon.
                   10293: 
                   10294: 
                   10295: 
                   10296: ssi_with_retries - Does the server side include of a resource.
                   10297:                      if the ssi call returns an error we'll retry it up to
                   10298:                      the number of times requested by the caller.
                   10299:                      If we still have a proble, no text is appended to the
                   10300:                      output and we set some global variables.
                   10301:                      to indicate to the caller an SSI error occurred.  
                   10302:                      All of this is supposed to deal with the issues described
                   10303:                      in LonCAPA BZ 5631 see:
                   10304:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10305:                      by informing the user that this happened.
                   10306: 
                   10307: Parameters:
                   10308:   resource   - The resource to include.  This is passed directly, without
                   10309:                interpretation to lonnet::ssi.
                   10310:   form       - The form hash parameters that guide the interpretation of the resource
                   10311:                
                   10312:   retries    - Number of retries allowed before giving up completely.
                   10313: Returns:
                   10314:   On success, returns the rendered resource identified by the resource parameter.
                   10315: Side Effects:
                   10316:   The following global variables can be set:
                   10317:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10318:                               It is up to the caller to initialize this to false
                   10319:                               if desired.
                   10320:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10321:                               of the resource that could not be rendered by the ssi
                   10322:                               call.
                   10323:    ssi_error_message   - The error string fetched from the ssi response
                   10324:                               in the event of an error.
                   10325: 
                   10326: 
                   10327: =head1 HANDLER SUBROUTINE
                   10328: 
                   10329: ssi_with_retries()
                   10330: 
                   10331: =head1 SUBROUTINES
                   10332: 
                   10333: =over
                   10334: 
1.671     raeburn  10335: =head1 Routines to display previous version of a Task for a specific student
                   10336: 
                   10337: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10338: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10339: requires a proctor to check-in the student, a new version of the Task will
                   10340: be created when the student is checked in to the new opportunity.
                   10341: 
                   10342: If a particular student has tried two or more versions of a particular task,
                   10343: the submission screen provides a user with vgr privileges (e.g., a Course
                   10344: Coordinator) the ability to display a previous version worked on by the
                   10345: student.  By default, the current version is displayed. If a previous version
                   10346: has been selected for display, submission data are only shown that pertain
                   10347: to that particular version, and the interface to submit grades is not shown.
                   10348: 
                   10349: =over 4
                   10350: 
                   10351: =item show_previous_task_version()
                   10352: 
                   10353: Displays a specified version of a student's Task, as the student sees it.
                   10354: 
                   10355: Inputs: 2
                   10356:         request - request object
                   10357:         symb    - unique symb for current instance of resource
                   10358: 
                   10359: Output: None.
                   10360: 
                   10361: Side Effects: calls &show_problem() to print version of Task, with
                   10362:               version contained in form item: $env{'form.previousversion'}
                   10363: 
                   10364: =item choose_task_version_form()
                   10365: 
                   10366: Displays a web form used to select which version of a student's view of a
                   10367: Task should be displayed.  Either launches a pop-up window, or replaces
                   10368: content in existing pop-up, or replaces page in main window.
                   10369: 
                   10370: Inputs: 4
                   10371:         symb    - unique symb for current instance of resource
                   10372:         uname   - username of student
                   10373:         udom    - domain of student
                   10374:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10375:                   breadcrumbs etc., are displayed
                   10376: 
                   10377: Output: 4
                   10378:         current   - student's current version
                   10379:         displayed - student's version being displayed
                   10380:         result    - scalar containing HTML for web form used to switch to
                   10381:                     a different version (or a link to close window, if pop-up).
                   10382:         js        - javascript for processing selection in versions web form
                   10383: 
                   10384: Side Effects: None.
                   10385: 
                   10386: =item previous_display_javascript()
                   10387: 
                   10388: Inputs: 2
                   10389:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10390:                   breadcrumbs etc., are displayed.
                   10391:         current - student's current version number.
                   10392: 
                   10393: Output: 1
                   10394:         js      - javascript for processing selection in versions web form.
                   10395: 
                   10396: Side Effects: None.
                   10397: 
                   10398: =back
                   10399: 
                   10400: =head1 Routines to process bubblesheet data.
                   10401: 
                   10402: =over 4
                   10403: 
1.531     jms      10404: =item scantron_get_correction() : 
                   10405: 
                   10406:    Builds the interface screen to interact with the operator to fix a
                   10407:    specific error condition in a specific scanline
                   10408: 
                   10409:  Arguments:
                   10410:     $r           - Apache request object
                   10411:     $i           - number of the current scanline
                   10412:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10413:     $scan_config - hash ref as returned from &get_scantron_config()
                   10414:     $line        - full contents of the current scanline
                   10415:     $error       - error condition, valid values are
                   10416:                    'incorrectCODE', 'duplicateCODE',
                   10417:                    'doublebubble', 'missingbubble',
                   10418:                    'duplicateID', 'incorrectID'
                   10419:     $arg         - extra information needed
                   10420:        For errors:
                   10421:          - duplicateID   - paper number that this studentID was seen before on
                   10422:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10423:                            seen on before
                   10424:          - incorrectCODE - current incorrect CODE 
                   10425:          - doublebubble  - array ref of the bubble lines that have double
                   10426:                            bubble errors
                   10427:          - missingbubble - array ref of the bubble lines that have missing
                   10428:                            bubble errors
                   10429: 
1.691     raeburn  10430:    $randomorder - True if exam folder has randomorder set
                   10431:    $randompick  - True if exam folder has randompick set
                   10432:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10433:                      for current line to question number used for same question
                   10434:                      in "Master Seqence" (as seen by Course Coordinator).
                   10435:    $startline   - Reference to hash where key is question number (0 is first)
                   10436:                   and value is number of first bubble line for current student
                   10437:                   or code-based randompick and/or randomorder.
                   10438: 
                   10439: 
                   10440: 
1.531     jms      10441: =item  scantron_get_maxbubble() : 
                   10442: 
1.582     raeburn  10443:    Arguments:
                   10444:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10445:                       failure to retrieve a navmap object.
                   10446:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10447:        calling routine should trap the error condition and display the warning
                   10448:        found in &navmap_errormsg().
                   10449: 
1.649     raeburn  10450:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10451: 
1.531     jms      10452:    Returns the maximum number of bubble lines that are expected to
                   10453:    occur. Does this by walking the selected sequence rendering the
                   10454:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10455:    for what the current value of the problem counter is.
                   10456: 
                   10457:    Caches the results to $env{'form.scantron_maxbubble'},
                   10458:    $env{'form.scantron.bubble_lines.n'}, 
                   10459:    $env{'form.scantron.first_bubble_line.n'} and
                   10460:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10461:    which are the total number of bubble lines, the number of bubble
1.531     jms      10462:    lines for response n and number of the first bubble line for response n,
                   10463:    and a comma separated list of numbers of bubble lines for sub-questions
                   10464:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10465: 
                   10466: 
                   10467: =item  scantron_validate_missingbubbles() : 
                   10468: 
                   10469:    Validates all scanlines in the selected file to not have any
                   10470:     answers that don't have bubbles that have not been verified
                   10471:     to be bubble free.
                   10472: 
                   10473: =item  scantron_process_students() : 
                   10474: 
1.659     raeburn  10475:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10476: 
                   10477:    The parsed scanline hash is added to %env 
                   10478: 
                   10479:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10480:    foreach resource , with the form data of
                   10481: 
                   10482: 	'submitted'     =>'scantron' 
                   10483: 	'grade_target'  =>'grade',
                   10484: 	'grade_username'=> username of student
                   10485: 	'grade_domain'  => domain of student
                   10486: 	'grade_courseid'=> of course
                   10487: 	'grade_symb'    => symb of resource to grade
                   10488: 
                   10489:     This triggers a grading pass. The problem grading code takes care
                   10490:     of converting the bubbled letter information (now in %env) into a
                   10491:     valid submission.
                   10492: 
                   10493: =item  scantron_upload_scantron_data() :
                   10494: 
1.659     raeburn  10495:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10496: 
                   10497: =item  scantron_upload_scantron_data_save() : 
                   10498: 
                   10499:    Adds a provided bubble information data file to the course if user
                   10500:    has the correct privileges to do so. 
                   10501: 
                   10502: =item  valid_file() :
                   10503: 
                   10504:    Validates that the requested bubble data file exists in the course.
                   10505: 
                   10506: =item  scantron_download_scantron_data() : 
                   10507: 
                   10508:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10509:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10510:    course.
                   10511: 
                   10512: =item  scantron_validate_ID() : 
                   10513: 
                   10514:    Validates all scanlines in the selected file to not have any
1.556     weissno  10515:    invalid or underspecified student/employee IDs
1.531     jms      10516: 
1.582     raeburn  10517: =item navmap_errormsg() :
                   10518: 
                   10519:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10520:    Should be called whenever the request to instantiate a navmap object fails.
                   10521: 
                   10522: =back
1.582     raeburn  10523: 
1.531     jms      10524: =back
                   10525: 
                   10526: =cut

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