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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.674   ! raeburn     4: # $Id: grades.pm,v 1.673 2012/05/13 01:15:30 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674   ! raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674   ! raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
                    333: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    334: 	my ($toprow,$bottomrow);
                    335: 	foreach my $foil (@$order) {
                    336: 	    if ($grading{$foil} == 1) {
                    337: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    338: 	    } else {
                    339: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  342: 	}
                    343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   346: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  347:     } elsif ($response eq 'match') {
                    348: 	my %answer=&Apache::lonnet::str2hash($answer);
                    349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    350: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    351: 	my ($toprow,$middlerow,$bottomrow);
                    352: 	foreach my $foil (@$order) {
                    353: 	    my $item=shift(@items);
                    354: 	    if ($grading{$foil} == 1) {
                    355: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  356: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  357: 	    } else {
                    358: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  359: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  360: 	    }
1.398     albertel  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        362: 	}
1.126     ng        363: 	return '<blockquote><table border="1">'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  366: 	    $middlerow.'</tr>'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   368: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  369:     } elsif ($response eq 'radiobutton') {
                    370: 	my %answer=&Apache::lonnet::str2hash($answer);
                    371: 	my ($toprow,$bottomrow);
1.434     albertel  372: 	my $correct = 
1.640     raeburn   373: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  374: 	foreach my $foil (@$order) {
1.148     albertel  375: 	    if (exists($answer{$foil})) {
1.434     albertel  376: 		if ($foil eq $correct) {
1.466     albertel  377: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  378: 		} else {
1.466     albertel  379: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  380: 		}
                    381: 	    } else {
1.466     albertel  382: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  383: 	    }
1.398     albertel  384: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  385: 	}
                    386: 	return '<blockquote><table border="1">'.
1.466     albertel  387: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    388: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   389: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  390:     } elsif ($response eq 'essay') {
1.257     albertel  391: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        392: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  393: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    394: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        395: 
1.257     albertel  396: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    397: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    398: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    399: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    400: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    401: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        402: 	}
1.166     albertel  403: 	$answer =~ s-\n-<br />-g;
                    404: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  405:     } elsif ( $response eq 'organic') {
                    406: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    407: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    408: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    409: 	return $result;
1.335     albertel  410:     } elsif ( $response eq 'Task') {
                    411: 	if ( $answer eq 'SUBMITTED') {
                    412: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  413: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  414: 	    return $result;
                    415: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    416: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    417: 			       keys(%{$record}));
                    418: 	    return join('<br />',($version,@matches));
                    419: 			       
                    420: 			       
                    421: 	} else {
                    422: 	    my $result =
                    423: 		'<p>'
                    424: 		.&mt('Overall result: [_1]',
                    425: 		     $record->{$version."resource.$respid.$partid.status"})
                    426: 		.'</p>';
                    427: 	    
                    428: 	    $result .= '<ul>';
                    429: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    430: 			     keys(%{$record}));
                    431: 	    foreach my $grade (sort(@grade)) {
                    432: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    433: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    434: 				     $dim, $record->{$grade}).
                    435: 			  '</li>';
                    436: 	    }
                    437: 	    $result.='</ul>';
                    438: 	    return $result;
                    439: 	}
1.440     albertel  440:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    441: 	$answer = 
                    442: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    443: 							      $answer);
1.122     ng        444:     }
1.118     ng        445:     return $answer;
                    446: }
                    447: 
                    448: #-- A couple of common js functions
                    449: sub commonJSfunctions {
                    450:     my $request = shift;
1.597     wenzelju  451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        452:     function radioSelection(radioButton) {
                    453: 	var selection=null;
                    454: 	if (radioButton.length > 1) {
                    455: 	    for (var i=0; i<radioButton.length; i++) {
                    456: 		if (radioButton[i].checked) {
                    457: 		    return radioButton[i].value;
                    458: 		}
                    459: 	    }
                    460: 	} else {
                    461: 	    if (radioButton.checked) return radioButton.value;
                    462: 	}
                    463: 	return selection;
                    464:     }
                    465: 
                    466:     function pullDownSelection(selectOne) {
                    467: 	var selection="";
                    468: 	if (selectOne.length > 1) {
                    469: 	    for (var i=0; i<selectOne.length; i++) {
                    470: 		if (selectOne[i].selected) {
                    471: 		    return selectOne[i].value;
                    472: 		}
                    473: 	    }
                    474: 	} else {
1.138     albertel  475:             // only one value it must be the selected one
                    476: 	    return selectOne.value;
1.118     ng        477: 	}
                    478:     }
                    479: COMMONJSFUNCTIONS
                    480: }
                    481: 
1.44      ng        482: #--- Dumps the class list with usernames,list of sections,
                    483: #--- section, ids and fullnames for each user.
                    484: sub getclasslist {
1.449     banghart  485:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  486:     my @getsec;
1.450     banghart  487:     my @getgroup;
1.442     banghart  488:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  489:     if (!ref($getsec)) {
                    490: 	if ($getsec ne '' && $getsec ne 'all') {
                    491: 	    @getsec=($getsec);
                    492: 	}
                    493:     } else {
                    494: 	@getsec=@{$getsec};
                    495:     }
                    496:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  497:     if (!ref($getgroup)) {
                    498: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    499: 	    @getgroup=($getgroup);
                    500: 	}
                    501:     } else {
                    502: 	@getgroup=@{$getgroup};
                    503:     }
                    504:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  505: 
1.449     banghart  506:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  507:     # Bail out if we were unable to get the classlist
1.56      matthew   508:     return if (! defined($classlist));
1.449     banghart  509:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   510:     #
                    511:     my %sections;
                    512:     my %fullnames;
1.205     matthew   513:     foreach my $student (keys(%$classlist)) {
                    514:         my $end      = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    516:         my $start    = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    518:         my $id       = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    520:         my $section  = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    522:         my $fullname = 
                    523:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    524:         my $status   = 
                    525:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  526:         my $group   = 
                    527:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        528: 	# filter students according to status selected
1.442     banghart  529: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    530: 	    if (!($stu_status =~ $status)) {
1.450     banghart  531: 		delete($classlist->{$student});
1.76      ng        532: 		next;
                    533: 	    }
                    534: 	}
1.450     banghart  535: 	# filter students according to groups selected
1.453     banghart  536: 	my @stu_groups = split(/,/,$group);
1.450     banghart  537: 	if (@getgroup) {
                    538: 	    my $exclude = 1;
1.454     banghart  539: 	    foreach my $grp (@getgroup) {
                    540: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  541: 	            if ($stu_group eq $grp) {
                    542: 	                $exclude = 0;
                    543:     	            } 
1.450     banghart  544: 	        }
1.453     banghart  545:     	        if (($grp eq 'none') && !$group) {
                    546:         	        $exclude = 0;
                    547:         	}
1.450     banghart  548: 	    }
                    549: 	    if ($exclude) {
                    550: 	        delete($classlist->{$student});
                    551: 	    }
                    552: 	}
1.205     matthew   553: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  554: 	if (&canview($section)) {
1.291     albertel  555: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  556: 		$sections{$section}++;
1.450     banghart  557: 		if ($classlist->{$student}) {
                    558: 		    $fullnames{$student}=$fullname;
                    559: 		}
1.103     albertel  560: 	    } else {
1.205     matthew   561: 		delete($classlist->{$student});
1.103     albertel  562: 	    }
                    563: 	} else {
1.205     matthew   564: 	    delete($classlist->{$student});
1.103     albertel  565: 	}
1.44      ng        566:     }
                    567:     my %seen = ();
1.56      matthew   568:     my @sections = sort(keys(%sections));
                    569:     return ($classlist,\@sections,\%fullnames);
1.44      ng        570: }
                    571: 
1.103     albertel  572: sub canmodify {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'mgr'}) {
                    575: 	if (!defined($perm{'mgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'mgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
                    592: sub canview {
                    593:     my ($sec)=@_;
                    594:     if ($perm{'vgr'}) {
                    595: 	if (!defined($perm{'vgr_section'})) {
                    596: 	    # can modify whole class
                    597: 	    return 1;
                    598: 	} else {
                    599: 	    if ($sec eq $perm{'vgr_section'}) {
                    600: 		#can modify the requested section
                    601: 		return 1;
                    602: 	    } else {
                    603: 		# can't modify the request section
                    604: 		return 0;
                    605: 	    }
                    606: 	}
                    607:     }
                    608:     #can't modify
                    609:     return 0;
                    610: }
                    611: 
1.44      ng        612: #--- Retrieve the grade status of a student for all the parts
                    613: sub student_gradeStatus {
1.324     albertel  614:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  615:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        616:     my %partstatus = ();
                    617:     foreach (@$partlist) {
1.128     ng        618: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        619: 	$status              = 'nothing' if ($status eq '');
                    620: 	$partstatus{$_}      = $status;
                    621: 	my $subkey           = "resource.$_.submitted_by";
                    622: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    623:     }
                    624:     return %partstatus;
                    625: }
                    626: 
1.45      ng        627: # hidden form and javascript that calls the form
                    628: # Use by verifyscript and viewgrades
                    629: # Shows a student's view of problem and submission
                    630: sub jscriptNform {
1.324     albertel  631:     my ($symb) = @_;
1.442     banghart  632:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  633:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        634: 	'    function viewOneStudent(user,domain) {'."\n".
                    635: 	'	document.onestudent.student.value = user;'."\n".
                    636: 	'	document.onestudent.userdom.value = domain;'."\n".
                    637: 	'	document.onestudent.submit();'."\n".
                    638: 	'    }'."\n".
1.597     wenzelju  639: 	"\n");
1.45      ng        640:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  641: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        643: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    644: 	'<input type="hidden" name="student" value="" />'."\n".
                    645: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    646: 	'</form>'."\n";
                    647:     return $jscript;
                    648: }
1.39      ng        649: 
1.447     foxr      650: 
                    651: 
1.315     bowersj2  652: # Given the score (as a number [0-1] and the weight) what is the final
                    653: # point value? This function will round to the nearest tenth, third,
                    654: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  655: sub compute_points {
1.315     bowersj2  656:     my ($score, $weight) = @_;
                    657:     
                    658:     my $tolerance = .00001;
                    659:     my $points = $score * $weight;
                    660: 
                    661:     # Check for nearness to 1/x.
                    662:     my $check_for_nearness = sub {
                    663:         my ($factor) = @_;
                    664:         my $num = ($points * $factor) + $tolerance;
                    665:         my $floored_num = floor($num);
1.316     albertel  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  667:             return $floored_num / $factor;
                    668:         }
                    669:         return $points;
                    670:     };
                    671: 
                    672:     $points = $check_for_nearness->(10);
                    673:     $points = $check_for_nearness->(3);
                    674:     $points = $check_for_nearness->(4);
                    675:     
                    676:     return $points;
                    677: }
                    678: 
1.44      ng        679: #------------------ End of general use routines --------------------
1.87      www       680: 
                    681: #
                    682: # Find most similar essay
                    683: #
                    684: 
                    685: sub most_similar {
1.674   ! raeburn   686:     my ($uname,$udom,$symb,$uessay)=@_;
        !           687: 
        !           688:     unless ($symb) { return ''; }
        !           689: 
        !           690:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       691: 
                    692: # ignore spaces and punctuation
                    693: 
                    694:     $uessay=~s/\W+/ /gs;
                    695: 
1.282     www       696: # ignore empty submissions (occuring when only files are sent)
                    697: 
1.598     www       698:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       699: 
1.87      www       700: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       701:     my $limit=0.6;
1.87      www       702:     my $sname='';
                    703:     my $sdom='';
                    704:     my $scrsid='';
                    705:     my $sessay='';
                    706: # go through all essays ...
1.674   ! raeburn   707:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  708: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       709: # ... except the same student
1.426     albertel  710:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674   ! raeburn   711: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  712: 	$tessay=~s/\W+/ /gs;
1.87      www       713: # String similarity gives up if not even limit
1.426     albertel  714: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       715: # Found one
1.426     albertel  716: 	if ($tsimilar>$limit) {
                    717: 	    $limit=$tsimilar;
                    718: 	    $sname=$tname;
                    719: 	    $sdom=$tdom;
                    720: 	    $scrsid=$tcrsid;
1.674   ! raeburn   721: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  722: 	}
1.87      www       723:     }
1.88      www       724:     if ($limit>0.6) {
1.87      www       725:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    726:     } else {
                    727:        return ('','','','',0);
                    728:     }
                    729: }
                    730: 
1.44      ng        731: #-------------------------------------------------------------------
                    732: 
                    733: #------------------------------------ Receipt Verification Routines
1.45      ng        734: #
1.602     www       735: 
                    736: sub initialverifyreceipt {
1.608     www       737:    my ($request,$symb) = @_;
1.602     www       738:    &commonJSfunctions($request);
1.605     www       739:    return '<form name="gradingMenu"><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.652     raeburn  1549:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1550: 
1.564     bisitz   1551:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1552:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1553:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1554: }
                   1555:     function displaySubject(msg,shwsel) {
1.76      ng       1556:     pDoc = pWin.document;
                   1557:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1558:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1559:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1560:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1561: }
                   1562: 
1.72      ng       1563:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1564:     pDoc = pWin.document;
                   1565:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1566:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1567:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1568:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1569: }
                   1570: 
                   1571:   function newMsg(newmsg,shwsel) {
1.76      ng       1572:     pDoc = pWin.document;
                   1573:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1574:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1575:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1576:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1577: }
                   1578: 
                   1579:   function msgTail() {
1.76      ng       1580:     pDoc = pWin.document;
1.465     albertel 1581:     pDoc.write("<\\/table>");
                   1582:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1584:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1585:     pDoc.write("<\\/form>");
1.351     albertel 1586:     pDoc.write('$end_page_msg_central');
1.128     ng       1587:     pDoc.close();
1.44      ng       1588: }
                   1589: 
                   1590: //====================== Script for keyword highlight options ==============
                   1591:   function kwhighlight() {
                   1592:     var kwclr    = document.SCORE.kwclr.value;
                   1593:     var kwsize   = document.SCORE.kwsize.value;
                   1594:     var kwstyle  = document.SCORE.kwstyle.value;
                   1595:     var redsel = "";
                   1596:     var grnsel = "";
                   1597:     var blusel = "";
                   1598:     if (kwclr=="red")   {var redsel="checked"};
                   1599:     if (kwclr=="green") {var grnsel="checked"};
                   1600:     if (kwclr=="blue")  {var blusel="checked"};
                   1601:     var sznsel = "";
                   1602:     var sz1sel = "";
                   1603:     var sz2sel = "";
                   1604:     if (kwsize=="0")  {var sznsel="checked"};
                   1605:     if (kwsize=="+1") {var sz1sel="checked"};
                   1606:     if (kwsize=="+2") {var sz2sel="checked"};
                   1607:     var synsel = "";
                   1608:     var syisel = "";
                   1609:     var sybsel = "";
                   1610:     if (kwstyle=="")    {var synsel="checked"};
                   1611:     if (kwstyle=="<i>") {var syisel="checked"};
                   1612:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1613:     highlightCentral();
                   1614:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1615:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1616:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1617:     highlightend();
                   1618:     return;
                   1619:   }
                   1620: 
                   1621:   function highlightCentral() {
1.76      ng       1622: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1623:     var xpos = (screen.width-400)/2;
                   1624:     xpos = (xpos < 0) ? '0' : xpos;
                   1625:     var ypos = (screen.height-330)/2-30;
                   1626:     ypos = (ypos < 0) ? '0' : ypos;
                   1627: 
1.206     albertel 1628:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1629:     hwdWin.focus();
                   1630:     var hDoc = hwdWin.document;
1.219     www      1631:     hDoc.$docopen;
1.351     albertel 1632:     hDoc.write('$start_page_highlight_central');
1.76      ng       1633:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1634:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1635: 
1.564     bisitz   1636:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1637:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1638:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1639:   }
                   1640: 
                   1641:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1642:     var hDoc = hwdWin.document;
                   1643:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1644:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1645:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1646:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1647:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1648:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1649:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1650:     hDoc.write("<\\/tr>");
1.44      ng       1651:   }
                   1652: 
                   1653:   function highlightend() { 
1.76      ng       1654:     var hDoc = hwdWin.document;
1.465     albertel 1655:     hDoc.write("<\\/table>");
                   1656:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1658:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1659:     hDoc.write("<\\/form>");
1.351     albertel 1660:     hDoc.write('$end_page_highlight_central');
1.128     ng       1661:     hDoc.close();
1.44      ng       1662:   }
                   1663: 
                   1664: SUBJAVASCRIPT
                   1665: }
                   1666: 
1.349     albertel 1667: sub get_increment {
1.348     bowersj2 1668:     my $increment = $env{'form.increment'};
                   1669:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1670:         $increment != .1) {
                   1671:         $increment = 1;
                   1672:     }
                   1673:     return $increment;
                   1674: }
                   1675: 
1.585     bisitz   1676: sub gradeBox_start {
                   1677:     return (
                   1678:         &Apache::loncommon::start_data_table()
                   1679:        .&Apache::loncommon::start_data_table_header_row()
                   1680:        .'<th>'.&mt('Part').'</th>'
                   1681:        .'<th>'.&mt('Points').'</th>'
                   1682:        .'<th>&nbsp;</th>'
                   1683:        .'<th>'.&mt('Assign Grade').'</th>'
                   1684:        .'<th>'.&mt('Weight').'</th>'
                   1685:        .'<th>'.&mt('Grade Status').'</th>'
                   1686:        .&Apache::loncommon::end_data_table_header_row()
                   1687:     );
                   1688: }
                   1689: 
                   1690: sub gradeBox_end {
                   1691:     return (
                   1692:         &Apache::loncommon::end_data_table()
                   1693:     );
                   1694: }
1.71      ng       1695: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1696: sub gradeBox {
1.322     albertel 1697:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1698:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1699: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1700:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1701:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1702:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1703:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1704:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1705: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1706:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1707:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1708:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1709: 				       [$partid]);
                   1710:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1711:     if ($last_resets{$partid}) {
                   1712:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1713:     }
1.585     bisitz   1714:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1715:     my $ctr = 0;
1.348     bowersj2 1716:     my $thisweight = 0;
1.349     albertel 1717:     my $increment = &get_increment();
1.485     albertel 1718: 
                   1719:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1720:     while ($thisweight<=$wgt) {
1.532     bisitz   1721: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1722:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1723: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1724: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1725: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1726:         $thisweight += $increment;
1.71      ng       1727: 	$ctr++;
                   1728:     }
1.485     albertel 1729:     $radio.='</tr></table>';
                   1730: 
                   1731:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1732: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1733: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1734: 	$wgt.')" /></td>'."\n";
1.485     albertel 1735:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1736: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1737: 	' </td>'."\n";
                   1738:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1739: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1740:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1741: 	$line.='<option></option>'.
                   1742: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1743:     } else {
1.485     albertel 1744: 	$line.='<option selected="selected"></option>'.
                   1745: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1746:     }
1.485     albertel 1747:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1748: 
                   1749: 
                   1750:     $result .= 
1.585     bisitz   1751: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1752:     $result.=&Apache::loncommon::end_data_table_row();
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);
                   1763:     if ($res_error) {
                   1764:         return &navmap_errormsg();
                   1765:     }
1.318     banghart 1766:     return $result;
                   1767: }
1.322     albertel 1768: 
                   1769: sub handback_box {
1.623     www      1770:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1771:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1772:     my (@respids);
1.652     raeburn  1773:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1774:     foreach my $part_response_id (@part_response_id) {
                   1775:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1776:         if ($part eq $partid) {
1.375     albertel 1777:             push(@respids,$resp);
1.323     banghart 1778:         }
                   1779:     }
1.318     banghart 1780:     my $result;
1.323     banghart 1781:     foreach my $respid (@respids) {
1.322     albertel 1782: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1783: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1784: 	next if (!@$files);
1.654     raeburn  1785: 	my $file_counter = 0;
1.313     banghart 1786: 	foreach my $file (@$files) {
1.368     banghart 1787: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1788:                 $file_counter++;
1.368     banghart 1789:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1790:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1791:     	        $file_disp = "$name.$ext";
                   1792:     	        $file = $file_path.$file_disp;
                   1793:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1794:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1795:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1796:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1797: 	    }
1.322     albertel 1798: 	}
1.654     raeburn  1799:         if ($file_counter) {
                   1800:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1801:                        '<span class="LC_info">'.
                   1802:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1803:         }
1.313     banghart 1804:     }
1.318     banghart 1805:     return $result;    
1.71      ng       1806: }
1.44      ng       1807: 
1.58      albertel 1808: sub show_problem {
1.382     albertel 1809:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1810:     my $rendered;
1.382     albertel 1811:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1812:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1813:     if ($mode eq 'both' or $mode eq 'text') {
                   1814: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1815: 						       $env{'request.course.id'},
                   1816: 						       undef,\%form);
1.144     albertel 1817:     }
1.58      albertel 1818:     if ($removeform) {
                   1819: 	$rendered=~s|<form(.*?)>||g;
                   1820: 	$rendered=~s|</form>||g;
1.374     albertel 1821: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1822:     }
1.144     albertel 1823:     my $companswer;
                   1824:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1825: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1826: 	$companswer=
                   1827: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1828: 						    $env{'request.course.id'},
                   1829: 						    %form);
1.144     albertel 1830:     }
1.58      albertel 1831:     if ($removeform) {
                   1832: 	$companswer=~s|<form(.*?)>||g;
                   1833: 	$companswer=~s|</form>||g;
1.144     albertel 1834: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1835:     }
1.671     raeburn  1836:     my $renderheading = &mt('View of the problem');
                   1837:     my $answerheading = &mt('Correct answer');
                   1838:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1839:         my $stu_fullname = $env{'form.fullname'};
                   1840:         if ($stu_fullname eq '') {
                   1841:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1842:         }
                   1843:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1844:         if ($forwhom ne '') {
                   1845:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1846:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1847:         }
                   1848:     }
1.468     albertel 1849:     $rendered=
1.588     bisitz   1850:         '<div class="LC_Box">'
1.671     raeburn  1851:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1852:        .$rendered
                   1853:        .'</div>';
1.468     albertel 1854:     $companswer=
1.588     bisitz   1855:         '<div class="LC_Box">'
1.671     raeburn  1856:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1857:        .$companswer
                   1858:        .'</div>';
1.468     albertel 1859:     my $result;
1.144     albertel 1860:     if ($mode eq 'both') {
1.588     bisitz   1861:         $result=$rendered.$companswer;
1.144     albertel 1862:     } elsif ($mode eq 'text') {
1.588     bisitz   1863:         $result=$rendered;
1.144     albertel 1864:     } elsif ($mode eq 'answer') {
1.588     bisitz   1865:         $result=$companswer;
1.144     albertel 1866:     }
1.71      ng       1867:     return $result;
1.58      albertel 1868: }
1.397     albertel 1869: 
1.396     banghart 1870: sub files_exist {
                   1871:     my ($r, $symb) = @_;
                   1872:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1873: 
1.396     banghart 1874:     foreach my $student (@students) {
                   1875:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1876:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1877: 					      $udom,$uname);
1.396     banghart 1878:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1879:         foreach my $submission (@$string) {
                   1880:             my ($partid,$respid) =
                   1881: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1882:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1883: 					   \%record);
                   1884:             return 1 if (@$files);
1.396     banghart 1885:         }
                   1886:     }
1.397     albertel 1887:     return 0;
1.396     banghart 1888: }
1.397     albertel 1889: 
1.394     banghart 1890: sub download_all_link {
                   1891:     my ($r,$symb) = @_;
1.621     www      1892:     unless (&files_exist($r, $symb)) {
                   1893:        $r->print(&mt('There are currently no submitted documents.'));
                   1894:        return;
                   1895:     }
                   1896: 
1.395     albertel 1897:     my $all_students = 
                   1898: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1899: 
                   1900:     my $parts =
                   1901: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1902: 
1.394     banghart 1903:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1904:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1905:                              'cgi.'.$identifier.'.symb' => $symb,
                   1906:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1907:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1908: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1909:     return;
                   1910: }
                   1911: 
                   1912: sub submit_download_link {
                   1913:     my ($request,$symb) = @_;
                   1914:     if (!$symb) { return ''; }
                   1915: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1916:     &download_all_link($request,$symb);
1.394     banghart 1917: }
1.395     albertel 1918: 
1.432     banghart 1919: sub build_section_inputs {
                   1920:     my $section_inputs;
                   1921:     if ($env{'form.section'} eq '') {
                   1922:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1923:     } else {
                   1924:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1925:         foreach my $section (@sections) {
1.432     banghart 1926:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1927:         }
                   1928:     }
                   1929:     return $section_inputs;
                   1930: }
                   1931: 
1.44      ng       1932: # --------------------------- show submissions of a student, option to grade 
                   1933: sub submission {
1.608     www      1934:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1935:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1936:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1937:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1938:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1939: 
1.605     www      1940:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1941:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1942: 
                   1943:     if (!&canview($usec)) {
1.398     albertel 1944: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1945: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1946: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1947: 	return;
                   1948:     }
                   1949: 
1.257     albertel 1950:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1951:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1952:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1953:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1954:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1955: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1956: 	'/check.gif" height="16" border="0" />';
1.41      ng       1957: 
                   1958:     # header info
                   1959:     if ($counter == 0) {
                   1960: 	&sub_page_js($request);
1.621     www      1961: 	&sub_page_kw_js($request);
1.118     ng       1962: 
1.44      ng       1963: 	# option to display problem, only once else it cause problems 
                   1964:         # with the form later since the problem has a form.
1.257     albertel 1965: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1966: 	    my $mode;
1.257     albertel 1967: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1968: 		$mode='both';
1.257     albertel 1969: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1970: 		$mode='text';
1.257     albertel 1971: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1972: 		$mode='answer';
                   1973: 	    }
1.329     albertel 1974: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1975: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1976: 	}
1.441     www      1977: 
1.44      ng       1978: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1979:         # if this subroutine has been called once.
1.41      ng       1980: 	my %keyhash = ();
1.624     www      1981: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1982:         if (1) {
1.41      ng       1983: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1984: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1985: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1986: 
1.257     albertel 1987: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1988: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1989: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1990: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1991: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1992: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1993: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1994: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1995: 	}
1.257     albertel 1996: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1997: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1998: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1999: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2000: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2001: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2002: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2003: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2004: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2005: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2006: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2007: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2008: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2009: 			&build_section_inputs().
1.326     albertel 2010: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2011: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2012: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2013: #	if ($env{'form.handgrade'} eq 'yes') {
                   2014:         if (1) {
1.257     albertel 2015: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2016: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2017: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2018: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2019: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2020: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2021: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2022: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2023: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2024: 	    }
1.123     ng       2025: 	}
1.41      ng       2026: 	
                   2027: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2028: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2029: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2030: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2031: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2032: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2033: 		'" />'."\n".
                   2034: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2035: 	    $cts++;
                   2036: 	}
                   2037: 	$request->print($prnmsg);
1.32      ng       2038: 
1.624     www      2039: #	if ($env{'form.handgrade'} eq 'yes') {
                   2040:         if (1) {
1.652     raeburn  2041: 
                   2042:             my %lt = &Apache::lonlocal::texthash(
                   2043:                           keyw => 'Keyword Options',
1.655     raeburn  2044:                           list => 'List',
1.652     raeburn  2045:                           past => 'Paste Selection to List',
1.661     www      2046:                           high => 'Highlight Attribute',
1.652     raeburn  2047:                      );    
1.88      www      2048: #
                   2049: # Print out the keyword options line
                   2050: #
1.41      ng       2051: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2052: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2053: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2054: <a href="#" onmousedown="javascript:getSel(); return false"
1.652     raeburn  2055:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2056: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2057: KEYWORDS
1.88      www      2058: #
                   2059: # Load the other essays for similarity check
                   2060: #
1.324     albertel 2061:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2062: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2063: 	    $apath=&escape($apath);
1.88      www      2064: 	    $apath=~s/\W/\_/gs;
1.674   ! raeburn  2065:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2066:         }
                   2067:     }
1.44      ng       2068: 
1.441     www      2069: # This is where output for one specific student would start
1.592     bisitz   2070:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2071:     $request->print(
                   2072:         "\n\n"
                   2073:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2074:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2075:        ."\n"
                   2076:     );
1.441     www      2077: 
1.592     bisitz   2078:     # Show additional functions if allowed
                   2079:     if ($perm{'vgr'}) {
                   2080:         $request->print(
                   2081:             &Apache::loncommon::track_student_link(
                   2082:                 &mt('View recent activity'),
                   2083:                 $uname,$udom,'check')
                   2084:            .' '
                   2085:         );
                   2086:     }
                   2087:     if ($perm{'opa'}) {
                   2088:         $request->print(
                   2089:             &Apache::loncommon::pprmlink(
                   2090:                 &mt('Set/Change parameters'),
                   2091:                 $uname,$udom,$symb,'check'));
                   2092:     }
                   2093: 
                   2094:     # Show Problem
1.257     albertel 2095:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2096: 	my $mode;
1.257     albertel 2097: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2098: 	    $mode='both';
1.257     albertel 2099: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2100: 	    $mode='text';
1.257     albertel 2101: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2102: 	    $mode='answer';
                   2103: 	}
1.329     albertel 2104: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2105: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2106:     }
1.144     albertel 2107: 
1.257     albertel 2108:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2109:     my $res_error;
                   2110:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2111:     if ($res_error) {
                   2112:         $request->print(&navmap_errormsg());
                   2113:         return;
                   2114:     }
1.41      ng       2115: 
1.44      ng       2116:     # Display student info
1.41      ng       2117:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2118: 
                   2119:     my $result='<div class="LC_Box">'
                   2120:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2121:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2122:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2123: #    if ($env{'form.handgrade'} eq 'no') {
                   2124:     if (1) {
1.588     bisitz   2125:         $result.='<p class="LC_info">'
                   2126:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2127:                 ."</p>\n";
1.469     albertel 2128:     }
                   2129: 
1.118     ng       2130:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2131:     my $fullname;
                   2132:     my $col_fullnames = [];
1.624     www      2133: #    if ($env{'form.handgrade'} eq 'yes') {
                   2134:     if (1) {
1.464     albertel 2135: 	(my $sub_result,$fullname,$col_fullnames)=
                   2136: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2137: 				 $counter);
                   2138: 	$result.=$sub_result;
1.41      ng       2139:     }
1.44      ng       2140:     $request->print($result."\n");
1.588     bisitz   2141: 
1.44      ng       2142:     # print student answer/submission
1.588     bisitz   2143:     # Options are (1) Handgraded submission only
1.44      ng       2144:     #             (2) Last submission, includes submission that is not handgraded 
                   2145:     #                  (for multi-response type part)
                   2146:     #             (3) Last submission plus the parts info
                   2147:     #             (4) The whole record for this student
1.257     albertel 2148:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2149: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2150: 	
                   2151: 	my $lastsubonly;
                   2152: 
1.588     bisitz   2153:         if ($$timestamp eq '') {
                   2154:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2155:         } else {
1.592     bisitz   2156:             $lastsubonly =
                   2157:                 '<div class="LC_grade_submissions_body">'
                   2158:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2159: 
1.151     albertel 2160: 	    my %seenparts;
1.375     albertel 2161: 	    my @part_response_id = &flatten_responseType($responseType);
                   2162: 	    foreach my $part (@part_response_id) {
1.393     albertel 2163: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2164: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2165: 
1.375     albertel 2166: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2167: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2168: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2169: 		    if (exists($seenparts{$partid})) { next; }
                   2170: 		    $seenparts{$partid}=1;
1.207     albertel 2171: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2172: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2173: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2174: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2175: 			'\');" target="_self">'.
1.257     albertel 2176: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2177: 		    $request->print($submitby);
                   2178: 		    next;
                   2179: 		}
                   2180: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2181: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2182:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2183:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2184:                         ' <span class="LC_internal_info">'.
1.623     www      2185:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2186:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2187: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2188: 		    next;
                   2189: 		}
1.468     albertel 2190: 		foreach my $submission (@$string) {
                   2191: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2192: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2193: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2194: 		    # Similarity check
                   2195: 		    my $similar='';
1.640     raeburn  2196:                     my ($type,$trial,$rndseed);
                   2197:                     if ($hide eq 'rand') {
                   2198:                         $type = 'randomizetry';
                   2199:                         $trial = $record{"resource.$partid.tries"};
                   2200:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2201:                     }
1.257     albertel 2202: 		    if($env{'form.checkPlag'}){
1.151     albertel 2203: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.674   ! raeburn  2204: 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2205: 			if ($osim) {
                   2206: 			    $osim=int($osim*100.0);
1.426     albertel 2207: 			    my %old_course_desc = 
                   2208: 				&Apache::lonnet::coursedescription($ocrsid,
                   2209: 								   {'one_time' => 1});
                   2210: 
1.640     raeburn  2211:                             if ($hide eq 'anon') {
1.596     raeburn  2212:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2213:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2214:                             } else {
                   2215: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2216: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2217: 				        $osim,
                   2218: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2219: 				        $old_course_desc{'description'},
                   2220: 				        $old_course_desc{'num'},
                   2221: 				        $old_course_desc{'domain'}).
                   2222: 				    '</span></h3><blockquote><i>'.
                   2223: 				    &keywords_highlight($oessay).
                   2224: 				    '</i></blockquote><hr />';
                   2225:                             }
1.151     albertel 2226: 			}
1.150     albertel 2227: 		    }
1.640     raeburn  2228: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2229:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2230: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2231: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2232: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2233: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2234:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2235:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2236:                             ' <span class="LC_internal_info">'.
1.623     www      2237:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2238:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2239: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2240: 			if (@$files) {
1.640     raeburn  2241:                             if ($hide eq 'anon') {
1.596     raeburn  2242:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2243:                             } else {
                   2244:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2245:                                 foreach my $file (@$files) {
                   2246:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2247:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2248:                                 }
                   2249:                             }
1.236     albertel 2250: 			    $lastsubonly.='<br />';
1.41      ng       2251: 			}
1.640     raeburn  2252:                         if ($hide eq 'anon') {
1.596     raeburn  2253:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2254:                         } else {
                   2255: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2256: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2257: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2258:                         }
1.151     albertel 2259: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2260: 			$lastsubonly.='</div>';
1.41      ng       2261: 		    }
                   2262: 		}
                   2263: 	    }
1.588     bisitz   2264: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2265: 	}
                   2266: 	$request->print($lastsubonly);
1.468     albertel 2267:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2268:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2269: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2270:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2271: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2272: 								 $env{'request.course.id'},
1.44      ng       2273: 								 $last,'.submission',
                   2274: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2275:     }
1.121     ng       2276:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2277: 	.$udom.'" />'."\n");
1.44      ng       2278:     # return if view submission with no grading option
1.618     www      2279:     if (!&canmodify($usec)) {
1.633     www      2280: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2281: 	return;
1.180     albertel 2282:     } else {
1.468     albertel 2283: 	$request->print('</div>'."\n");
1.41      ng       2284:     }
1.33      ng       2285: 
1.121     ng       2286:     # essay grading message center
1.624     www      2287: #    if ($env{'form.handgrade'} eq 'yes') {
                   2288:     if (1) {
1.468     albertel 2289: 	my $result='<div class="LC_grade_message_center">';
                   2290:     
                   2291: 	$result.='<div class="LC_grade_message_center_header">'.
                   2292: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2293: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2294: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2295: 	if (scalar(@$col_fullnames) > 0) {
                   2296: 	    my $lastone = pop(@$col_fullnames);
                   2297: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2298: 	}
                   2299: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2300: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2301: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2302: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2303: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2304: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2305: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2306: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2307: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2308: 	    '<br />&nbsp;('.
1.468     albertel 2309: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2310: 	$result.='</div></div>';
1.121     ng       2311: 	$request->print($result);
1.118     ng       2312:     }
1.41      ng       2313: 
                   2314:     my %seen = ();
                   2315:     my @partlist;
1.129     ng       2316:     my @gradePartRespid;
1.375     albertel 2317:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2318:     $request->print(
1.588     bisitz   2319:         '<div class="LC_Box">'
                   2320:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2321:     );
1.592     bisitz   2322:     $request->print(&gradeBox_start());
1.375     albertel 2323:     foreach my $part_response_id (@part_response_id) {
                   2324:     	my ($partid,$respid) = @{ $part_response_id };
                   2325: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2326: 	next if ($seen{$partid} > 0);
1.41      ng       2327: 	$seen{$partid}++;
1.393     albertel 2328: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2329: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2330: 	push(@partlist,$partid);
                   2331: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2332: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2333:     }
1.585     bisitz   2334:     $request->print(&gradeBox_end()); # </div>
                   2335:     $request->print('</div>');
1.468     albertel 2336: 
                   2337:     $request->print('<div class="LC_grade_info_links">');
                   2338:     $request->print('</div>');
                   2339: 
1.45      ng       2340:     $result='<input type="hidden" name="partlist'.$counter.
                   2341: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2342:     $result.='<input type="hidden" name="gradePartRespid'.
                   2343: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2344:     my $ctr = 0;
                   2345:     while ($ctr < scalar(@partlist)) {
                   2346: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2347: 	    $partlist[$ctr].'" />'."\n";
                   2348: 	$ctr++;
                   2349:     }
1.468     albertel 2350:     $request->print($result.''."\n");
1.41      ng       2351: 
1.441     www      2352: # Done with printing info for one student
                   2353: 
1.468     albertel 2354:     $request->print('</div>');#LC_grade_show_user
1.441     www      2355: 
                   2356: 
1.41      ng       2357:     # print end of form
                   2358:     if ($counter == $total) {
1.592     bisitz   2359:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2360: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2361: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2362: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2363: 	my $ntstu ='<select name="NTSTU">'.
                   2364: 	    '<option>1</option><option>2</option>'.
                   2365: 	    '<option>3</option><option>5</option>'.
                   2366: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2367: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2368: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2369:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2370: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2371: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2372: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2373: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2374:         $endform.='<span class="LC_warning">'.
                   2375:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2376:                   '</span>'."\n" ;
1.349     albertel 2377:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2378:             "' name='increment' />";
1.485     albertel 2379: 	$endform.='</td></tr></table></form>';
1.41      ng       2380: 	$request->print($endform);
                   2381:     }
                   2382:     return '';
1.38      ng       2383: }
                   2384: 
1.464     albertel 2385: sub check_collaborators {
                   2386:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2387:     my ($result,@col_fullnames);
                   2388:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2389:     foreach my $part (keys(%$handgrade)) {
                   2390: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2391: 					'.maxcollaborators',
                   2392: 					$symb,$udom,$uname);
                   2393: 	next if ($ncol <= 0);
                   2394: 	$part =~ s/\_/\./g;
                   2395: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2396: 	my (@good_collaborators, @bad_collaborators);
                   2397: 	foreach my $possible_collaborator
1.630     www      2398: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2399: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2400: 	    next if ($possible_collaborator eq '');
1.631     www      2401: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2402: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2403: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2404: 	    # Doing this grep allows 'fuzzy' specification
                   2405: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2406: 			       keys(%$classlist));
                   2407: 	    if (! scalar(@matches)) {
                   2408: 		push(@bad_collaborators, $possible_collaborator);
                   2409: 	    } else {
                   2410: 		push(@good_collaborators, @matches);
                   2411: 	    }
                   2412: 	}
                   2413: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2414: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2415: 	    foreach my $name (@good_collaborators) {
                   2416: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2417: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2418: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2419: 	    }
1.630     www      2420: 	    $result.='</ol><br />'."\n";
1.466     albertel 2421: 	    my ($part)=split(/\./,$part);
1.464     albertel 2422: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2423: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2424: 		"\n";
                   2425: 	}
                   2426: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2427: 	    $result.='<div class="LC_warning">';
1.464     albertel 2428: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2429: 	    $result .= '</div>';
                   2430: 	}         
                   2431: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2432: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2433: 	    $result .= &mt('This student has submitted too many '.
                   2434: 		'collaborators.  Maximum is [_1].',$ncol);
                   2435: 	    $result .= '</div>';
                   2436: 	}
                   2437:     }
                   2438:     return ($result,$fullname,\@col_fullnames);
                   2439: }
                   2440: 
1.44      ng       2441: #--- Retrieve the last submission for all the parts
1.38      ng       2442: sub get_last_submission {
1.119     ng       2443:     my ($returnhash)=@_;
1.596     raeburn  2444:     my (@string,$timestamp,%lasthidden);
1.119     ng       2445:     if ($$returnhash{'version'}) {
1.46      ng       2446: 	my %lasthash=();
                   2447: 	my ($version);
1.119     ng       2448: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2449: 	    foreach my $key (sort(split(/\:/,
                   2450: 					$$returnhash{$version.':keys'}))) {
                   2451: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2452: 		$timestamp = 
1.545     raeburn  2453: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2454: 	    }
                   2455: 	}
1.640     raeburn  2456:         my (%typeparts,%randombytry);
1.596     raeburn  2457:         my $showsurv = 
                   2458:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2459:         foreach my $key (sort(keys(%lasthash))) {
                   2460:             if ($key =~ /\.type$/) {
                   2461:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2462:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2463:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2464:                     my ($ign,@parts) = split(/\./,$key);
                   2465:                     pop(@parts);
1.641     raeburn  2466:                     my $id = join('.',@parts);
1.640     raeburn  2467:                     if ($lasthash{$key} eq 'randomizetry') {
                   2468:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2469:                     } else {
                   2470:                         unless ($showsurv) {
                   2471:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2472:                         }
1.596     raeburn  2473:                     }
                   2474:                     delete($lasthash{$key});
                   2475:                 }
                   2476:             }
                   2477:         }
                   2478:         my @hidden = keys(%typeparts);
1.640     raeburn  2479:         my @randomize = keys(%randombytry);
1.397     albertel 2480: 	foreach my $key (keys(%lasthash)) {
                   2481: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2482:             my $hide;
                   2483:             if (@hidden) {
                   2484:                 foreach my $id (@hidden) {
                   2485:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2486:                         $hide = 'anon';
1.596     raeburn  2487:                         last;
                   2488:                     }
                   2489:                 }
                   2490:             }
1.640     raeburn  2491:             unless ($hide) {
                   2492:                 if (@randomize) {
                   2493:                     foreach my $id (@hidden) {
                   2494:                         if ($key =~ /^\Q$id\E/) {
                   2495:                             $hide = 'rand';
                   2496:                             last;
                   2497:                         }
                   2498:                     }
                   2499:                 }
                   2500:             }
1.397     albertel 2501: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2502: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2503: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2504: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2505: 	}
                   2506:     }
1.397     albertel 2507:     if (!@string) {
                   2508: 	$string[0] =
1.539     riegler  2509: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2510:     }
                   2511:     return (\@string,\$timestamp);
1.38      ng       2512: }
1.35      ng       2513: 
1.44      ng       2514: #--- High light keywords, with style choosen by user.
1.38      ng       2515: sub keywords_highlight {
1.44      ng       2516:     my $string    = shift;
1.257     albertel 2517:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2518:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2519:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2520:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2521:     foreach my $keyword (@keylist) {
                   2522: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2523:     }
                   2524:     return $string;
1.38      ng       2525: }
1.36      ng       2526: 
1.671     raeburn  2527: # For Tasks provide a mechanism to display previous version for one specific student
                   2528: 
                   2529: sub show_previous_task_version {
                   2530:     my ($request,$symb) = @_;
                   2531:     if ($symb eq '') {
                   2532:         $request->print("Unable to handle ambiguous references.");
                   2533: 
                   2534:         return '';
                   2535:     }
                   2536:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2537:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2538:     if (!&canview($usec)) {
                   2539:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
                   2540:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
                   2541:                         $env{'request.course.id'}.')</span>');
                   2542:         return;
                   2543:     }
                   2544:     my $mode = 'both';
                   2545:     my $isTask = ($symb =~/\.task$/);
                   2546:     if ($isTask) {
                   2547:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2548:             if ($env{'form.fullname'} eq '') {
                   2549:                 $env{'form.fullname'} =
                   2550:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2551:             }
                   2552:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2553:             $request->print("\n\n".
                   2554:                             '<div class="LC_grade_show_user">'.
                   2555:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2556:                             '</h2>'."\n");
                   2557:             &Apache::lonxml::clear_problem_counter();
                   2558:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2559:                             {'previousversion' => $env{'form.previousversion'} }));
                   2560:             $request->print("\n</div>");
                   2561:         }
                   2562:     }
                   2563:     return;
                   2564: }
                   2565: 
                   2566: sub choose_task_version_form {
                   2567:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2568:     my $isTask = ($symb =~/\.task$/);
                   2569:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2570:     if ($isTask) {
                   2571:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2572:                                               $udom,$uname);
                   2573:         if (($record{'resource.0.version'} eq '') ||
                   2574:             ($record{'resource.0.version'} < 2)) {
                   2575:             return ($record{'resource.0.version'},
                   2576:                     $record{'resource.0.version'},$result,$js);
                   2577:         } else {
                   2578:             $current = $record{'resource.0.version'};
                   2579:         }
                   2580:         if ($env{'form.previousversion'}) {
                   2581:             $displayed = $env{'form.previousversion'};
                   2582:             $rowtitle = &mt('Choose another version:')
                   2583:         } else {
                   2584:             $displayed = $current;
                   2585:             $rowtitle = &mt('Show earlier version:');
                   2586:         }
                   2587:         $result = '<div class="LC_left_float">';
                   2588:         my $list;
                   2589:         my $numversions = 0;
                   2590:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2591:             if ($i == $current) {
                   2592:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2593:                     next;
                   2594:                 } else {
                   2595:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2596:                     $numversions ++;
                   2597:                 }
                   2598:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2599:                 unless ($i == $env{'form.previousversion'}) {
                   2600:                     $numversions ++;
                   2601:                 }
                   2602:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2603:             }
                   2604:         }
                   2605:         if ($numversions) {
                   2606:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2607:             $result .=
                   2608:                 '<form name="getprev" method="post" action=""'.
                   2609:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2610:                 &Apache::loncommon::start_data_table().
                   2611:                 &Apache::loncommon::start_data_table_row().
                   2612:                 '<th align="left">'.$rowtitle.'</th>'.
                   2613:                 '<td><select name="version">'.
                   2614:                 '<option>'.&mt('Select').'</option>'.
                   2615:                 $list.
                   2616:                 '</select></td>'.
                   2617:                 &Apache::loncommon::end_data_table_row();
                   2618:             unless ($nomenu) {
                   2619:                 $result .= &Apache::loncommon::start_data_table_row().
                   2620:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2621:                 '<td><span class="LC_nobreak">'.
                   2622:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2623:                 &mt('Yes').'</label>'.
                   2624:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2625:                 '</span></td>'.
                   2626:                 &Apache::loncommon::end_data_table_row();
                   2627:             }
                   2628:             $result .=
                   2629:                 &Apache::loncommon::start_data_table_row().
                   2630:                 '<th align="left">&nbsp;</th>'.
                   2631:                 '<td>'.
                   2632:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2633:                 '</td>'.
                   2634:                 &Apache::loncommon::end_data_table_row().
                   2635:                 &Apache::loncommon::end_data_table().
                   2636:                 '</form>';
                   2637:             $js = &previous_display_javascript($nomenu,$current);
                   2638:         } elsif ($displayed && $nomenu) {
                   2639:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2640:         } else {
                   2641:             $result .= &mt('No previous versions to show for this student');
                   2642:         }
                   2643:         $result .= '</div>';
                   2644:     }
                   2645:     return ($current,$displayed,$result,$js);
                   2646: }
                   2647: 
                   2648: sub previous_display_javascript {
                   2649:     my ($nomenu,$current) = @_;
                   2650:     my $js = <<"JSONE";
                   2651: <script type="text/javascript">
                   2652: // <![CDATA[
                   2653: function previousVersion(uname,udom,symb) {
                   2654:     var current = '$current';
                   2655:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2656:     var prevstr = new RegExp("^\\\\d+\$");
                   2657:     if (!prevstr.test(version)) {
                   2658:         return false;
                   2659:     }
                   2660:     var url = '';
                   2661:     if (version == current) {
                   2662:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2663:     } else {
                   2664:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2665:     }
                   2666: JSONE
                   2667:     if ($nomenu) {
                   2668:         $js .= <<"JSTWO";
                   2669:     document.location.href = url;
                   2670: JSTWO
                   2671:     } else {
                   2672:         $js .= <<"JSTHREE";
                   2673:     var newwin = 0;
                   2674:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2675:         if (document.getprev.prevwin[i].checked == true) {
                   2676:             newwin = document.getprev.prevwin[i].value;
                   2677:         }
                   2678:     }
                   2679:     if (newwin == 1) {
                   2680:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2681:         url = url+'&inhibitmenu=yes';
                   2682:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2683:             previousWin = window.open(url,'',options,1);
                   2684:         } else {
                   2685:             previousWin.location.href = url;
                   2686:         }
                   2687:         previousWin.focus();
                   2688:         return false;
                   2689:     } else {
                   2690:         document.location.href = url;
                   2691:         return false;
                   2692:     }
                   2693: JSTHREE
                   2694:     }
                   2695:     $js .= <<"ENDJS";
                   2696:     return false;
                   2697: }
                   2698: // ]]>
                   2699: </script>
                   2700: ENDJS
                   2701: 
                   2702: }
                   2703: 
1.44      ng       2704: #--- Called from submission routine
1.38      ng       2705: sub processHandGrade {
1.608     www      2706:     my ($request,$symb) = @_;
1.324     albertel 2707:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2708:     my $button = $env{'form.gradeOpt'};
                   2709:     my $ngrade = $env{'form.NCT'};
                   2710:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2711:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2712:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2713: 
1.44      ng       2714:     if ($button eq 'Save & Next') {
                   2715: 	my $ctr = 0;
                   2716: 	while ($ctr < $ngrade) {
1.257     albertel 2717: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2718: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2719: 	    if ($errorflag eq 'no_score') {
                   2720: 		$ctr++;
                   2721: 		next;
                   2722: 	    }
1.104     albertel 2723: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2724: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2725: 		$ctr++;
                   2726: 		next;
                   2727: 	    }
1.257     albertel 2728: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2729: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2730: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2731:             my ($feedurl,$showsymb) =
                   2732: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2733: 	    my $messagetail;
1.62      albertel 2734: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2735: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2736: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2737: 		$subject.=' ['.$restitle.']';
1.44      ng       2738: 		my (@msgnum) = split(/,/,$includemsg);
                   2739: 		foreach (@msgnum) {
1.257     albertel 2740: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2741: 		}
1.80      ng       2742: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2743: 		if ($env{'form.withgrades'.$ctr}) {
                   2744: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2745: 		    $messagetail = " for <a href=\"".
1.605     www      2746: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2747: 		}
                   2748: 		$msgstatus = 
                   2749:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2750: 						     $message.$messagetail,
1.418     albertel 2751:                                                      undef,$feedurl,undef,
1.386     raeburn  2752:                                                      undef,undef,$showsymb,
                   2753:                                                      $restitle);
1.574     bisitz   2754: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2755: 				$msgstatus.'<br />');
1.44      ng       2756: 	    }
1.257     albertel 2757: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2758: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2759: 		foreach my $collabstr (@collabstrs) {
                   2760: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2761: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2762: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2763: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2764: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2765: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2766: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2767: 			    next;
1.418     albertel 2768: 			} elsif ($message ne '') {
                   2769: 			    my ($baseurl,$showsymb) = 
                   2770: 				&get_feedurl_and_symb($symb,$collaborator,
                   2771: 						      $udom);
                   2772: 			    if ($env{'form.withgrades'.$ctr}) {
                   2773: 				$messagetail = " for <a href=\"".
1.605     www      2774:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2775: 			    }
1.418     albertel 2776: 			    $msgstatus = 
                   2777: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2778: 			}
1.44      ng       2779: 		    }
                   2780: 		}
                   2781: 	    }
                   2782: 	    $ctr++;
                   2783: 	}
                   2784:     }
                   2785: 
1.624     www      2786: #    if ($env{'form.handgrade'} eq 'yes') {
                   2787:     if (1) {
1.119     ng       2788: 	# Keywords sorted in alphabatical order
1.257     albertel 2789: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2790: 	my %keyhash = ();
1.257     albertel 2791: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2792: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2793: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2794: 	$env{'form.keywords'} = join(' ',@keywords);
                   2795: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2796: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2797: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2798: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2799: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2800: 
                   2801: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2802: 	# New messages are saved in env for the next student.
1.119     ng       2803: 	# All messages are saved in nohist_handgrade.db
                   2804: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2805: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2806: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2807: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2808: 		$idx++;
                   2809: 	    }
                   2810: 	    $ctr++;
1.41      ng       2811: 	}
1.119     ng       2812: 	$ctr = 0;
                   2813: 	while ($ctr < $ngrade) {
1.257     albertel 2814: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2815: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2816: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2817: 		$idx++;
                   2818: 	    }
                   2819: 	    $ctr++;
1.41      ng       2820: 	}
1.257     albertel 2821: 	$env{'form.savemsgN'} = --$idx;
                   2822: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2823: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2824: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2825:     }
1.44      ng       2826:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2827:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2828:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2829: 	my ($ctr,$total) = (0,0);
                   2830: 	while ($ctr < $ngrade) {
1.257     albertel 2831: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2832: 	    $ctr++;
                   2833: 	}
1.257     albertel 2834: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2835: 	$ctr = 0;
                   2836: 	while ($ctr < $total) {
1.257     albertel 2837: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2838: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2839: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2840: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2841: 	    $ctr++;
                   2842: 	}
                   2843: 	return '';
                   2844:     }
1.36      ng       2845: 
1.44      ng       2846:     # Get the next/previous one or group of students
1.257     albertel 2847:     my $firststu = $env{'form.unamedom0'};
                   2848:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2849:     my $ctr = 2;
1.41      ng       2850:     while ($laststu eq '') {
1.257     albertel 2851: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2852: 	$ctr++;
                   2853: 	$laststu = $firststu if ($ctr > $ngrade);
                   2854:     }
1.44      ng       2855: 
1.41      ng       2856:     my (@parsedlist,@nextlist);
                   2857:     my ($nextflg) = 0;
1.524     raeburn  2858:     foreach my $item (sort 
1.294     albertel 2859: 	     {
                   2860: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2861: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2862: 		 }
                   2863: 		 return $a cmp $b;
                   2864: 	     } (keys(%$fullname))) {
1.605     www      2865: # FIXME: this is fishy, looks like the button label
1.41      ng       2866: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2867: 	    push(@parsedlist,$item);
1.41      ng       2868: 	}
1.524     raeburn  2869: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2870: 	if ($button eq 'Previous') {
1.524     raeburn  2871: 	    last if ($item eq $firststu);
                   2872: 	    push(@parsedlist,$item);
1.41      ng       2873: 	}
                   2874:     }
                   2875:     $ctr = 0;
1.605     www      2876: # FIXME: this is fishy, looks like the button label
1.41      ng       2877:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2878:     my $res_error;
                   2879:     my ($partlist) = &response_type($symb,\$res_error);
                   2880:     if ($res_error) {
                   2881:         $request->print(&navmap_errormsg());
                   2882:         return;
                   2883:     }
1.41      ng       2884:     foreach my $student (@parsedlist) {
1.257     albertel 2885: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2886: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2887: 	
                   2888: 	if ($submitonly eq 'queued') {
                   2889: 	    my %queue_status = 
                   2890: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2891: 							$udom,$uname);
                   2892: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2893: 	}
                   2894: 
1.156     albertel 2895: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2896: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2897: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2898: 	    my $submitted = 0;
1.248     albertel 2899: 	    my $ungraded = 0;
                   2900: 	    my $incorrect = 0;
1.524     raeburn  2901: 	    foreach my $item (keys(%status)) {
                   2902: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2903: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2904: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2905: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2906: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2907: 		    $submitted = 0;
                   2908: 		}
1.41      ng       2909: 	    }
1.156     albertel 2910: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2911: 				     $submitonly eq 'incorrect' ||
                   2912: 				     $submitonly eq 'graded'));
1.248     albertel 2913: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2914: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2915: 	}
1.524     raeburn  2916: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2917: 	last if ($ctr == $ntstu);
1.41      ng       2918: 	$ctr++;
                   2919:     }
1.36      ng       2920: 
1.41      ng       2921:     $ctr = 0;
                   2922:     my $total = scalar(@nextlist)-1;
1.39      ng       2923: 
1.524     raeburn  2924:     foreach (sort(@nextlist)) {
1.41      ng       2925: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2926: 	$env{'form.student'}  = $uname;
                   2927: 	$env{'form.userdom'}  = $udom;
                   2928: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2929: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2930: 	$ctr++;
                   2931:     }
                   2932:     if ($total < 0) {
1.653     raeburn  2933: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2934: 	$request->print($the_end);
                   2935:     }
                   2936:     return '';
1.38      ng       2937: }
1.36      ng       2938: 
1.44      ng       2939: #---- Save the score and award for each student, if changed
1.38      ng       2940: sub saveHandGrade {
1.324     albertel 2941:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2942:     my @version_parts;
1.104     albertel 2943:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2944: 					   $env{'request.course.id'});
1.104     albertel 2945:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2946:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2947:     my @parts_graded;
1.77      ng       2948:     my %newrecord  = ();
                   2949:     my ($pts,$wgt) = ('','');
1.269     raeburn  2950:     my %aggregate = ();
                   2951:     my $aggregateflag = 0;
1.301     albertel 2952:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2953:     foreach my $new_part (@parts) {
1.337     banghart 2954: 	#collaborator ($submi may vary for different parts
1.259     banghart 2955: 	if ($submitter && $new_part ne $part) { next; }
                   2956: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2957: 	if ($dropMenu eq 'excused') {
1.259     banghart 2958: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2959: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2960: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2961: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2962: 		}
1.364     banghart 2963: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2964: 	    }
1.125     ng       2965: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2966: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2967: 	    foreach my $key (keys(%record)) {
1.259     banghart 2968: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2969: 	    }
1.259     banghart 2970: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2971: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2972:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2973: 
                   2974:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2975: 					       [$new_part]);
                   2976:             my $aggtries =$totaltries;
1.269     raeburn  2977:             if ($last_resets{$new_part}) {
1.270     albertel 2978:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2979: 					   $new_part);
1.269     raeburn  2980:             }
1.270     albertel 2981: 
                   2982:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2983:             if ($aggtries > 0) {
1.327     albertel 2984:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2985:                 $aggregateflag = 1;
                   2986:             }
1.125     ng       2987: 	} elsif ($dropMenu eq '') {
1.259     banghart 2988: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2989: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2990: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2991: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2992: 		next;
                   2993: 	    }
1.259     banghart 2994: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2995: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2996: 	    my $partial= $pts/$wgt;
1.259     banghart 2997: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2998: 		#do not update score for part if not changed.
1.346     banghart 2999:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3000: 		next;
1.251     banghart 3001: 	    } else {
1.524     raeburn  3002: 	        push(@parts_graded,$new_part);
1.153     albertel 3003: 	    }
1.259     banghart 3004: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3005: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3006: 	    }
1.259     banghart 3007: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3008: 	    if ($partial == 0) {
1.153     albertel 3009: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3010: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3011: 		}
1.41      ng       3012: 	    } else {
1.153     albertel 3013: 		if ($record{$reckey} ne 'correct_by_override') {
                   3014: 		    $newrecord{$reckey} = 'correct_by_override';
                   3015: 		}
                   3016: 	    }	    
                   3017: 	    if ($submitter && 
1.259     banghart 3018: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3019: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3020: 	    }
1.259     banghart 3021: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3022: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3023: 	}
1.259     banghart 3024: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3025: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3026: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3027: 	        $dropMenu eq 'reset status')
                   3028: 	   {
1.524     raeburn  3029: 	    push(@version_parts,$new_part);
1.259     banghart 3030: 	}
1.41      ng       3031:     }
1.301     albertel 3032:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3033:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3034: 
1.344     albertel 3035:     if (%newrecord) {
                   3036:         if (@version_parts) {
1.364     banghart 3037:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3038:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3039: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3040: 	    foreach my $new_part (@version_parts) {
                   3041: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3042: 				$new_part,\%newrecord);
                   3043: 	    }
1.259     banghart 3044:         }
1.44      ng       3045: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3046: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3047: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3048: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3049:     }
1.269     raeburn  3050:     if ($aggregateflag) {
                   3051:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3052: 			      $cdom,$cnum);
1.269     raeburn  3053:     }
1.301     albertel 3054:     return ('',$pts,$wgt);
1.36      ng       3055: }
1.322     albertel 3056: 
1.380     albertel 3057: sub check_and_remove_from_queue {
                   3058:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3059:     my @ungraded_parts;
                   3060:     foreach my $part (@{$parts}) {
                   3061: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3062: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3063: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3064: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3065: 		) {
                   3066: 	    push(@ungraded_parts, $part);
                   3067: 	}
                   3068:     }
                   3069:     if ( !@ungraded_parts ) {
                   3070: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3071: 					       $cnum,$domain,$stuname);
                   3072:     }
                   3073: }
                   3074: 
1.337     banghart 3075: sub handback_files {
                   3076:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3077:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3078:     my $res_error;
                   3079:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3080:     if ($res_error) {
                   3081:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3082:         return;
                   3083:     }
1.654     raeburn  3084:     my @handedback;
                   3085:     my $file_msg;
1.375     albertel 3086:     my @part_response_id = &flatten_responseType($responseType);
                   3087:     foreach my $part_response_id (@part_response_id) {
                   3088:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3089: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3090:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3091:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3092:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3093:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3094:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3095:                     my ($directory,$answer_file) = 
1.654     raeburn  3096:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3097:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3098: 		        &file_name_version_ext($answer_file);
1.355     banghart 3099: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3100:                     my $getpropath = 1;
1.662     raeburn  3101:                     my ($dir_list,$listerror) = 
                   3102:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3103:                                                  $domain,$stuname,$getpropath);
                   3104: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.355     banghart 3105:                     # fix file name
                   3106:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3107:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3108:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3109:             	                                $save_file_name);
1.337     banghart 3110:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3111:                         $request->print('<br /><span class="LC_error">'.
                   3112:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3113:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3114:                                         '</span>');
1.356     banghart 3115:                     } else {
1.360     banghart 3116:                         # mark the file as read only
1.654     raeburn  3117:                         push(@handedback,$save_file_name);
1.367     albertel 3118: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3119: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3120: 			}
                   3121:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3122: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3123:                     }
1.654     raeburn  3124:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3125:                 }
                   3126:             }
                   3127:         }
1.654     raeburn  3128:     }
                   3129:     if (@handedback > 0) {
                   3130:         $request->print('<br />');
                   3131:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3132:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3133:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3134:         my ($subject,$message);
                   3135:         if (scalar(@handedback) == 1) {
                   3136:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3137:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3138:         } else {
                   3139:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3140:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3141:         }
                   3142:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3143:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3144:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3145:         my ($feedurl,$showsymb) =
                   3146:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3147:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3148:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3149:         my $msgstatus =
                   3150:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3151:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3152:                  $restitle);
                   3153:         if ($msgstatus) {
                   3154:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3155:         }
                   3156:     }
1.338     banghart 3157:     return;
1.337     banghart 3158: }
                   3159: 
1.418     albertel 3160: sub get_feedurl_and_symb {
                   3161:     my ($symb,$uname,$udom) = @_;
                   3162:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3163:     $url = &Apache::lonnet::clutter($url);
                   3164:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3165: 					$symb,$udom,$uname);
                   3166:     if ($encrypturl =~ /^yes$/i) {
                   3167: 	&Apache::lonenc::encrypted(\$url,1);
                   3168: 	&Apache::lonenc::encrypted(\$symb,1);
                   3169:     }
                   3170:     return ($url,$symb);
                   3171: }
                   3172: 
1.313     banghart 3173: sub get_submitted_files {
                   3174:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3175:     my @files;
                   3176:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3177:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3178:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3179:     	    push(@files,$file_url.$file);
                   3180:         }
                   3181:     }
                   3182:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3183:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3184:     }
                   3185:     return (\@files);
                   3186: }
1.322     albertel 3187: 
1.269     raeburn  3188: # ----------- Provides number of tries since last reset.
                   3189: sub get_num_tries {
                   3190:     my ($record,$last_reset,$part) = @_;
                   3191:     my $timestamp = '';
                   3192:     my $num_tries = 0;
                   3193:     if ($$record{'version'}) {
                   3194:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3195:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3196:                 $timestamp = $$record{$version.':timestamp'};
                   3197:                 if ($timestamp > $last_reset) {
                   3198:                     $num_tries ++;
                   3199:                 } else {
                   3200:                     last;
                   3201:                 }
                   3202:             }
                   3203:         }
                   3204:     }
                   3205:     return $num_tries;
                   3206: }
                   3207: 
                   3208: # ----------- Determine decrements required in aggregate totals 
                   3209: sub decrement_aggs {
                   3210:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3211:     my %decrement = (
                   3212:                         attempts => 0,
                   3213:                         users => 0,
                   3214:                         correct => 0
                   3215:                     );
                   3216:     $decrement{'attempts'} = $aggtries;
                   3217:     if ($solvedstatus =~ /^correct/) {
                   3218:         $decrement{'correct'} = 1;
                   3219:     }
                   3220:     if ($aggtries == $totaltries) {
                   3221:         $decrement{'users'} = 1;
                   3222:     }
1.524     raeburn  3223:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3224:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3225:     }
                   3226:     return;
                   3227: }
                   3228: 
                   3229: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3230: sub get_last_resets {
1.270     albertel 3231:     my ($symb,$courseid,$partids) =@_;
                   3232:     my %last_resets;
1.269     raeburn  3233:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3234:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3235:     my @keys;
                   3236:     foreach my $part (@{$partids}) {
                   3237: 	push(@keys,"$symb\0$part\0resettime");
                   3238:     }
                   3239:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3240: 				     $cdom,$cname);
                   3241:     foreach my $part (@{$partids}) {
                   3242: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3243:     }
1.270     albertel 3244:     return %last_resets;
1.269     raeburn  3245: }
                   3246: 
1.251     banghart 3247: # ----------- Handles creating versions for portfolio files as answers
                   3248: sub version_portfiles {
1.343     banghart 3249:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3250:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3251:     my @returned_keys;
1.255     banghart 3252:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3253:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3254:     foreach my $key (keys(%$record)) {
1.259     banghart 3255:         my $new_portfiles;
1.263     banghart 3256:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3257:             my @versioned_portfiles;
1.367     albertel 3258:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3259:             foreach my $file (@portfiles) {
1.306     banghart 3260:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3261:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3262: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3263: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3264:                 my $getpropath = 1;    
1.662     raeburn  3265:                 my ($dir_list,$listerror) = 
                   3266:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3267:                                              $stu_name,$getpropath);
                   3268:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3269:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3270:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3271:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3272:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3273:                         [$directory.$new_answer],
1.306     banghart 3274:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3275:                 }
1.252     banghart 3276:             }
1.343     banghart 3277:             $$record{$key} = join(',',@versioned_portfiles);
                   3278:             push(@returned_keys,$key);
1.251     banghart 3279:         }
                   3280:     } 
1.343     banghart 3281:     return (@returned_keys);   
1.305     banghart 3282: }
                   3283: 
1.307     banghart 3284: sub get_next_version {
1.341     banghart 3285:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3286:     my $version;
1.662     raeburn  3287:     if (ref($dir_list) eq 'ARRAY') {
                   3288:         foreach my $row (@{$dir_list}) {
                   3289:             my ($file) = split(/\&/,$row,2);
                   3290:             my ($file_name,$file_version,$file_ext) =
                   3291: 	        &file_name_version_ext($file);
                   3292:             if (($file_name eq $answer_name) && 
                   3293: 	        ($file_ext eq $answer_ext)) {
                   3294:                      # gets here if filename and extension match, 
                   3295:                      # regardless of version
1.307     banghart 3296:                 if ($file_version ne '') {
1.662     raeburn  3297:                     # a versioned file is found  so save it for later
                   3298:                     if ($file_version > $version) {
                   3299: 		        $version = $file_version;
                   3300: 	            }
                   3301:                 }
1.307     banghart 3302:             }
                   3303:         }
1.662     raeburn  3304:     }
1.307     banghart 3305:     $version ++;
                   3306:     return($version);
                   3307: }
                   3308: 
1.305     banghart 3309: sub version_selected_portfile {
1.306     banghart 3310:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3311:     my ($answer_name,$answer_ver,$answer_ext) =
                   3312:         &file_name_version_ext($file_name);
                   3313:     my $new_answer;
                   3314:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3315:     if($env{'form.copy'} eq '-1') {
                   3316:         $new_answer = 'problem getting file';
                   3317:     } else {
                   3318:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3319:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3320:                             $stu_name,$domain,'copy',
                   3321: 		        '/portfolio'.$directory.$new_answer);
                   3322:     }    
                   3323:     return ($new_answer);
1.251     banghart 3324: }
                   3325: 
1.304     albertel 3326: sub file_name_version_ext {
                   3327:     my ($file)=@_;
                   3328:     my @file_parts = split(/\./, $file);
                   3329:     my ($name,$version,$ext);
                   3330:     if (@file_parts > 1) {
                   3331: 	$ext=pop(@file_parts);
                   3332: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3333: 	    $version=pop(@file_parts);
                   3334: 	}
                   3335: 	$name=join('.',@file_parts);
                   3336:     } else {
                   3337: 	$name=join('.',@file_parts);
                   3338:     }
                   3339:     return($name,$version,$ext);
                   3340: }
                   3341: 
1.44      ng       3342: #--------------------------------------------------------------------------------------
                   3343: #
                   3344: #-------------------------- Next few routines handles grading by section or whole class
                   3345: #
                   3346: #--- Javascript to handle grading by section or whole class
1.42      ng       3347: sub viewgrades_js {
                   3348:     my ($request) = shift;
                   3349: 
1.539     riegler  3350:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3351:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3352:    function writePoint(partid,weight,point) {
1.125     ng       3353: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3354: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3355: 	if (point == "textval") {
1.125     ng       3356: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3357: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3358: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3359: 		var resetbox = false;
                   3360: 		for (var i=0; i<radioButton.length; i++) {
                   3361: 		    if (radioButton[i].checked) {
                   3362: 			textbox.value = i;
                   3363: 			resetbox = true;
                   3364: 		    }
                   3365: 		}
                   3366: 		if (!resetbox) {
                   3367: 		    textbox.value = "";
                   3368: 		}
                   3369: 		return;
                   3370: 	    }
1.109     matthew  3371: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3372: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3373: 				   ") greater than the weight for the part. Accept?");
                   3374: 		if (resp == false) {
                   3375: 		    textbox.value = "";
                   3376: 		    return;
                   3377: 		}
                   3378: 	    }
1.42      ng       3379: 	    for (var i=0; i<radioButton.length; i++) {
                   3380: 		radioButton[i].checked=false;
1.109     matthew  3381: 		if (parseFloat(point) == i) {
1.42      ng       3382: 		    radioButton[i].checked=true;
                   3383: 		}
                   3384: 	    }
1.41      ng       3385: 
1.42      ng       3386: 	} else {
1.125     ng       3387: 	    textbox.value = parseFloat(point);
1.42      ng       3388: 	}
1.41      ng       3389: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3390: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3391: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3392: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3393: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3394: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3395: 	    if (saveval != "correct") {
                   3396: 		scorename.value = point;
1.43      ng       3397: 		if (selname[0].selected != true) {
                   3398: 		    selname[0].selected = true;
                   3399: 		}
1.42      ng       3400: 	    }
                   3401: 	}
1.125     ng       3402: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3403:     }
                   3404: 
                   3405:     function writeRadText(partid,weight) {
1.125     ng       3406: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3407: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3408:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3409: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3410: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3411: 	    for (var i=0; i<radioButton.length; i++) {
                   3412: 		radioButton[i].checked=false;
                   3413: 
                   3414: 	    }
                   3415: 	    textbox.value = "";
                   3416: 
                   3417: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3418: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3419: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3420: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3421: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3422: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3423: 		if ((saveval != "correct") || override) {
1.42      ng       3424: 		    scorename.value = "";
1.125     ng       3425: 		    if (selval[1].selected) {
                   3426: 			selname[1].selected = true;
                   3427: 		    } else {
                   3428: 			selname[2].selected = true;
                   3429: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3430: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3431: 		    }
1.42      ng       3432: 		}
                   3433: 	    }
1.43      ng       3434: 	} else {
                   3435: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3436: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3437: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3438: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3439: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3440: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3441: 		if ((saveval != "correct") || override) {
1.125     ng       3442: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3443: 		    selname[0].selected = true;
                   3444: 		}
                   3445: 	    }
                   3446: 	}	    
1.42      ng       3447:     }
                   3448: 
                   3449:     function changeSelect(partid,user) {
1.125     ng       3450: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3451: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3452: 	var point  = textbox.value;
1.125     ng       3453: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3454: 
1.109     matthew  3455: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3456: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3457: 	    textbox.value = "";
                   3458: 	    return;
                   3459: 	}
1.109     matthew  3460: 	if (parseFloat(point) > parseFloat(weight)) {
                   3461: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3462: 			       ") greater than the weight of the part. Accept?");
                   3463: 	    if (resp == false) {
                   3464: 		textbox.value = "";
                   3465: 		return;
                   3466: 	    }
                   3467: 	}
1.42      ng       3468: 	selval[0].selected = true;
                   3469:     }
                   3470: 
                   3471:     function changeOneScore(partid,user) {
1.125     ng       3472: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3473: 	if (selval[1].selected || selval[2].selected) {
                   3474: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3475: 	    if (selval[2].selected) {
                   3476: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3477: 	    }
1.269     raeburn  3478:         }
1.42      ng       3479:     }
                   3480: 
                   3481:     function resetEntry(numpart) {
                   3482: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3483: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3484: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3485: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3486: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3487: 	    for (var i=0; i<radioButton.length; i++) {
                   3488: 		radioButton[i].checked=false;
                   3489: 
                   3490: 	    }
                   3491: 	    textbox.value = "";
                   3492: 	    selval[0].selected = true;
                   3493: 
                   3494: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3495: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3496: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3497: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3498: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3499: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3500: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3501: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3502: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3503: 		if (saveselval == "excused") {
1.43      ng       3504: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3505: 		} else {
1.43      ng       3506: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3507: 		}
                   3508: 	    }
1.41      ng       3509: 	}
1.42      ng       3510:     }
                   3511: 
1.41      ng       3512: VIEWJAVASCRIPT
1.42      ng       3513: }
                   3514: 
1.44      ng       3515: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3516: sub viewgrades {
1.608     www      3517:     my ($request,$symb) = @_;
1.42      ng       3518:     &viewgrades_js($request);
1.41      ng       3519: 
1.168     albertel 3520:     #need to make sure we have the correct data for later EXT calls, 
                   3521:     #thus invalidate the cache
                   3522:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3523:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3524:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3525:     &Apache::lonnet::clear_EXT_cache_status();
                   3526: 
1.398     albertel 3527:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3528: 
                   3529:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3530:     $result.=&jscriptNform($symb);
1.41      ng       3531: 
1.44      ng       3532:     #beginning of class grading form
1.442     banghart 3533:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3534:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3535: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3536: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3537: 	&build_section_inputs().
1.442     banghart 3538: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3539: 
1.560     raeburn  3540:     my ($common_header,$specific_header);
1.257     albertel 3541:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3542: 	$common_header = &mt('Assign Common Grade to Class');
                   3543:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3544:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3545:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3546: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3547:     } else {
1.560     raeburn  3548:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3549:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3550: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3551:     }
1.560     raeburn  3552:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3553:     #radio buttons/text box for assigning points for a section or class.
                   3554:     #handles different parts of a problem
1.582     raeburn  3555:     my $res_error;
                   3556:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3557:     if ($res_error) {
                   3558:         return &navmap_errormsg();
                   3559:     }
1.42      ng       3560:     my %weight = ();
                   3561:     my $ctsparts = 0;
1.45      ng       3562:     my %seen = ();
1.375     albertel 3563:     my @part_response_id = &flatten_responseType($responseType);
                   3564:     foreach my $part_response_id (@part_response_id) {
                   3565:     	my ($partid,$respid) = @{ $part_response_id };
                   3566: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3567: 	next if $seen{$partid};
                   3568: 	$seen{$partid}++;
1.375     albertel 3569: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3570: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3571: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3572: 
1.324     albertel 3573: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3574: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3575: 	my $ctr = 0;
1.42      ng       3576: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3577: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3578: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3579: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3580: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3581: 	    $ctr++;
                   3582: 	}
1.485     albertel 3583: 	$radio.='</tr></table>';
                   3584: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3585: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3586: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3587: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3588: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3589: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3590: 		$weight{$partid}.')"> '.
1.401     albertel 3591: 	    '<option selected="selected"> </option>'.
1.485     albertel 3592: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3593: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3594: 	    '</select></td>'.
                   3595:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3596: 	$line.='<input type="hidden" name="partid_'.
                   3597: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3598: 	$line.='<input type="hidden" name="weight_'.
                   3599: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3600: 
                   3601: 	$result.=
                   3602: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3603: 	    '<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 3604: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3605: 	$ctsparts++;
1.41      ng       3606:     }
1.474     albertel 3607:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3608: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3609:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3610: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3611: 
1.44      ng       3612:     #table listing all the students in a section/class
                   3613:     #header of table
1.560     raeburn  3614:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3615:               &Apache::loncommon::start_data_table().
                   3616: 	      &Apache::loncommon::start_data_table_header_row().
                   3617: 	      '<th>'.&mt('No.').'</th>'.
                   3618: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3619:     my $partserror;
                   3620:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3621:     if ($partserror) {
                   3622:         return &navmap_errormsg();
                   3623:     }
1.324     albertel 3624:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3625:     my @partids = ();
1.41      ng       3626:     foreach my $part (@parts) {
                   3627: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3628:         my $narrowtext = &mt('Tries');
                   3629: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3630: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3631: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3632:         push(@partids,$partid);
1.628     www      3633: #
                   3634: # FIXME: Looks like $display looks at English text
                   3635: #
1.324     albertel 3636: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3637: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3638: 	    $result.='<th>'.
                   3639: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3640: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3641: 	    next;
1.485     albertel 3642: 	    
1.207     albertel 3643: 	} else {
1.485     albertel 3644: 	    if ($display =~ /Problem Status/) {
                   3645: 		my $grade_status_mt = &mt('Grade Status');
                   3646: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3647: 	    }
                   3648: 	    my $part_mt = &mt('Part:');
                   3649: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3650: 	}
1.485     albertel 3651: 
1.474     albertel 3652: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3653:     }
1.474     albertel 3654:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3655: 
1.270     albertel 3656:     my %last_resets = 
                   3657: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3658: 
1.41      ng       3659:     #get info for each student
1.44      ng       3660:     #list all the students - with points and grade status
1.257     albertel 3661:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3662:     my $ctr = 0;
1.294     albertel 3663:     foreach (sort 
                   3664: 	     {
                   3665: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3666: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3667: 		 }
                   3668: 		 return $a cmp $b;
                   3669: 	     } (keys(%$fullname))) {
1.126     ng       3670: 	$ctr++;
1.324     albertel 3671: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3672: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3673:     }
1.474     albertel 3674:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3675:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3676:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3677: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3678:     if (scalar(%$fullname) eq 0) {
                   3679: 	my $colspan=3+scalar(@parts);
1.433     banghart 3680: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3681:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3682: 	$result='<span class="LC_warning">'.
1.485     albertel 3683: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3684: 	        $section_display, $stu_status).
1.433     banghart 3685: 	    '</span>';
1.96      albertel 3686:     }
1.41      ng       3687:     return $result;
                   3688: }
                   3689: 
1.44      ng       3690: #--- call by previous routine to display each student
1.41      ng       3691: sub viewstudentgrade {
1.324     albertel 3692:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3693:     my ($uname,$udom) = split(/:/,$student);
                   3694:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3695:     my %aggregates = (); 
1.474     albertel 3696:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3697: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3698: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3699: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3700: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3701: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3702:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3703:     foreach my $apart (@$parts) {
                   3704: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3705: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3706:         $result.='<td align="center">';
1.269     raeburn  3707:         my ($aggtries,$totaltries);
                   3708:         unless (exists($aggregates{$part})) {
1.270     albertel 3709: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3710: 
                   3711: 	    $aggtries = $totaltries;
1.269     raeburn  3712:             if ($$last_resets{$part}) {  
1.270     albertel 3713:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3714: 					   $part);
                   3715:             }
1.269     raeburn  3716:             $result.='<input type="hidden" name="'.
                   3717:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3718:             $result.='<input type="hidden" name="'.
                   3719:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3720:             $aggregates{$part} = 1;
                   3721:         }
1.41      ng       3722: 	if ($type eq 'awarded') {
1.320     albertel 3723: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3724: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3725: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3726: 	    $result.='<input type="text" name="'.
1.89      albertel 3727: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3728:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3729: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3730: 	} elsif ($type eq 'solved') {
                   3731: 	    my ($status,$foo)=split(/_/,$score,2);
                   3732: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3733: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3734: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3735: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3736: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3737:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3738: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3739: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3740: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3741: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3742: 	} else {
                   3743: 	    $result.='<input type="hidden" name="'.
                   3744: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3745: 		    "\n";
1.233     albertel 3746: 	    $result.='<input type="text" name="'.
1.122     ng       3747: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3748: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3749: 	}
                   3750:     }
1.474     albertel 3751:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3752:     return $result;
1.38      ng       3753: }
                   3754: 
1.44      ng       3755: #--- change scores for all the students in a section/class
                   3756: #    record does not get update if unchanged
1.38      ng       3757: sub editgrades {
1.608     www      3758:     my ($request,$symb) = @_;
1.41      ng       3759: 
1.433     banghart 3760:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3761:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3762:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3763: 
1.477     albertel 3764:     my $result= &Apache::loncommon::start_data_table().
                   3765: 	&Apache::loncommon::start_data_table_header_row().
                   3766: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3767: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3768:     my %scoreptr = (
                   3769: 		    'correct'  =>'correct_by_override',
                   3770: 		    'incorrect'=>'incorrect_by_override',
                   3771: 		    'excused'  =>'excused',
                   3772: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3773:                     'credited' =>'credit_attempted',
1.43      ng       3774: 		    'nothing'  => '',
                   3775: 		    );
1.257     albertel 3776:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3777: 
1.44      ng       3778:     my (@partid);
                   3779:     my %weight = ();
1.54      albertel 3780:     my %columns = ();
1.44      ng       3781:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3782: 
1.582     raeburn  3783:     my $partserror;
                   3784:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3785:     if ($partserror) {
                   3786:         return &navmap_errormsg();
                   3787:     }
1.54      albertel 3788:     my $header;
1.257     albertel 3789:     while ($ctr < $env{'form.totalparts'}) {
                   3790: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3791: 	push(@partid,$partid);
1.257     albertel 3792: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3793: 	$ctr++;
1.54      albertel 3794:     }
1.324     albertel 3795:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3796:     foreach my $partid (@partid) {
1.478     albertel 3797: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3798: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3799: 	$columns{$partid}=2;
                   3800: 	foreach my $stores (@parts) {
                   3801: 	    my ($part,$type) = &split_part_type($stores);
                   3802: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3803: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3804: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3805: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3806:             my $narrowtext = &mt('Tries');
                   3807: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3808: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3809: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3810: 	    $columns{$partid}+=2;
                   3811: 	}
                   3812:     }
                   3813:     foreach my $partid (@partid) {
1.324     albertel 3814: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3815: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3816: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3817: 	    '</th>';
1.54      albertel 3818: 
1.44      ng       3819:     }
1.477     albertel 3820:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3821: 	&Apache::loncommon::start_data_table_header_row().
                   3822: 	$header.
                   3823: 	&Apache::loncommon::end_data_table_header_row();
                   3824:     my @noupdate;
1.126     ng       3825:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3826:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3827: 	my $line;
1.257     albertel 3828: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3829: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3830: 	my %newrecord;
                   3831: 	my $updateflag = 0;
1.281     albertel 3832: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3833: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3834: 	if (!&canmodify($usec)) {
1.126     ng       3835: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3836: 	    push(@noupdate,
1.478     albertel 3837: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3838: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3839: 	    next;
                   3840: 	}
1.269     raeburn  3841:         my %aggregate = ();
                   3842:         my $aggregateflag = 0;
1.281     albertel 3843: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3844: 	foreach (@partid) {
1.257     albertel 3845: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3846: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3847: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3848: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3849: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3850: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3851: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3852: 	    my $score;
                   3853: 	    if ($partial eq '') {
1.257     albertel 3854: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3855: 	    } elsif ($partial > 0) {
                   3856: 		$score = 'correct_by_override';
                   3857: 	    } elsif ($partial == 0) {
                   3858: 		$score = 'incorrect_by_override';
                   3859: 	    }
1.257     albertel 3860: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3861: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3862: 
1.292     albertel 3863: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3864: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3865: 	    if ($dropMenu eq 'reset status' &&
                   3866: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3867: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3868: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3869: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3870: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3871: 		$updateflag = 1;
1.269     raeburn  3872:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3873:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3874:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3875:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3876:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3877:                     $aggregateflag = 1;
                   3878:                 }
1.139     albertel 3879: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3880: 		$updateflag = 1;
                   3881: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3882: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3883: 		$rec_update++;
1.125     ng       3884: 	    }
                   3885: 
1.93      albertel 3886: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3887: 		'<td align="center">'.$awarded.
                   3888: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3889: 
1.54      albertel 3890: 
                   3891: 	    my $partid=$_;
                   3892: 	    foreach my $stores (@parts) {
                   3893: 		my ($part,$type) = &split_part_type($stores);
                   3894: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3895: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3896: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3897: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3898: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3899: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3900: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3901: 		    $updateflag=1;
                   3902: 		}
1.93      albertel 3903: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3904: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3905: 	    }
1.44      ng       3906: 	}
1.477     albertel 3907: 	$line.="\n";
1.301     albertel 3908: 
                   3909: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3910: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3911: 
1.44      ng       3912: 	if ($updateflag) {
                   3913: 	    $count++;
1.257     albertel 3914: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3915: 				    $udom,$uname);
1.301     albertel 3916: 
                   3917: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3918: 					      $cnum,$udom,$uname)) {
                   3919: 		# need to figure out if should be in queue.
                   3920: 		my %record =  
                   3921: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3922: 					     $udom,$uname);
                   3923: 		my $all_graded = 1;
                   3924: 		my $none_graded = 1;
                   3925: 		foreach my $part (@parts) {
                   3926: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3927: 			$all_graded = 0;
                   3928: 		    } else {
                   3929: 			$none_graded = 0;
                   3930: 		    }
                   3931: 		}
                   3932: 
                   3933: 		if ($all_graded || $none_graded) {
                   3934: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3935: 							   $symb,$cdom,$cnum,
                   3936: 							   $udom,$uname);
                   3937: 		}
                   3938: 	    }
                   3939: 
1.477     albertel 3940: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3941: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3942: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3943: 	    $updateCtr++;
1.93      albertel 3944: 	} else {
1.477     albertel 3945: 	    push(@noupdate,
                   3946: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3947: 	    $noupdateCtr++;
1.44      ng       3948: 	}
1.269     raeburn  3949:         if ($aggregateflag) {
                   3950:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3951: 				  $cdom,$cnum);
1.269     raeburn  3952:         }
1.93      albertel 3953:     }
1.477     albertel 3954:     if (@noupdate) {
1.126     ng       3955: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3956: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3957: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3958: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3959: 	    &mt('No Changes Occurred For the Students Below').
                   3960: 	    '</td>'.
1.477     albertel 3961: 	    &Apache::loncommon::end_data_table_row();
                   3962: 	foreach my $line (@noupdate) {
                   3963: 	    $result.=
                   3964: 		&Apache::loncommon::start_data_table_row().
                   3965: 		$line.
                   3966: 		&Apache::loncommon::end_data_table_row();
                   3967: 	}
1.44      ng       3968:     }
1.614     www      3969:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3970:     my $msg = '<p><b>'.
                   3971: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3972: 	    $rec_update,$count).'</b><br />'.
                   3973: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3974: 	'</b></p>';
1.44      ng       3975:     return $title.$msg.$result;
1.5       albertel 3976: }
1.54      albertel 3977: 
                   3978: sub split_part_type {
                   3979:     my ($partstr) = @_;
                   3980:     my ($temp,@allparts)=split(/_/,$partstr);
                   3981:     my $type=pop(@allparts);
1.439     albertel 3982:     my $part=join('_',@allparts);
1.54      albertel 3983:     return ($part,$type);
                   3984: }
                   3985: 
1.44      ng       3986: #------------- end of section for handling grading by section/class ---------
                   3987: #
                   3988: #----------------------------------------------------------------------------
                   3989: 
1.5       albertel 3990: 
1.44      ng       3991: #----------------------------------------------------------------------------
                   3992: #
                   3993: #-------------------------- Next few routines handles grading by csv upload
                   3994: #
                   3995: #--- Javascript to handle csv upload
1.27      albertel 3996: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3997:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3998:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3999:   return(<<ENDPICK);
                   4000:   function verify(vf) {
                   4001:     var foundsomething=0;
                   4002:     var founduname=0;
1.243     albertel 4003:     var foundID=0;
1.27      albertel 4004:     for (i=0;i<=vf.nfields.value;i++) {
                   4005:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4006:       if (i==0 && tw!=0) { foundID=1; }
                   4007:       if (i==1 && tw!=0) { founduname=1; }
                   4008:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4009:     }
1.246     albertel 4010:     if (founduname==0 && foundID==0) {
                   4011: 	alert('$error1');
                   4012: 	return;
1.27      albertel 4013:     }
                   4014:     if (foundsomething==0) {
1.246     albertel 4015: 	alert('$error2');
                   4016: 	return;
1.27      albertel 4017:     }
                   4018:     vf.submit();
                   4019:   }
                   4020:   function flip(vf,tf) {
                   4021:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4022:     var i;
                   4023:     for (i=0;i<=vf.nfields.value;i++) {
                   4024:       //can not pick the same destination field for both name and domain
                   4025:       if (((i ==0)||(i ==1)) && 
                   4026:           ((tf==0)||(tf==1)) && 
                   4027:           (i!=tf) &&
                   4028:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4029:         eval('vf.f'+i+'.selectedIndex=0;')
                   4030:       }
                   4031:     }
                   4032:   }
                   4033: ENDPICK
                   4034: }
                   4035: 
                   4036: sub csvupload_javascript_forward_associate {
1.573     bisitz   4037:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4038:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4039:   return(<<ENDPICK);
                   4040:   function verify(vf) {
                   4041:     var foundsomething=0;
                   4042:     var founduname=0;
1.243     albertel 4043:     var foundID=0;
1.27      albertel 4044:     for (i=0;i<=vf.nfields.value;i++) {
                   4045:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4046:       if (tw==1) { foundID=1; }
                   4047:       if (tw==2) { founduname=1; }
                   4048:       if (tw>3) { foundsomething=1; }
1.27      albertel 4049:     }
1.246     albertel 4050:     if (founduname==0 && foundID==0) {
                   4051: 	alert('$error1');
                   4052: 	return;
1.27      albertel 4053:     }
                   4054:     if (foundsomething==0) {
1.246     albertel 4055: 	alert('$error2');
                   4056: 	return;
1.27      albertel 4057:     }
                   4058:     vf.submit();
                   4059:   }
                   4060:   function flip(vf,tf) {
                   4061:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4062:     var i;
                   4063:     //can not pick the same destination field twice
                   4064:     for (i=0;i<=vf.nfields.value;i++) {
                   4065:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4066:         eval('vf.f'+i+'.selectedIndex=0;')
                   4067:       }
                   4068:     }
                   4069:   }
                   4070: ENDPICK
                   4071: }
                   4072: 
1.26      albertel 4073: sub csvuploadmap_header {
1.324     albertel 4074:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4075:     my $javascript;
1.257     albertel 4076:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4077: 	$javascript=&csvupload_javascript_reverse_associate();
                   4078:     } else {
                   4079: 	$javascript=&csvupload_javascript_forward_associate();
                   4080:     }
1.45      ng       4081: 
1.418     albertel 4082:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4083:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4084:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4085:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4086:     my $reverse=&mt("Reverse Association");
1.41      ng       4087:     $request->print(<<ENDPICK);
1.632     www      4088: <br />
                   4089: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4090: <input type="hidden" name="associate"  value="" />
                   4091: <input type="hidden" name="phase"      value="three" />
                   4092: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4093: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4094: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4095: <input type="hidden" name="upfile_associate" 
1.257     albertel 4096:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4097: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4098: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4099: <hr />
                   4100: ENDPICK
1.597     wenzelju 4101:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4102:     return '';
1.26      albertel 4103: 
                   4104: }
                   4105: 
                   4106: sub csvupload_fields {
1.582     raeburn  4107:     my ($symb,$errorref) = @_;
                   4108:     my (@parts) = &getpartlist($symb,$errorref);
                   4109:     if (ref($errorref)) {
                   4110:         if ($$errorref) {
                   4111:             return;
                   4112:         }
                   4113:     }
                   4114: 
1.556     weissno  4115:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4116: 		['username','Student Username'],
                   4117: 		['domain','Student Domain']);
1.324     albertel 4118:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4119:     foreach my $part (sort(@parts)) {
                   4120: 	my @datum;
                   4121: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4122: 	my $name=$part;
                   4123: 	if  (!$display) { $display = $name; }
                   4124: 	@datum=($name,$display);
1.244     albertel 4125: 	if ($name=~/^stores_(.*)_awarded/) {
                   4126: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4127: 	}
1.41      ng       4128: 	push(@fields,\@datum);
                   4129:     }
                   4130:     return (@fields);
1.26      albertel 4131: }
                   4132: 
                   4133: sub csvuploadmap_footer {
1.41      ng       4134:     my ($request,$i,$keyfields) =@_;
                   4135:     $request->print(<<ENDPICK);
1.26      albertel 4136: </table>
                   4137: <input type="hidden" name="nfields" value="$i" />
                   4138: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4139: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4140: </form>
                   4141: ENDPICK
                   4142: }
                   4143: 
1.283     albertel 4144: sub checkforfile_js {
1.638     www      4145:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4146:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4147:     function checkUpload(formname) {
                   4148: 	if (formname.upfile.value == "") {
1.539     riegler  4149: 	    alert("$alertmsg");
1.86      ng       4150: 	    return false;
                   4151: 	}
                   4152: 	formname.submit();
                   4153:     }
                   4154: CSVFORMJS
1.283     albertel 4155:     return $result;
                   4156: }
                   4157: 
                   4158: sub upcsvScores_form {
1.608     www      4159:     my ($request,$symb) = @_;
1.283     albertel 4160:     if (!$symb) {return '';}
                   4161:     my $result=&checkforfile_js();
1.632     www      4162:     $result.=&Apache::loncommon::start_data_table().
                   4163:              &Apache::loncommon::start_data_table_header_row().
                   4164:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4165:              &Apache::loncommon::end_data_table_header_row().
                   4166:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4167:     my $upload=&mt("Upload Scores");
1.86      ng       4168:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4169:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4170:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4171:     $result.=<<ENDUPFORM;
1.106     albertel 4172: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4173: <input type="hidden" name="symb" value="$symb" />
                   4174: <input type="hidden" name="command" value="csvuploadmap" />
                   4175: $upfile_select
1.589     bisitz   4176: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4177: </form>
                   4178: ENDUPFORM
1.370     www      4179:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4180:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4181:              '</td>'.
                   4182:             &Apache::loncommon::end_data_table_row().
                   4183:             &Apache::loncommon::end_data_table();
1.86      ng       4184:     return $result;
                   4185: }
                   4186: 
                   4187: 
1.26      albertel 4188: sub csvuploadmap {
1.608     www      4189:     my ($request,$symb)= @_;
1.41      ng       4190:     if (!$symb) {return '';}
1.72      ng       4191: 
1.41      ng       4192:     my $datatoken;
1.257     albertel 4193:     if (!$env{'form.datatoken'}) {
1.41      ng       4194: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4195:     } else {
1.257     albertel 4196: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4197: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4198:     }
1.41      ng       4199:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4200:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4201:     my ($i,$keyfields);
                   4202:     if (@records) {
1.582     raeburn  4203:         my $fieldserror;
                   4204: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4205:         if ($fieldserror) {
                   4206:             $request->print(&navmap_errormsg());
                   4207:             return;
                   4208:         }
1.257     albertel 4209: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4210: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4211: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4212: 							  \@fields);
                   4213: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4214: 	    chop($keyfields);
                   4215: 	} else {
                   4216: 	    unshift(@fields,['none','']);
                   4217: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4218: 							    \@fields);
1.311     banghart 4219:             foreach my $rec (@records) {
                   4220:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4221:                 if (%temp) {
                   4222:                     $keyfields=join(',',sort(keys(%temp)));
                   4223:                     last;
                   4224:                 }
                   4225:             }
1.41      ng       4226: 	}
                   4227:     }
                   4228:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4229: 
1.41      ng       4230:     return '';
1.27      albertel 4231: }
                   4232: 
1.246     albertel 4233: sub csvuploadoptions {
1.608     www      4234:     my ($request,$symb)= @_;
1.632     www      4235:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4236:     $request->print(<<ENDPICK);
                   4237: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4238: <input type="hidden" name="command"    value="csvuploadassign" />
                   4239: <p>
                   4240: <label>
                   4241:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4242:    $overwrite
1.246     albertel 4243: </label>
                   4244: </p>
                   4245: ENDPICK
                   4246:     my %fields=&get_fields();
                   4247:     if (!defined($fields{'domain'})) {
1.257     albertel 4248: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4249: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4250:     }
1.257     albertel 4251:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4252: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4253: 	my $cleankey=$1;
                   4254: 	if ($cleankey eq 'command') { next; }
                   4255: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4256: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4257:     }
                   4258:     # FIXME do a check for any duplicated user ids...
                   4259:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4260:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4261: <hr /></form>'."\n");
1.246     albertel 4262:     return '';
                   4263: }
                   4264: 
                   4265: sub get_fields {
                   4266:     my %fields;
1.257     albertel 4267:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4268:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4269: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4270: 	    if ($env{'form.f'.$i} ne 'none') {
                   4271: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4272: 	    }
                   4273: 	} else {
1.257     albertel 4274: 	    if ($env{'form.f'.$i} ne 'none') {
                   4275: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4276: 	    }
                   4277: 	}
1.27      albertel 4278:     }
1.246     albertel 4279:     return %fields;
                   4280: }
                   4281: 
                   4282: sub csvuploadassign {
1.608     www      4283:     my ($request,$symb)= @_;
1.246     albertel 4284:     if (!$symb) {return '';}
1.345     bowersj2 4285:     my $error_msg = '';
1.246     albertel 4286:     &Apache::loncommon::load_tmp_file($request);
                   4287:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4288:     my %fields=&get_fields();
1.257     albertel 4289:     my $courseid=$env{'request.course.id'};
1.97      albertel 4290:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4291:     my @notallowed;
1.41      ng       4292:     my @skipped;
1.657     raeburn  4293:     my @warnings;
1.41      ng       4294:     my $countdone=0;
                   4295:     foreach my $grade (@gradedata) {
                   4296: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4297: 	my $domain;
                   4298: 	if ($entries{$fields{'domain'}}) {
                   4299: 	    $domain=$entries{$fields{'domain'}};
                   4300: 	} else {
1.257     albertel 4301: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4302: 	}
1.243     albertel 4303: 	$domain=~s/\s//g;
1.41      ng       4304: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4305: 	$username=~s/\s//g;
1.243     albertel 4306: 	if (!$username) {
                   4307: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4308: 	    $id=~s/\s//g;
1.243     albertel 4309: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4310: 	    $username=$ids{$id};
                   4311: 	}
1.41      ng       4312: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4313: 	    my $id=$entries{$fields{'ID'}};
                   4314: 	    $id=~s/\s//g;
                   4315: 	    if ($id) {
                   4316: 		push(@skipped,"$id:$domain");
                   4317: 	    } else {
                   4318: 		push(@skipped,"$username:$domain");
                   4319: 	    }
1.41      ng       4320: 	    next;
                   4321: 	}
1.108     albertel 4322: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4323: 	if (!&canmodify($usec)) {
                   4324: 	    push(@notallowed,"$username:$domain");
                   4325: 	    next;
                   4326: 	}
1.244     albertel 4327: 	my %points;
1.41      ng       4328: 	my %grades;
                   4329: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4330: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4331: 		$dest eq 'domain') { next; }
                   4332: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4333: 	    if ($dest=~/stores_(.*)_points/) {
                   4334: 		my $part=$1;
                   4335: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4336: 					      $symb,$domain,$username);
1.345     bowersj2 4337:                 if ($wgt) {
                   4338:                     $entries{$fields{$dest}}=~s/\s//g;
                   4339:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4340:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4341:                                           : 'correct_by_override';
1.638     www      4342:                     if ($pcr>1) {
1.657     raeburn  4343:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4344:                     }
1.345     bowersj2 4345:                     $grades{"resource.$part.awarded"}=$pcr;
                   4346:                     $grades{"resource.$part.solved"}=$award;
                   4347:                     $points{$part}=1;
                   4348:                 } else {
                   4349:                     $error_msg = "<br />" .
                   4350:                         &mt("Some point values were assigned"
                   4351:                             ." for problems with a weight "
                   4352:                             ."of zero. These values were "
                   4353:                             ."ignored.");
                   4354:                 }
1.244     albertel 4355: 	    } else {
                   4356: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4357: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4358: 		my $store_key=$dest;
                   4359: 		$store_key=~s/^stores/resource/;
                   4360: 		$store_key=~s/_/\./g;
                   4361: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4362: 	    }
1.41      ng       4363: 	}
1.508     www      4364: 	if (! %grades) { 
                   4365:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4366:         } else {
                   4367: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4368: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4369: 					   $env{'request.course.id'},
                   4370: 					   $domain,$username);
1.508     www      4371: 	   if ($result eq 'ok') {
1.627     www      4372: # Successfully stored
1.508     www      4373: 	      $request->print('.');
1.627     www      4374: # Remove from grading queue
                   4375:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4376:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4377:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4378:                                              $domain,$username);
                   4379:               $countdone++;
                   4380:            } else {
1.508     www      4381: 	      $request->print("<p><span class=\"LC_error\">".
                   4382:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4383:                                   "$username:$domain",$result)."</span></p>");
                   4384: 	   }
                   4385: 	   $request->rflush();
                   4386:         }
1.41      ng       4387:     }
1.570     www      4388:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4389:     if (@warnings) {
                   4390:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4391:         $request->print(join(', ',@warnings));
                   4392:     }
1.41      ng       4393:     if (@skipped) {
1.571     www      4394: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4395:         $request->print(join(', ',@skipped));
1.106     albertel 4396:     }
                   4397:     if (@notallowed) {
1.571     www      4398: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4399: 	$request->print(join(', ',@notallowed));
1.41      ng       4400:     }
1.106     albertel 4401:     $request->print("<br />\n");
1.345     bowersj2 4402:     return $error_msg;
1.26      albertel 4403: }
1.44      ng       4404: #------------- end of section for handling csv file upload ---------
                   4405: #
                   4406: #-------------------------------------------------------------------
                   4407: #
1.122     ng       4408: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4409: #
                   4410: #--- Select a page/sequence and a student to grade
1.68      ng       4411: sub pickStudentPage {
1.608     www      4412:     my ($request,$symb) = @_;
1.68      ng       4413: 
1.539     riegler  4414:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4415:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4416: 
                   4417: function checkPickOne(formname) {
1.76      ng       4418:     if (radioSelection(formname.student) == null) {
1.539     riegler  4419: 	alert("$alertmsg");
1.68      ng       4420: 	return;
                   4421:     }
1.125     ng       4422:     ptr = pullDownSelection(formname.selectpage);
                   4423:     formname.page.value = formname["page"+ptr].value;
                   4424:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4425:     formname.submit();
                   4426: }
                   4427: 
                   4428: LISTJAVASCRIPT
1.118     ng       4429:     &commonJSfunctions($request);
1.608     www      4430: 
1.257     albertel 4431:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4432:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4433:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4434: 
1.398     albertel 4435:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4436: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4437: 
1.80      ng       4438:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4439:     my $map_error;
                   4440:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4441:     if ($map_error) {
                   4442:         $request->print(&navmap_errormsg());
                   4443:         return; 
                   4444:     }
1.137     albertel 4445:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4446: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4447: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4448:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4449:     my $ctr=0;
1.68      ng       4450:     foreach (@$titles) {
                   4451: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4452: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4453: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4454: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4455: 	$ctr++;
1.68      ng       4456:     }
1.485     albertel 4457:     $select.= '</select>';
1.539     riegler  4458:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4459: 
1.70      ng       4460:     $ctr=0;
                   4461:     foreach (@$titles) {
                   4462: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4463: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4464: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4465: 	$ctr++;
                   4466:     }
1.72      ng       4467:     $result.='<input type="hidden" name="page" />'."\n".
                   4468: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4469: 
1.485     albertel 4470:     my $options =
                   4471: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4472: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4473:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4474: 
                   4475:     $options =
                   4476: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4477: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4478: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4479:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4480:     
                   4481:     $result.=&build_section_inputs();
1.442     banghart 4482:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4483:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4484: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4485: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4486: 
1.539     riegler  4487:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4488: 
1.80      ng       4489:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4490:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4491: 
1.68      ng       4492:     $request->print($result);
                   4493: 
1.485     albertel 4494:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4495: 	&Apache::loncommon::start_data_table().
                   4496: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4497: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4498: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4499: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4500: 	'<th>'.&nameUserString('header').'</th>'.
                   4501: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4502:  
1.76      ng       4503:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4504:     my $ptr = 1;
1.294     albertel 4505:     foreach my $student (sort 
                   4506: 			 {
                   4507: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4508: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4509: 			     }
                   4510: 			     return $a cmp $b;
                   4511: 			 } (keys(%$fullname))) {
1.68      ng       4512: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4513: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4514:                                   : '</td>');
1.126     ng       4515: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4516: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4517: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4518: 	$studentTable.=
                   4519: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4520:                          : '');
1.68      ng       4521: 	$ptr++;
                   4522:     }
1.484     albertel 4523:     if ($ptr%2 == 0) {
                   4524: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4525: 	    &Apache::loncommon::end_data_table_row();
                   4526:     }
                   4527:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4528:     $studentTable.='<input type="button" '.
1.589     bisitz   4529:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4530: 
                   4531:     $request->print($studentTable);
                   4532: 
                   4533:     return '';
                   4534: }
                   4535: 
                   4536: sub getSymbMap {
1.582     raeburn  4537:     my ($map_error) = @_;
1.132     bowersj2 4538:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4539:     unless (ref($navmap)) {
                   4540:         if (ref($map_error)) {
                   4541:             $$map_error = 'navmap';
                   4542:         }
                   4543:         return;
                   4544:     }
1.68      ng       4545:     my %symbx = ();
                   4546:     my @titles = ();
1.117     bowersj2 4547:     my $minder = 0;
                   4548: 
                   4549:     # Gather every sequence that has problems.
1.240     albertel 4550:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4551: 					       1,0,1);
1.117     bowersj2 4552:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4553: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4554: 	    my $title = $minder.'.'.
                   4555: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4556: 	    push(@titles, $title); # minder in case two titles are identical
                   4557: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4558: 	    $minder++;
1.241     albertel 4559: 	}
1.68      ng       4560:     }
                   4561:     return \@titles,\%symbx;
                   4562: }
                   4563: 
1.72      ng       4564: #
                   4565: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4566: sub displayPage {
1.608     www      4567:     my ($request,$symb) = @_;
1.257     albertel 4568:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4569:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4570:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4571:     my $pageTitle = $env{'form.page'};
1.103     albertel 4572:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4573:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4574:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4575: 
                   4576:     #need to make sure we have the correct data for later EXT calls, 
                   4577:     #thus invalidate the cache
                   4578:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4579:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4580:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4581:     &Apache::lonnet::clear_EXT_cache_status();
                   4582: 
1.103     albertel 4583:     if (!&canview($usec)) {
1.485     albertel 4584: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4585: 	return;
                   4586:     }
1.398     albertel 4587:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4588:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4589: 	'</h3>'."\n";
1.500     albertel 4590:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4591:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4592: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4593:     } else {
                   4594: 	delete($env{'form.CODE'});
                   4595:     }
1.71      ng       4596:     &sub_page_js($request);
                   4597:     $request->print($result);
                   4598: 
1.132     bowersj2 4599:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4600:     unless (ref($navmap)) {
                   4601:         $request->print(&navmap_errormsg());
                   4602:         return;
                   4603:     }
1.257     albertel 4604:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4605:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4606:     if (!$map) {
1.485     albertel 4607: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4608: 	return; 
                   4609:     }
1.68      ng       4610:     my $iterator = $navmap->getIterator($map->map_start(),
                   4611: 					$map->map_finish());
                   4612: 
1.71      ng       4613:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4614: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4615: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4616: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4617: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4618: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4619: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4620: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4621: 
1.382     albertel 4622:     if (defined($env{'form.CODE'})) {
                   4623: 	$studentTable.=
                   4624: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4625:     }
1.381     albertel 4626:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4627: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4628: 
1.594     bisitz   4629:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4630:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4631:         '</span>'."\n".
1.484     albertel 4632: 	&Apache::loncommon::start_data_table().
                   4633: 	&Apache::loncommon::start_data_table_header_row().
                   4634: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4635: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4636: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4637: 
1.329     albertel 4638:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4639:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4640:     $iterator->next(); # skip the first BEGIN_MAP
                   4641:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4642:     while ($depth > 0) {
1.68      ng       4643:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4644:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4645: 
1.385     albertel 4646:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4647: 	    my $parts = $curRes->parts();
1.68      ng       4648:             my $title = $curRes->compTitle();
1.71      ng       4649: 	    my $symbx = $curRes->symb();
1.484     albertel 4650: 	    $studentTable.=
                   4651: 		&Apache::loncommon::start_data_table_row().
                   4652: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4653: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4654: 		                        : '<br />('.&mt('[_1]parts)',
                   4655: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4656: 		 ).
                   4657: 		 '</td>';
1.71      ng       4658: 	    $studentTable.='<td valign="top">';
1.382     albertel 4659: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4660: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4661: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4662: 					     undef,'both',\%form);
1.71      ng       4663: 	    } else {
1.382     albertel 4664: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4665: 		$companswer =~ s|<form(.*?)>||g;
                   4666: 		$companswer =~ s|</form>||g;
1.71      ng       4667: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4668: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4669: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4670: #		}
1.116     ng       4671: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4672: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4673: 	    }
                   4674: 
1.257     albertel 4675: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4676: 
1.257     albertel 4677: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4678: 		if ($record{'version'} eq '') {
1.485     albertel 4679: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4680: 		} else {
1.116     ng       4681: 		    my %responseType = ();
                   4682: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4683: 			my @responseIds =$curRes->responseIds($partid);
                   4684: 			my @responseType =$curRes->responseType($partid);
                   4685: 			my %responseIds;
                   4686: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4687: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4688: 			}
                   4689: 			$responseType{$partid} = \%responseIds;
1.116     ng       4690: 		    }
1.148     albertel 4691: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4692: 
1.71      ng       4693: 		}
1.257     albertel 4694: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4695: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4696: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4697: 									$env{'request.course.id'},
1.71      ng       4698: 									'','.submission');
                   4699:  
                   4700: 	    }
1.103     albertel 4701: 	    if (&canmodify($usec)) {
1.585     bisitz   4702:             $studentTable.=&gradeBox_start();
1.103     albertel 4703: 		foreach my $partid (@{$parts}) {
                   4704: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4705: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4706: 		    $question++;
                   4707: 		}
1.585     bisitz   4708:             $studentTable.=&gradeBox_end();
1.196     albertel 4709: 		$prob++;
1.71      ng       4710: 	    }
                   4711: 	    $studentTable.='</td></tr>';
1.68      ng       4712: 
1.103     albertel 4713: 	}
1.68      ng       4714:         $curRes = $iterator->next();
                   4715:     }
                   4716: 
1.589     bisitz   4717:     $studentTable.=
                   4718:         '</table>'."\n".
                   4719:         '<input type="button" value="'.&mt('Save').'" '.
                   4720:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4721:         '</form>'."\n";
1.71      ng       4722:     $request->print($studentTable);
                   4723: 
                   4724:     return '';
1.119     ng       4725: }
                   4726: 
                   4727: sub displaySubByDates {
1.148     albertel 4728:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4729:     my $isCODE=0;
1.335     albertel 4730:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4731:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4732:     my $studentTable=&Apache::loncommon::start_data_table().
                   4733: 	&Apache::loncommon::start_data_table_header_row().
                   4734: 	'<th>'.&mt('Date/Time').'</th>'.
                   4735: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4736:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4737: 	'<th>'.&mt('Submission').'</th>'.
                   4738: 	'<th>'.&mt('Status').'</th>'.
                   4739: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4740:     my ($version);
                   4741:     my %mark;
1.148     albertel 4742:     my %orders;
1.119     ng       4743:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4744:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4745: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4746:     }
1.335     albertel 4747: 
                   4748:     my $interaction;
1.525     raeburn  4749:     my $no_increment = 1;
1.640     raeburn  4750:     my %lastrndseed;
1.119     ng       4751:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4752: 	my $timestamp = 
                   4753: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4754: 	if (exists($$record{$version.':resource.0.version'})) {
                   4755: 	    $interaction = $$record{$version.':resource.0.version'};
                   4756: 	}
1.671     raeburn  4757:         if ($isTask && $env{'form.previousversion'}) {
                   4758:             next unless ($interaction == $env{'form.previousversion'});
                   4759:         }
1.335     albertel 4760: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4761: 		             : "$version:resource");
1.467     albertel 4762: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4763: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4764: 	if ($isCODE) {
                   4765: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4766: 	}
1.671     raeburn  4767:         if ($isTask) {
                   4768:             $studentTable.='<td>'.$interaction.'</td>';
                   4769:         }
1.119     ng       4770: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4771: 	my @displaySub = ();
                   4772: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4773:             my ($hidden,$type);
                   4774:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4775:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4776:                 $hidden = 1;
                   4777:             }
1.335     albertel 4778: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4779: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4780: 	    
1.122     ng       4781: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4782: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4783: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4784: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4785: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4786:                     
1.335     albertel 4787: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4788: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4789:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4790:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4791:                                    .' <span class="LC_internal_info">'
1.625     www      4792:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4793:                                    .'</span>'
                   4794:                                    .' <b>';
1.596     raeburn  4795:                     if ($hidden) {
                   4796:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4797:                     } else {
1.640     raeburn  4798:                         my ($trial,$rndseed,$newvariation);
                   4799:                         if ($type eq 'randomizetry') {
                   4800:                             $trial = $$record{"$where.$partid.tries"};
                   4801:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4802:                         }
1.596     raeburn  4803: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4804: 			    $displaySub[0].=&mt('Trial not counted');
                   4805: 		        } else {
                   4806: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4807: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4808:                             if ($rndseed || $lastrndseed{$partid}) {
                   4809:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4810:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4811:                                 }
                   4812:                             }
                   4813:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4814: 		        }
                   4815: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4816:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4817: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4818: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4819: 			    $orders{$partid}->{$responseId}=
                   4820: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4821:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4822: 		        }
1.640     raeburn  4823: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4824: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4825: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4826:                     }
1.147     albertel 4827: 		}
                   4828: 	    }
1.335     albertel 4829: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4830: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4831: 				    $$record{"$where.$partid.checkedin"},
                   4832: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4833: 					'<br />';
1.335     albertel 4834: 	    }
                   4835: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4836: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4837: 		    lc($$record{"$where.$partid.award"}).' '.
                   4838: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4839: 		    '<br />';
                   4840: 	    }
1.335     albertel 4841: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4842: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4843: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4844: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4845: 		$displaySub[2].=
                   4846: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4847: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4848: 	    }
                   4849: 	}
                   4850: 	# needed because old essay regrader has not parts info
                   4851: 	if (exists $$record{"$version:resource.regrader"}) {
                   4852: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4853: 	}
                   4854: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4855: 	if ($displaySub[2]) {
1.467     albertel 4856: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4857: 	}
1.467     albertel 4858: 	$studentTable.='&nbsp;</td>'.
                   4859: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4860:     }
1.467     albertel 4861:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4862:     return $studentTable;
1.71      ng       4863: }
                   4864: 
                   4865: sub updateGradeByPage {
1.608     www      4866:     my ($request,$symb) = @_;
1.71      ng       4867: 
1.257     albertel 4868:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4869:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4870:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4871:     my $pageTitle = $env{'form.page'};
1.103     albertel 4872:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4873:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4874:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4875:     if (!&canmodify($usec)) {
1.526     raeburn  4876: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4877: 	return;
                   4878:     }
1.398     albertel 4879:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4880:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4881: 	'</h3>'."\n";
1.70      ng       4882: 
1.68      ng       4883:     $request->print($result);
                   4884: 
1.582     raeburn  4885: 
1.132     bowersj2 4886:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4887:     unless (ref($navmap)) {
                   4888:         $request->print(&navmap_errormsg());
                   4889:         return;
                   4890:     }
1.257     albertel 4891:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4892:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4893:     if (!$map) {
1.527     raeburn  4894: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4895: 	return; 
                   4896:     }
1.71      ng       4897:     my $iterator = $navmap->getIterator($map->map_start(),
                   4898: 					$map->map_finish());
1.70      ng       4899: 
1.484     albertel 4900:     my $studentTable=
                   4901: 	&Apache::loncommon::start_data_table().
                   4902: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4903: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4904: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4905: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4906: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4907: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4908: 
                   4909:     $iterator->next(); # skip the first BEGIN_MAP
                   4910:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4911:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4912:     while ($depth > 0) {
1.71      ng       4913:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4914:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4915: 
1.385     albertel 4916:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4917: 	    my $parts = $curRes->parts();
1.71      ng       4918:             my $title = $curRes->compTitle();
                   4919: 	    my $symbx = $curRes->symb();
1.484     albertel 4920: 	    $studentTable.=
                   4921: 		&Apache::loncommon::start_data_table_row().
                   4922: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4923: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4924:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4925: 		.')').'</td>';
1.71      ng       4926: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4927: 
                   4928: 	    my %newrecord=();
                   4929: 	    my @displayPts=();
1.269     raeburn  4930:             my %aggregate = ();
                   4931:             my $aggregateflag = 0;
1.71      ng       4932: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4933: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4934: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4935: 
1.257     albertel 4936: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4937: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4938: 		my $partial = $newpts/$wgt;
                   4939: 		my $score;
                   4940: 		if ($partial > 0) {
                   4941: 		    $score = 'correct_by_override';
1.125     ng       4942: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4943: 		    $score = 'incorrect_by_override';
                   4944: 		}
1.257     albertel 4945: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4946: 		if ($dropMenu eq 'excused') {
1.71      ng       4947: 		    $partial = '';
                   4948: 		    $score = 'excused';
1.125     ng       4949: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4950: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4951: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4952: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4953: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4954: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4955: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4956: 		    $changeflag++;
                   4957: 		    $newpts = '';
1.269     raeburn  4958:                     
                   4959:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4960:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4961:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4962:                     if ($aggtries > 0) {
                   4963:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4964:                         $aggregateflag = 1;
                   4965:                     }
1.71      ng       4966: 		}
1.324     albertel 4967: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4968: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4969: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4970: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4971: 		    '&nbsp;<br />';
1.526     raeburn  4972: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4973: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4974: 		    '&nbsp;<br />';
1.71      ng       4975: 		$question++;
1.380     albertel 4976: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4977: 
1.71      ng       4978: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4979: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4980: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4981: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4982: 
                   4983: 		$changeflag++;
                   4984: 	    }
                   4985: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4986: 		my %record = 
                   4987: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4988: 					     $udom,$uname);
                   4989: 
                   4990: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4991: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4992: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4993: 		    $newrecord{'resource.CODE'} = '';
                   4994: 		}
1.257     albertel 4995: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4996: 					$udom,$uname);
1.382     albertel 4997: 		%record = &Apache::lonnet::restore($symbx,
                   4998: 						   $env{'request.course.id'},
                   4999: 						   $udom,$uname);
1.380     albertel 5000: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5001: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5002: 	    }
1.380     albertel 5003: 	    
1.269     raeburn  5004:             if ($aggregateflag) {
                   5005:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5006:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5007:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5008:             }
1.125     ng       5009: 
1.71      ng       5010: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5011: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5012: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5013: 
1.196     albertel 5014: 	    $prob++;
1.68      ng       5015: 	}
1.71      ng       5016:         $curRes = $iterator->next();
1.68      ng       5017:     }
1.98      albertel 5018: 
1.484     albertel 5019:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5020:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5021: 		  &mt('The scores were changed for [quant,_1,problem].',
                   5022: 		  $changeflag));
1.76      ng       5023:     $request->print($grademsg.$studentTable);
1.68      ng       5024: 
1.70      ng       5025:     return '';
                   5026: }
                   5027: 
1.72      ng       5028: #-------- end of section for handling grading by page/sequence ---------
                   5029: #
                   5030: #-------------------------------------------------------------------
                   5031: 
1.581     www      5032: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5033: #
                   5034: #------ start of section for handling grading by page/sequence ---------
                   5035: 
1.423     albertel 5036: =pod
                   5037: 
                   5038: =head1 Bubble sheet grading routines
                   5039: 
1.424     albertel 5040:   For this documentation:
                   5041: 
                   5042:    'scanline' refers to the full line of characters
                   5043:    from the file that we are parsing that represents one entire sheet
                   5044: 
                   5045:    'bubble line' refers to the data
1.659     raeburn  5046:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5047: 
                   5048: 
1.659     raeburn  5049: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5050: into a course. When a user wants to grade, they select a
1.659     raeburn  5051: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5052: one of the predefined configurations for what each scanline looks
                   5053: like.
                   5054: 
                   5055: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5056: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5057: because too light bubbling), 'double bubble' (each bubble line should
                   5058: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  5059: invalid student/employee ID
1.424     albertel 5060: 
                   5061: If the CODE option is used that determines the randomization of the
1.556     weissno  5062: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5063: username:domain.
                   5064: 
                   5065: During the validation phase the instructor can choose to skip scanlines. 
                   5066: 
1.659     raeburn  5067: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5068: 
                   5069:   scantron_original_filename (unmodified original file)
                   5070:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5071:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5072: 
                   5073: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5074: correction information that isn't representable in the bubblesheet
1.424     albertel 5075: file (see &scantron_getfile() for more information)
                   5076: 
                   5077: After all scanlines are either valid, marked as valid or skipped, then
                   5078: foreach line foreach problem in the picked sequence, an ssi request is
                   5079: made that simulates a user submitting their selected letter(s) against
                   5080: the homework problem.
1.423     albertel 5081: 
                   5082: =over 4
                   5083: 
                   5084: 
                   5085: 
                   5086: =item defaultFormData
                   5087: 
                   5088:   Returns html hidden inputs used to hold context/default values.
                   5089: 
                   5090:  Arguments:
                   5091:   $symb - $symb of the current resource 
                   5092: 
                   5093: =cut
1.422     foxr     5094: 
1.81      albertel 5095: sub defaultFormData {
1.324     albertel 5096:     my ($symb)=@_;
1.613     www      5097:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5098: }
                   5099: 
1.447     foxr     5100: 
1.423     albertel 5101: =pod 
                   5102: 
                   5103: =item getSequenceDropDown
                   5104: 
                   5105:    Return html dropdown of possible sequences to grade
                   5106:  
                   5107:  Arguments:
1.582     raeburn  5108:    $symb - $symb of the current resource
                   5109:    $map_error - ref to scalar which will container error if
                   5110:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5111: 
                   5112: =cut
1.422     foxr     5113: 
1.75      albertel 5114: sub getSequenceDropDown {
1.582     raeburn  5115:     my ($symb,$map_error)=@_;
1.75      albertel 5116:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5117:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5118:     if (ref($map_error)) {
                   5119:         return if ($$map_error);
                   5120:     }
1.137     albertel 5121:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5122:     my $ctr=0;
                   5123:     foreach (@$titles) {
                   5124: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5125: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5126: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5127: 	    '>'.$showtitle.'</option>'."\n";
                   5128: 	$ctr++;
                   5129:     }
                   5130:     $result.= '</select>';
                   5131:     return $result;
                   5132: }
                   5133: 
1.495     albertel 5134: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5135:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5136: 
                   5137: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5138: 
1.509     raeburn  5139: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5140:                                    # matchresponse or rankresponse, where 
                   5141:                                    # an individual response can have multiple 
                   5142:                                    # lines
1.503     raeburn  5143: 
                   5144: my %responsetype_per_response;     # responsetype for each response
                   5145: 
1.495     albertel 5146: # Save and restore the bubble lines array to the form env.
                   5147: 
                   5148: 
                   5149: sub save_bubble_lines {
                   5150:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5151: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5152: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5153: 	    $first_bubble_line{$line};
1.503     raeburn  5154:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5155:             $subdivided_bubble_lines{$line};
                   5156:         $env{"form.scantron.responsetype.$line"} =
                   5157:             $responsetype_per_response{$line};
1.495     albertel 5158:     }
                   5159: }
                   5160: 
                   5161: 
                   5162: sub restore_bubble_lines {
                   5163:     my $line = 0;
                   5164:     %bubble_lines_per_response = ();
                   5165:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5166: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5167: 	$bubble_lines_per_response{$line} = $value;
                   5168: 	$first_bubble_line{$line}  =
                   5169: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5170:         $subdivided_bubble_lines{$line} =
                   5171:             $env{"form.scantron.sub_bubblelines.$line"};
                   5172:         $responsetype_per_response{$line} =
                   5173:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5174: 	$line++;
                   5175:     }
                   5176: }
                   5177: 
                   5178: #  Given the parsed scanline, get the response for 
                   5179: #  'answer' number n:
                   5180: 
                   5181: sub get_response_bubbles {
                   5182:     my ($parsed_line, $response)  = @_;
                   5183: 
                   5184:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5185:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5186:     
                   5187:     my $selected = "";
                   5188: 
                   5189:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5190: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5191: 	$bubble_line++;
                   5192:     }
                   5193:     return $selected;
                   5194: }
1.423     albertel 5195: 
                   5196: =pod 
                   5197: 
                   5198: =item scantron_filenames
                   5199: 
                   5200:    Returns a list of the scantron files in the current course 
                   5201: 
                   5202: =cut
1.422     foxr     5203: 
1.202     albertel 5204: sub scantron_filenames {
1.257     albertel 5205:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5206:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5207:     my $getpropath = 1;
1.662     raeburn  5208:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5209:                                                         $cname,$getpropath);
1.202     albertel 5210:     my @possiblenames;
1.662     raeburn  5211:     if (ref($dirlist) eq 'ARRAY') {
                   5212:         foreach my $filename (sort(@{$dirlist})) {
                   5213: 	    ($filename)=split(/&/,$filename);
                   5214: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5215: 	    $filename=~s/^scantron_orig_//;
                   5216: 	    push(@possiblenames,$filename);
                   5217:         }
1.202     albertel 5218:     }
                   5219:     return @possiblenames;
                   5220: }
                   5221: 
1.423     albertel 5222: =pod 
                   5223: 
                   5224: =item scantron_uploads
                   5225: 
                   5226:    Returns  html drop-down list of scantron files in current course.
                   5227: 
                   5228:  Arguments:
                   5229:    $file2grade - filename to set as selected in the dropdown
                   5230: 
                   5231: =cut
1.422     foxr     5232: 
1.202     albertel 5233: sub scantron_uploads {
1.209     ng       5234:     my ($file2grade) = @_;
1.202     albertel 5235:     my $result=	'<select name="scantron_selectfile">';
                   5236:     $result.="<option></option>";
                   5237:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5238: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5239:     }
                   5240:     $result.="</select>";
                   5241:     return $result;
                   5242: }
                   5243: 
1.423     albertel 5244: =pod 
                   5245: 
                   5246: =item scantron_scantab
                   5247: 
                   5248:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5249:   file.
                   5250: 
                   5251: =cut
1.422     foxr     5252: 
1.82      albertel 5253: sub scantron_scantab {
                   5254:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5255:     $result.='<option></option>'."\n";
1.518     raeburn  5256:     my @lines = &get_scantronformat_file();
                   5257:     if (@lines > 0) {
                   5258:         foreach my $line (@lines) {
                   5259:             next if (($line =~ /^\#/) || ($line eq ''));
                   5260: 	    my ($name,$descrip)=split(/:/,$line);
                   5261: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5262:         }
1.82      albertel 5263:     }
                   5264:     $result.='</select>'."\n";
1.518     raeburn  5265:     return $result;
                   5266: }
                   5267: 
                   5268: =pod
                   5269: 
                   5270: =item get_scantronformat_file
                   5271: 
                   5272:   Returns an array containing lines from the scantron format file for
                   5273:   the domain of the course.
                   5274: 
                   5275:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5276:   lines are from this file.
                   5277: 
                   5278:   Otherwise, if a default.tab has been published in RES space by the 
                   5279:   domainconfig user, lines are from this file.
                   5280: 
                   5281:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5282:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5283: 
1.518     raeburn  5284: =cut
                   5285: 
                   5286: sub get_scantronformat_file {
                   5287:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5288:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5289:     my $gottab = 0;
                   5290:     my @lines;
                   5291:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5292:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5293:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5294:             if ($formatfile ne '-1') {
                   5295:                 @lines = split("\n",$formatfile,-1);
                   5296:                 $gottab = 1;
                   5297:             }
                   5298:         }
                   5299:     }
                   5300:     if (!$gottab) {
                   5301:         my $confname = $cdom.'-domainconfig';
                   5302:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5303:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5304:         if ($formatfile ne '-1') {
                   5305:             @lines = split("\n",$formatfile,-1);
                   5306:             $gottab = 1;
                   5307:         }
                   5308:     }
                   5309:     if (!$gottab) {
1.519     raeburn  5310:         my @domains = &Apache::lonnet::current_machine_domains();
                   5311:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5312:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5313:             @lines = <$fh>;
                   5314:             close($fh);
                   5315:         } else {
                   5316:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5317:             @lines = <$fh>;
                   5318:             close($fh);
                   5319:         }
1.518     raeburn  5320:     }
                   5321:     return @lines;
1.82      albertel 5322: }
                   5323: 
1.423     albertel 5324: =pod 
                   5325: 
                   5326: =item scantron_CODElist
                   5327: 
                   5328:   Returns html drop down of the saved CODE lists from current course,
                   5329:   generated from earlier printings.
                   5330: 
                   5331: =cut
1.422     foxr     5332: 
1.186     albertel 5333: sub scantron_CODElist {
1.257     albertel 5334:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5335:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5336:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5337:     my $namechoice='<option></option>';
1.225     albertel 5338:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5339: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5340: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5341: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5342:     }
                   5343:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5344:     return $namechoice;
                   5345: }
                   5346: 
1.423     albertel 5347: =pod 
                   5348: 
                   5349: =item scantron_CODEunique
                   5350: 
                   5351:   Returns the html for "Each CODE to be used once" radio.
                   5352: 
                   5353: =cut
1.422     foxr     5354: 
1.186     albertel 5355: sub scantron_CODEunique {
1.532     bisitz   5356:     my $result='<span class="LC_nobreak">
1.272     albertel 5357:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5358:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5359:                 </span>
1.532     bisitz   5360:                 <span class="LC_nobreak">
1.272     albertel 5361:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5362:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5363:                 </span>';
1.186     albertel 5364:     return $result;
                   5365: }
1.423     albertel 5366: 
                   5367: =pod 
                   5368: 
                   5369: =item scantron_selectphase
                   5370: 
1.659     raeburn  5371:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5372:   Allows for - starting a grading run.
1.424     albertel 5373:              - downloading existing scan data (original, corrected
1.423     albertel 5374:                                                 or skipped info)
                   5375: 
                   5376:              - uploading new scan data
                   5377: 
                   5378:  Arguments:
                   5379:   $r          - The Apache request object
                   5380:   $file2grade - name of the file that contain the scanned data to score
                   5381: 
                   5382: =cut
1.186     albertel 5383: 
1.75      albertel 5384: sub scantron_selectphase {
1.608     www      5385:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5386:     if (!$symb) {return '';}
1.582     raeburn  5387:     my $map_error;
                   5388:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5389:     if ($map_error) {
                   5390:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5391:         return;
                   5392:     }
1.324     albertel 5393:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5394:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5395:     my $format_selector=&scantron_scantab();
1.186     albertel 5396:     my $CODE_selector=&scantron_CODElist();
                   5397:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5398:     my $result;
1.422     foxr     5399: 
1.513     foxr     5400:     $ssi_error = 0;
                   5401: 
1.606     wenzelju 5402:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5403:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5404: 
                   5405: 	# Chunk of form to prompt for a scantron file upload.
                   5406: 
                   5407:         $r->print('
                   5408:     <br />
                   5409:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5410:        '.&Apache::loncommon::start_data_table_header_row().'
                   5411:             <th>
                   5412:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5413:             </th>
                   5414:        '.&Apache::loncommon::end_data_table_header_row().'
                   5415:        '.&Apache::loncommon::start_data_table_row().'
                   5416:             <td>
                   5417: ');
1.608     www      5418:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5419:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5420:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5421:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5422:     function checkUpload(formname) {
                   5423: 	if (formname.upfile.value == "") {
                   5424: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5425: 	    return false;
                   5426: 	}
                   5427: 	formname.submit();
                   5428:     }'));
                   5429:     $r->print('
                   5430:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5431:                 '.$default_form_data.'
                   5432:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5433:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5434:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5435:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5436:                 <br />
                   5437:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5438:               </form>
                   5439: ');
                   5440: 
                   5441:         $r->print('
                   5442:             </td>
                   5443:        '.&Apache::loncommon::end_data_table_row().'
                   5444:        '.&Apache::loncommon::end_data_table().'
                   5445: ');
                   5446:     }
                   5447: 
1.422     foxr     5448:     # Chunk of form to prompt for a file to grade and how:
                   5449: 
1.489     albertel 5450:     $result.= '
                   5451:     <br />
                   5452:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5453:     <input type="hidden" name="command" value="scantron_warning" />
                   5454:     '.$default_form_data.'
                   5455:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5456:        '.&Apache::loncommon::start_data_table_header_row().'
                   5457:             <th colspan="2">
1.492     albertel 5458:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5459:             </th>
                   5460:        '.&Apache::loncommon::end_data_table_header_row().'
                   5461:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5462:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5463:        '.&Apache::loncommon::end_data_table_row().'
                   5464:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5465:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5466:        '.&Apache::loncommon::end_data_table_row().'
                   5467:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5468:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5469:        '.&Apache::loncommon::end_data_table_row().'
                   5470:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5471:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5472:        '.&Apache::loncommon::end_data_table_row().'
                   5473:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5474:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5475:        '.&Apache::loncommon::end_data_table_row().'
                   5476:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5477: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5478:             <td>
1.492     albertel 5479: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5480:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5481:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5482: 	    </td>
1.489     albertel 5483:        '.&Apache::loncommon::end_data_table_row().'
                   5484:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5485:             <td colspan="2">
1.572     www      5486:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5487:             </td>
1.489     albertel 5488:        '.&Apache::loncommon::end_data_table_row().'
                   5489:     '.&Apache::loncommon::end_data_table().'
                   5490:     </form>
                   5491: ';
1.162     albertel 5492:    
                   5493:     $r->print($result);
                   5494: 
1.422     foxr     5495: 
                   5496: 
                   5497:     # Chunk of the form that prompts to view a scoring office file,
                   5498:     # corrected file, skipped records in a file.
                   5499: 
1.489     albertel 5500:     $r->print('
                   5501:    <br />
                   5502:    <form action="/adm/grades" name="scantron_download">
                   5503:      '.$default_form_data.'
                   5504:      <input type="hidden" name="command" value="scantron_download" />
                   5505:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5506:        '.&Apache::loncommon::start_data_table_header_row().'
                   5507:               <th>
1.492     albertel 5508:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5509:               </th>
                   5510:        '.&Apache::loncommon::end_data_table_header_row().'
                   5511:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5512:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5513:                 <br />
1.492     albertel 5514:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5515:        '.&Apache::loncommon::end_data_table_row().'
                   5516:      '.&Apache::loncommon::end_data_table().'
                   5517:    </form>
                   5518:    <br />
                   5519: ');
1.162     albertel 5520: 
1.457     banghart 5521:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5522: 
1.528     raeburn  5523:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5524:              $default_form_data."\n".
                   5525:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5526:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5527:              '<th colspan="2">
1.572     www      5528:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5529:              '</th>'."\n".
                   5530:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5531:               &Apache::loncommon::start_data_table_row()."\n".
                   5532:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5533:               '<td> '.$sequence_selector.' </td>'.
                   5534:               &Apache::loncommon::end_data_table_row()."\n".
                   5535:               &Apache::loncommon::start_data_table_row()."\n".
                   5536:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5537:               '<td> '.$file_selector.' </td>'."\n".
                   5538:               &Apache::loncommon::end_data_table_row()."\n".
                   5539:               &Apache::loncommon::start_data_table_row()."\n".
                   5540:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5541:               '<td> '.$format_selector.' </td>'."\n".
                   5542:               &Apache::loncommon::end_data_table_row()."\n".
                   5543:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5544:               '<td> '.&mt('Options').' </td>'."\n".
                   5545:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5546:               &Apache::loncommon::end_data_table_row()."\n".
                   5547:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5548:               '<td colspan="2">'."\n".
                   5549:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5550:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5551:               '</td>'."\n".
                   5552:               &Apache::loncommon::end_data_table_row()."\n".
                   5553:               &Apache::loncommon::end_data_table()."\n".
                   5554:               '</form><br />');
                   5555:     return;
1.75      albertel 5556: }
                   5557: 
1.423     albertel 5558: =pod
                   5559: 
                   5560: =item get_scantron_config
                   5561: 
                   5562:    Parse and return the scantron configuration line selected as a
                   5563:    hash of configuration file fields.
                   5564: 
                   5565:  Arguments:
                   5566:     which - the name of the configuration to parse from the file.
                   5567: 
                   5568: 
                   5569:  Returns:
                   5570:             If the named configuration is not in the file, an empty
                   5571:             hash is returned.
                   5572:     a hash with the fields
                   5573:       name         - internal name for the this configuration setup
                   5574:       description  - text to display to operator that describes this config
                   5575:       CODElocation - if 0 or the string 'none'
                   5576:                           - no CODE exists for this config
                   5577:                      if -1 || the string 'letter'
                   5578:                           - a CODE exists for this config and is
                   5579:                             a string of letters
                   5580:                      Unsupported value (but planned for future support)
                   5581:                           if a positive integer
                   5582:                                - The CODE exists as the first n items from
                   5583:                                  the question section of the form
                   5584:                           if the string 'number'
                   5585:                                - The CODE exists for this config and is
                   5586:                                  a string of numbers
                   5587:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5588:                      the CODE starts
                   5589:       CODElength  - length of the CODE
1.573     bisitz   5590:       IDstart     - column where the student/employee ID starts
1.556     weissno  5591:       IDlength    - length of the student/employee ID info
1.423     albertel 5592:       Qstart      - column where the information from the bubbled
                   5593:                     'questions' start
                   5594:       Qlength     - number of columns comprising a single bubble line from
                   5595:                     the sheet. (usually either 1 or 10)
1.424     albertel 5596:       Qon         - either a single character representing the character used
1.423     albertel 5597:                     to signal a bubble was chosen in the positional setup, or
                   5598:                     the string 'letter' if the letter of the chosen bubble is
                   5599:                     in the final, or 'number' if a number representing the
                   5600:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5601:       Qoff        - the character used to represent that a bubble was
                   5602:                     left blank
1.423     albertel 5603:       PaperID     - if the scanning process generates a unique number for each
                   5604:                     sheet scanned the column that this ID number starts in
                   5605:       PaperIDlength - number of columns that comprise the unique ID number
                   5606:                       for the sheet of paper
1.424     albertel 5607:       FirstName   - column that the first name starts in
1.423     albertel 5608:       FirstNameLength - number of columns that the first name spans
                   5609:  
                   5610:       LastName    - column that the last name starts in
                   5611:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5612:       BubblesPerRow - number of bubbles available in each row used to 
                   5613:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5614: 
1.423     albertel 5615: =cut
1.422     foxr     5616: 
1.82      albertel 5617: sub get_scantron_config {
                   5618:     my ($which) = @_;
1.518     raeburn  5619:     my @lines = &get_scantronformat_file();
1.82      albertel 5620:     my %config;
1.157     albertel 5621:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5622:     foreach my $line (@lines) {
1.82      albertel 5623: 	my ($name,$descrip)=split(/:/,$line);
                   5624: 	if ($name ne $which ) { next; }
                   5625: 	chomp($line);
                   5626: 	my @config=split(/:/,$line);
                   5627: 	$config{'name'}=$config[0];
                   5628: 	$config{'description'}=$config[1];
                   5629: 	$config{'CODElocation'}=$config[2];
                   5630: 	$config{'CODEstart'}=$config[3];
                   5631: 	$config{'CODElength'}=$config[4];
                   5632: 	$config{'IDstart'}=$config[5];
                   5633: 	$config{'IDlength'}=$config[6];
                   5634: 	$config{'Qstart'}=$config[7];
1.497     foxr     5635:  	$config{'Qlength'}=$config[8];
1.82      albertel 5636: 	$config{'Qoff'}=$config[9];
                   5637: 	$config{'Qon'}=$config[10];
1.157     albertel 5638: 	$config{'PaperID'}=$config[11];
                   5639: 	$config{'PaperIDlength'}=$config[12];
                   5640: 	$config{'FirstName'}=$config[13];
                   5641: 	$config{'FirstNamelength'}=$config[14];
                   5642: 	$config{'LastName'}=$config[15];
                   5643: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5644:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5645: 	last;
                   5646:     }
                   5647:     return %config;
                   5648: }
                   5649: 
1.423     albertel 5650: =pod 
                   5651: 
                   5652: =item username_to_idmap
                   5653: 
1.556     weissno  5654:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5655:     student username:domain.
                   5656: 
                   5657:   Arguments:
                   5658: 
                   5659:     $classlist - reference to the class list hash. This is a hash
                   5660:                  keyed by student name:domain  whose elements are references
1.424     albertel 5661:                  to arrays containing various chunks of information
1.423     albertel 5662:                  about the student. (See loncoursedata for more info).
                   5663: 
                   5664:   Returns
                   5665:     %idmap - the constructed hash
                   5666: 
                   5667: =cut
                   5668: 
1.82      albertel 5669: sub username_to_idmap {
                   5670:     my ($classlist)= @_;
                   5671:     my %idmap;
                   5672:     foreach my $student (keys(%$classlist)) {
                   5673: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5674: 	    $student;
                   5675:     }
                   5676:     return %idmap;
                   5677: }
1.423     albertel 5678: 
                   5679: =pod
                   5680: 
1.424     albertel 5681: =item scantron_fixup_scanline
1.423     albertel 5682: 
                   5683:    Process a requested correction to a scanline.
                   5684: 
                   5685:   Arguments:
                   5686:     $scantron_config   - hash from &get_scantron_config()
                   5687:     $scan_data         - hash of correction information 
                   5688:                           (see &scantron_getfile())
                   5689:     $line              - existing scanline
                   5690:     $whichline         - line number of the passed in scanline
                   5691:     $field             - type of change to process 
                   5692:                          (either 
1.573     bisitz   5693:                           'ID'     -> correct the student/employee ID
1.423     albertel 5694:                           'CODE'   -> correct the CODE
                   5695:                           'answer' -> fixup the submitted answers)
                   5696:     
                   5697:    $args               - hash of additional info,
                   5698:                           - 'ID' 
                   5699:                                'newid' -> studentID to use in replacement
1.424     albertel 5700:                                           of existing one
1.423     albertel 5701:                           - 'CODE' 
                   5702:                                'CODE_ignore_dup' - set to true if duplicates
                   5703:                                                    should be ignored.
                   5704: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5705:                                         if the existing unfound code should
1.423     albertel 5706:                                         be used as is
                   5707:                           - 'answer'
                   5708:                                'response' - new answer or 'none' if blank
                   5709:                                'question' - the bubble line to change
1.503     raeburn  5710:                                'questionnum' - the question identifier,
                   5711:                                                may include subquestion. 
1.423     albertel 5712: 
                   5713:   Returns:
                   5714:     $line - the modified scanline
                   5715: 
                   5716:   Side effects: 
                   5717:     $scan_data - may be updated
                   5718: 
                   5719: =cut
                   5720: 
1.82      albertel 5721: 
1.157     albertel 5722: sub scantron_fixup_scanline {
                   5723:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5724:     if ($field eq 'ID') {
                   5725: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5726: 	    return ($line,1,'New value too large');
1.157     albertel 5727: 	}
                   5728: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5729: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5730: 				     $args->{'newid'});
                   5731: 	}
                   5732: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5733: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5734: 	if ($args->{'newid'}=~/^\s*$/) {
                   5735: 	    &scan_data($scan_data,"$whichline.user",
                   5736: 		       $args->{'username'}.':'.$args->{'domain'});
                   5737: 	}
1.186     albertel 5738:     } elsif ($field eq 'CODE') {
1.192     albertel 5739: 	if ($args->{'CODE_ignore_dup'}) {
                   5740: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5741: 	}
                   5742: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5743: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5744: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5745: 		return ($line,1,'New CODE value too large');
                   5746: 	    }
                   5747: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5748: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5749: 	    }
                   5750: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5751: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5752: 	}
1.157     albertel 5753:     } elsif ($field eq 'answer') {
1.497     foxr     5754: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5755: 	my $off=$scantron_config->{'Qoff'};
                   5756: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5757: 	my $answer=${off}x$length;
                   5758: 	if ($args->{'response'} eq 'none') {
                   5759: 	    &scan_data($scan_data,
1.503     raeburn  5760: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5761: 	} else {
                   5762: 	    if ($on eq 'letter') {
                   5763: 		my @alphabet=('A'..'Z');
                   5764: 		$answer=$alphabet[$args->{'response'}];
                   5765: 	    } elsif ($on eq 'number') {
                   5766: 		$answer=$args->{'response'}+1;
                   5767: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5768: 	    } else {
1.497     foxr     5769: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5770: 	    }
1.497     foxr     5771: 	    &scan_data($scan_data,
1.503     raeburn  5772: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5773: 	}
1.497     foxr     5774: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5775: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5776:     }
                   5777:     return $line;
                   5778: }
1.423     albertel 5779: 
                   5780: =pod
                   5781: 
                   5782: =item scan_data
                   5783: 
                   5784:     Edit or look up  an item in the scan_data hash.
                   5785: 
                   5786:   Arguments:
                   5787:     $scan_data  - The hash (see scantron_getfile)
                   5788:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5789:                   scantronfilename_key).
1.423     albertel 5790:     $data        - New value of the hash entry.
                   5791:     $delete      - If true, the entry is removed from the hash.
                   5792: 
                   5793:   Returns:
                   5794:     The new value of the hash table field (undefined if deleted).
                   5795: 
                   5796: =cut
                   5797: 
                   5798: 
1.157     albertel 5799: sub scan_data {
                   5800:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5801:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5802:     if (defined($value)) {
                   5803: 	$scan_data->{$filename.'_'.$key} = $value;
                   5804:     }
                   5805:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5806:     return $scan_data->{$filename.'_'.$key};
                   5807: }
1.423     albertel 5808: 
1.495     albertel 5809: # ----- These first few routines are general use routines.----
                   5810: 
                   5811: # Return the number of occurences of a pattern in a string.
                   5812: 
                   5813: sub occurence_count {
                   5814:     my ($string, $pattern) = @_;
                   5815: 
                   5816:     my @matches = ($string =~ /$pattern/g);
                   5817: 
                   5818:     return scalar(@matches);
                   5819: }
                   5820: 
                   5821: 
                   5822: # Take a string known to have digits and convert all the
                   5823: # digits into letters in the range J,A..I.
                   5824: 
                   5825: sub digits_to_letters {
                   5826:     my ($input) = @_;
                   5827: 
                   5828:     my @alphabet = ('J', 'A'..'I');
                   5829: 
                   5830:     my @input    = split(//, $input);
                   5831:     my $output ='';
                   5832:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5833: 	if ($input[$i] =~ /\d/) {
                   5834: 	    $output .= $alphabet[$input[$i]];
                   5835: 	} else {
                   5836: 	    $output .= $input[$i];
                   5837: 	}
                   5838:     }
                   5839:     return $output;
                   5840: }
                   5841: 
1.423     albertel 5842: =pod 
                   5843: 
                   5844: =item scantron_parse_scanline
                   5845: 
                   5846:   Decodes a scanline from the selected scantron file
                   5847: 
                   5848:  Arguments:
                   5849:     line             - The text of the scantron file line to process
                   5850:     whichline        - Line number
                   5851:     scantron_config  - Hash describing the format of the scantron lines.
                   5852:     scan_data        - Hash of extra information about the scanline
                   5853:                        (see scantron_getfile for more information)
                   5854:     just_header      - True if should not process question answers but only
                   5855:                        the stuff to the left of the answers.
                   5856:  Returns:
                   5857:    Hash containing the result of parsing the scanline
                   5858: 
                   5859:    Keys are all proceeded by the string 'scantron.'
                   5860: 
                   5861:        CODE    - the CODE in use for this scanline
                   5862:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5863:                  by the operator
                   5864:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5865:                             CODEs were selected, but the usage has been
                   5866:                             forced by the operator
1.556     weissno  5867:        ID  - student/employee ID
1.423     albertel 5868:        PaperID - if used, the ID number printed on the sheet when the 
                   5869:                  paper was scanned
                   5870:        FirstName - first name from the sheet
                   5871:        LastName  - last name from the sheet
                   5872: 
                   5873:      if just_header was not true these key may also exist
                   5874: 
1.447     foxr     5875:        missingerror - a list of bubble ranges that are considered to be answers
                   5876:                       to a single question that don't have any bubbles filled in.
                   5877:                       Of the form questionnumber:firstbubblenumber:count.
                   5878:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5879:                       to a single question that have more than one bubble filled in.
                   5880:                       Of the form questionnumber::firstbubblenumber:count
                   5881:    
                   5882:                 In the above, count is the number of bubble responses in the
                   5883:                 input line needed to represent the possible answers to the question.
                   5884:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5885:                 per line would have count = 2.
                   5886: 
1.423     albertel 5887:        maxquest     - the number of the last bubble line that was parsed
                   5888: 
                   5889:        (<number> starts at 1)
                   5890:        <number>.answer - zero or more letters representing the selected
                   5891:                          letters from the scanline for the bubble line 
                   5892:                          <number>.
                   5893:                          if blank there was either no bubble or there where
                   5894:                          multiple bubbles, (consult the keys missingerror and
                   5895:                          doubleerror if this is an error condition)
                   5896: 
                   5897: =cut
                   5898: 
1.82      albertel 5899: sub scantron_parse_scanline {
1.423     albertel 5900:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5901: 
1.82      albertel 5902:     my %record;
1.550     raeburn  5903:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5904:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5905:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5906:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5907: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5908: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5909: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5910: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5911: 	    $record{'scantron.CODE'}=substr($data,
                   5912: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5913: 					    $$scantron_config{'CODElength'});
1.191     albertel 5914: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5915: 		$record{'scantron.useCODE'}=1;
                   5916: 	    }
1.192     albertel 5917: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5918: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5919: 	    }
1.82      albertel 5920: 	} else {
                   5921: 	    #FIXME interpret first N questions
                   5922: 	}
                   5923:     }
1.83      albertel 5924:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5925: 				  $$scantron_config{'IDlength'});
1.157     albertel 5926:     $record{'scantron.PaperID'}=
                   5927: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5928: 	       $$scantron_config{'PaperIDlength'});
                   5929:     $record{'scantron.FirstName'}=
                   5930: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5931: 	       $$scantron_config{'FirstNamelength'});
                   5932:     $record{'scantron.LastName'}=
                   5933: 	substr($data,$$scantron_config{'LastName'}-1,
                   5934: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5935:     if ($just_header) { return \%record; }
1.194     albertel 5936: 
1.82      albertel 5937:     my @alphabet=('A'..'Z');
                   5938:     my $questnum=0;
1.447     foxr     5939:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5940: 
1.470     foxr     5941:     chomp($questions);		# Get rid of any trailing \n.
                   5942:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5943:     while (length($questions)) {
1.447     foxr     5944: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5945:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5946:                              || 1;
                   5947:         $questnum++;
                   5948:         my $quest_id = $questnum;
                   5949:         my $currentquest = substr($questions,0,$answer_length);
                   5950:         $questions       = substr($questions,$answer_length);
                   5951:         if (length($currentquest) < $answer_length) { next; }
                   5952: 
                   5953:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5954:             my $subquestnum = 1;
                   5955:             my $subquestions = $currentquest;
                   5956:             my @subanswers_needed = 
                   5957:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5958:             foreach my $subans (@subanswers_needed) {
                   5959:                 my $subans_length =
                   5960:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5961:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5962:                 $subquestions   = substr($subquestions,$subans_length);
                   5963:                 $quest_id = "$questnum.$subquestnum";
                   5964:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5965:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5966:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5967:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5968:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5969:                 } else {
                   5970:                     $ansnum = &scantron_validator_positional($ansnum,
                   5971:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5972:                 }
                   5973:                 $subquestnum ++;
                   5974:             }
                   5975:         } else {
                   5976:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5977:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5978:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5979:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5980:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5981:             } else {
                   5982:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5983:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5984:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5985:             }
                   5986:         }
                   5987:     }
                   5988:     $record{'scantron.maxquest'}=$questnum;
                   5989:     return \%record;
                   5990: }
1.447     foxr     5991: 
1.503     raeburn  5992: sub scantron_validator_lettnum {
                   5993:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5994:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5995: 
                   5996:     # Qon 'letter' implies for each slot in currquest we have:
                   5997:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5998:     #    about anything else (esp. a value of Qoff) for missing
                   5999:     #    bubbles.
                   6000:     #
                   6001:     # Qon 'number' implies each slot gives a digit that indexes the
                   6002:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6003:     #    and * or ? for double bubbles on a single line.
                   6004:     #
1.447     foxr     6005: 
1.503     raeburn  6006:     my $matchon;
                   6007:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6008:         $matchon = '[A-Z]';
                   6009:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6010:         $matchon = '\d';
                   6011:     }
                   6012:     my $occurrences = 0;
                   6013:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6014:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6015:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6016:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6017:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6018:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6019:         my @singlelines = split('',$currquest);
                   6020:         foreach my $entry (@singlelines) {
                   6021:             $occurrences = &occurence_count($entry,$matchon);
                   6022:             if ($occurrences > 1) {
                   6023:                 last;
                   6024:             }
                   6025:         } 
                   6026:     } else {
                   6027:         $occurrences = &occurence_count($currquest,$matchon); 
                   6028:     }
                   6029:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6030:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6031:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6032:             my $bubble = substr($currquest,$ans,1);
                   6033:             if ($bubble =~ /$matchon/ ) {
                   6034:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6035:                     if ($bubble == 0) {
                   6036:                         $bubble = 10; 
                   6037:                     }
                   6038:                     $record->{"scantron.$ansnum.answer"} = 
                   6039:                         $alphabet->[$bubble-1];
                   6040:                 } else {
                   6041:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6042:                 }
                   6043:             } else {
                   6044:                 $record->{"scantron.$ansnum.answer"}='';
                   6045:             }
                   6046:             $ansnum++;
                   6047:         }
                   6048:     } elsif (!defined($currquest)
                   6049:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6050:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6051:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6052:             $record->{"scantron.$ansnum.answer"}='';
                   6053:             $ansnum++;
                   6054:         }
                   6055:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6056:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6057:         }
                   6058:     } else {
                   6059:         if ($$scantron_config{'Qon'} eq 'number') {
                   6060:             $currquest = &digits_to_letters($currquest);            
                   6061:         }
                   6062:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6063:             my $bubble = substr($currquest,$ans,1);
                   6064:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6065:             $ansnum++;
                   6066:         }
                   6067:     }
                   6068:     return $ansnum;
                   6069: }
1.447     foxr     6070: 
1.503     raeburn  6071: sub scantron_validator_positional {
                   6072:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   6073:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     6074: 
1.503     raeburn  6075:     # Otherwise there's a positional notation;
                   6076:     # each bubble line requires Qlength items, and there are filled in
                   6077:     # bubbles for each case where there 'Qon' characters.
                   6078:     #
1.447     foxr     6079: 
1.503     raeburn  6080:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6081: 
1.503     raeburn  6082:     # If the split only gives us one element.. the full length of the
                   6083:     # answer string, no bubbles are filled in:
1.447     foxr     6084: 
1.507     raeburn  6085:     if ($answers_needed eq '') {
                   6086:         return;
                   6087:     }
                   6088: 
1.503     raeburn  6089:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6090:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6091:             $record->{"scantron.$ansnum.answer"}='';
                   6092:             $ansnum++;
                   6093:         }
                   6094:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6095:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6096:         }
                   6097:     } elsif (scalar(@array) == 2) {
                   6098:         my $location = length($array[0]);
                   6099:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6100:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6101:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6102:             if ($ans eq $line_num) {
                   6103:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6104:             } else {
                   6105:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6106:             }
                   6107:             $ansnum++;
                   6108:          }
                   6109:     } else {
                   6110:         #  If there's more than one instance of a bubble character
                   6111:         #  That's a double bubble; with positional notation we can
                   6112:         #  record all the bubbles filled in as well as the
                   6113:         #  fact this response consists of multiple bubbles.
                   6114:         #
                   6115:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6116:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6117:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6118:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6119:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6120:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6121:             my $doubleerror = 0;
                   6122:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6123:                    (!$doubleerror)) {
                   6124:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6125:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6126:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6127:                if (length(@currarray) > 2) {
                   6128:                    $doubleerror = 1;
                   6129:                } 
                   6130:             }
                   6131:             if ($doubleerror) {
                   6132:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6133:             }
                   6134:         } else {
                   6135:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6136:         }
                   6137:         my $item = $ansnum;
                   6138:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6139:             $record->{"scantron.$item.answer"} = '';
                   6140:             $item ++;
                   6141:         }
1.447     foxr     6142: 
1.503     raeburn  6143:         my @ans=@array;
                   6144:         my $i=0;
                   6145:         my $increment = 0;
                   6146:         while ($#ans) {
                   6147:             $i+=length($ans[0]) + $increment;
                   6148:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6149:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6150:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6151:             shift(@ans);
                   6152:             $increment = 1;
                   6153:         }
                   6154:         $ansnum += $answers_needed;
1.82      albertel 6155:     }
1.503     raeburn  6156:     return $ansnum;
1.82      albertel 6157: }
                   6158: 
1.423     albertel 6159: =pod
                   6160: 
                   6161: =item scantron_add_delay
                   6162: 
                   6163:    Adds an error message that occurred during the grading phase to a
                   6164:    queue of messages to be shown after grading pass is complete
                   6165: 
                   6166:  Arguments:
1.424     albertel 6167:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6168:    $scanline    - the scanline that caused the error
                   6169:    $errormesage - the error message
                   6170:    $errorcode   - a numeric code for the error
                   6171: 
                   6172:  Side Effects:
1.424     albertel 6173:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6174: 
                   6175: =cut
                   6176: 
1.82      albertel 6177: sub scantron_add_delay {
1.140     albertel 6178:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6179:     push(@$delayqueue,
                   6180: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6181: 	  'ecode' => $errorcode }
                   6182: 	 );
1.82      albertel 6183: }
                   6184: 
1.423     albertel 6185: =pod
                   6186: 
                   6187: =item scantron_find_student
                   6188: 
1.424     albertel 6189:    Finds the username for the current scanline
                   6190: 
                   6191:   Arguments:
                   6192:    $scantron_record - hash result from scantron_parse_scanline
                   6193:    $scan_data       - hash of correction information 
                   6194:                       (see &scantron_getfile() form more information)
                   6195:    $idmap           - hash from &username_to_idmap()
                   6196:    $line            - number of current scanline
                   6197:  
                   6198:   Returns:
                   6199:    Either 'username:domain' or undef if unknown
                   6200: 
1.423     albertel 6201: =cut
                   6202: 
1.82      albertel 6203: sub scantron_find_student {
1.157     albertel 6204:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6205:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6206:     if ($scanID =~ /^\s*$/) {
                   6207:  	return &scan_data($scan_data,"$line.user");
                   6208:     }
1.83      albertel 6209:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6210:  	if (lc($id) eq lc($scanID)) {
                   6211:  	    return $$idmap{$id};
                   6212:  	}
1.83      albertel 6213:     }
                   6214:     return undef;
                   6215: }
                   6216: 
1.423     albertel 6217: =pod
                   6218: 
                   6219: =item scantron_filter
                   6220: 
1.424     albertel 6221:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6222:    hidden resources was selected
                   6223: 
1.423     albertel 6224: =cut
                   6225: 
1.83      albertel 6226: sub scantron_filter {
                   6227:     my ($curres)=@_;
1.331     albertel 6228: 
                   6229:     if (ref($curres) && $curres->is_problem()) {
                   6230: 	# if the user has asked to not have either hidden
                   6231: 	# or 'randomout' controlled resources to be graded
                   6232: 	# don't include them
                   6233: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6234: 	    && $curres->randomout) {
                   6235: 	    return 0;
                   6236: 	}
1.83      albertel 6237: 	return 1;
                   6238:     }
                   6239:     return 0;
1.82      albertel 6240: }
                   6241: 
1.423     albertel 6242: =pod
                   6243: 
                   6244: =item scantron_process_corrections
                   6245: 
1.424     albertel 6246:    Gets correction information out of submitted form data and corrects
                   6247:    the scanline
                   6248: 
1.423     albertel 6249: =cut
                   6250: 
1.157     albertel 6251: sub scantron_process_corrections {
                   6252:     my ($r) = @_;
1.257     albertel 6253:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6254:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6255:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6256:     my $which=$env{'form.scantron_line'};
1.200     albertel 6257:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6258:     my ($skip,$err,$errmsg);
1.257     albertel 6259:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6260: 	$skip=1;
1.257     albertel 6261:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6262: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6263: 	    $env{'form.scantron_domain'};
1.157     albertel 6264: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6265: 	($line,$err,$errmsg)=
                   6266: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6267: 				     'ID',{'newid'=>$newid,
1.257     albertel 6268: 				    'username'=>$env{'form.scantron_username'},
                   6269: 				    'domain'=>$env{'form.scantron_domain'}});
                   6270:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6271: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6272: 	my $newCODE;
1.192     albertel 6273: 	my %args;
1.190     albertel 6274: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6275: 	    $newCODE='use_unfound';
1.190     albertel 6276: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6277: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6278: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6279: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6280: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6281: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6282: 	}
1.257     albertel 6283: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6284: 	    $args{'CODE_ignore_dup'}=1;
                   6285: 	}
                   6286: 	$args{'CODE'}=$newCODE;
1.186     albertel 6287: 	($line,$err,$errmsg)=
                   6288: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6289: 				     'CODE',\%args);
1.257     albertel 6290:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6291: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6292: 	    ($line,$err,$errmsg)=
                   6293: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6294: 					 $which,'answer',
                   6295: 					 { 'question'=>$question,
1.503     raeburn  6296: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6297:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6298: 	    if ($err) { last; }
                   6299: 	}
                   6300:     }
                   6301:     if ($err) {
1.398     albertel 6302: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6303:     } else {
1.200     albertel 6304: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6305: 	&scantron_putfile($scanlines,$scan_data);
                   6306:     }
                   6307: }
                   6308: 
1.423     albertel 6309: =pod
                   6310: 
                   6311: =item reset_skipping_status
                   6312: 
1.424     albertel 6313:    Forgets the current set of remember skipped scanlines (and thus
                   6314:    reverts back to considering all lines in the
                   6315:    scantron_skipped_<filename> file)
                   6316: 
1.423     albertel 6317: =cut
                   6318: 
1.200     albertel 6319: sub reset_skipping_status {
                   6320:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6321:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6322:     &scantron_putfile(undef,$scan_data);
                   6323: }
                   6324: 
1.423     albertel 6325: =pod
                   6326: 
                   6327: =item start_skipping
                   6328: 
1.424     albertel 6329:    Marks a scanline to be skipped. 
                   6330: 
1.423     albertel 6331: =cut
                   6332: 
1.376     albertel 6333: sub start_skipping {
1.200     albertel 6334:     my ($scan_data,$i)=@_;
                   6335:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6336:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6337: 	$remembered{$i}=2;
                   6338:     } else {
                   6339: 	$remembered{$i}=1;
                   6340:     }
1.200     albertel 6341:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6342: }
                   6343: 
1.423     albertel 6344: =pod
                   6345: 
                   6346: =item should_be_skipped
                   6347: 
1.424     albertel 6348:    Checks whether a scanline should be skipped.
                   6349: 
1.423     albertel 6350: =cut
                   6351: 
1.200     albertel 6352: sub should_be_skipped {
1.376     albertel 6353:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6354:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6355: 	# not redoing old skips
1.376     albertel 6356: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6357: 	return 0;
                   6358:     }
                   6359:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6360: 
                   6361:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6362: 	return 0;
                   6363:     }
1.200     albertel 6364:     return 1;
                   6365: }
                   6366: 
1.423     albertel 6367: =pod
                   6368: 
                   6369: =item remember_current_skipped
                   6370: 
1.424     albertel 6371:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6372:    file and remembers them into scan_data for later use.
                   6373: 
1.423     albertel 6374: =cut
                   6375: 
1.200     albertel 6376: sub remember_current_skipped {
                   6377:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6378:     my %to_remember;
                   6379:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6380: 	if ($scanlines->{'skipped'}[$i]) {
                   6381: 	    $to_remember{$i}=1;
                   6382: 	}
                   6383:     }
1.376     albertel 6384: 
1.200     albertel 6385:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6386:     &scantron_putfile(undef,$scan_data);
                   6387: }
                   6388: 
1.423     albertel 6389: =pod
                   6390: 
                   6391: =item check_for_error
                   6392: 
1.424     albertel 6393:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6394:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6395:     something went wrong.
                   6396: 
1.423     albertel 6397: =cut
                   6398: 
1.200     albertel 6399: sub check_for_error {
                   6400:     my ($r,$result)=@_;
                   6401:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6402: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6403:     }
                   6404: }
1.157     albertel 6405: 
1.423     albertel 6406: =pod
                   6407: 
                   6408: =item scantron_warning_screen
                   6409: 
1.424     albertel 6410:    Interstitial screen to make sure the operator has selected the
                   6411:    correct options before we start the validation phase.
                   6412: 
1.423     albertel 6413: =cut
                   6414: 
1.203     albertel 6415: sub scantron_warning_screen {
1.650     raeburn  6416:     my ($button_text,$symb)=@_;
1.257     albertel 6417:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6418:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6419:     my $CODElist;
1.284     albertel 6420:     if ($scantron_config{'CODElocation'} &&
                   6421: 	$scantron_config{'CODEstart'} &&
                   6422: 	$scantron_config{'CODElength'}) {
                   6423: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6424: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6425: 	$CODElist=
1.492     albertel 6426: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6427: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6428:     }
1.663     raeburn  6429:     my $lastbubblepoints;
                   6430:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6431:         $lastbubblepoints =
                   6432:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6433:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6434:     }
1.492     albertel 6435:     return ('
1.203     albertel 6436: <p>
1.492     albertel 6437: <span class="LC_warning">
                   6438: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6439: </p>
                   6440: <table>
1.492     albertel 6441: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6442: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6443: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6444: </table>
1.650     raeburn  6445: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6446: '.&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 6447: 
                   6448: <br />
1.492     albertel 6449: ');
1.203     albertel 6450: }
                   6451: 
1.423     albertel 6452: =pod
                   6453: 
                   6454: =item scantron_do_warning
                   6455: 
1.424     albertel 6456:    Check if the operator has picked something for all required
                   6457:    fields. Error out if something is missing.
                   6458: 
1.423     albertel 6459: =cut
                   6460: 
1.203     albertel 6461: sub scantron_do_warning {
1.608     www      6462:     my ($r,$symb)=@_;
1.203     albertel 6463:     if (!$symb) {return '';}
1.324     albertel 6464:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6465:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6466:     if ( $env{'form.selectpage'} eq '' ||
                   6467: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6468: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6469: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6470: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6471: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6472: 	} 
1.257     albertel 6473: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6474: 	    $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 6475: 	} 
1.257     albertel 6476: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6477: 	    $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 6478: 	} 
                   6479:     } else {
1.650     raeburn  6480: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6481:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6482: 	$r->print('
1.663     raeburn  6483: '.$warning.$bubbledbyhand.'
1.492     albertel 6484: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6485: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6486: ');
1.237     albertel 6487:     }
1.614     www      6488:     $r->print("</form><br />");
1.203     albertel 6489:     return '';
                   6490: }
                   6491: 
1.423     albertel 6492: =pod
                   6493: 
                   6494: =item scantron_form_start
                   6495: 
1.424     albertel 6496:     html hidden input for remembering all selected grading options
                   6497: 
1.423     albertel 6498: =cut
                   6499: 
1.203     albertel 6500: sub scantron_form_start {
                   6501:     my ($max_bubble)=@_;
                   6502:     my $result= <<SCANTRONFORM;
                   6503: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6504:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6505:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6506:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6507:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6508:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6509:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6510:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6511:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6512:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6513: SCANTRONFORM
1.447     foxr     6514: 
                   6515:   my $line = 0;
                   6516:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6517:        my $chunk =
                   6518: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6519:        $chunk .=
                   6520: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6521:        $chunk .= 
                   6522:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6523:        $chunk .=
                   6524:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6525:        $result .= $chunk;
                   6526:        $line++;
                   6527:    }
1.203     albertel 6528:     return $result;
                   6529: }
                   6530: 
1.423     albertel 6531: =pod
                   6532: 
                   6533: =item scantron_validate_file
                   6534: 
1.659     raeburn  6535:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6536: 
                   6537:     Also processes any necessary information resets that need to
                   6538:     occur before validation begins (ignore previous corrections,
                   6539:     restarting the skipped records processing)
                   6540: 
1.423     albertel 6541: =cut
                   6542: 
1.157     albertel 6543: sub scantron_validate_file {
1.608     www      6544:     my ($r,$symb) = @_;
1.157     albertel 6545:     if (!$symb) {return '';}
1.324     albertel 6546:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6547:     
                   6548:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6549:     # them when doing the corrections reset
1.257     albertel 6550:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6551: 	&reset_skipping_status();
                   6552:     }
1.257     albertel 6553:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6554: 	&remember_current_skipped();
1.257     albertel 6555: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6556:     }
                   6557: 
1.257     albertel 6558:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6559: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6560: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6561: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6562: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6563:     }
1.200     albertel 6564: 
1.257     albertel 6565:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6566: 	&scantron_process_corrections($r);
                   6567:     }
1.503     raeburn  6568:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6569:     #get the student pick code ready
                   6570:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6571:     my $nav_error;
1.649     raeburn  6572:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6573:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6574:     if ($nav_error) {
                   6575:         $r->print(&navmap_errormsg());
                   6576:         return '';
                   6577:     }
1.203     albertel 6578:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6579:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6580:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6581:     }
1.157     albertel 6582:     $r->print($result);
                   6583:     
1.334     albertel 6584:     my @validate_phases=( 'sequence',
                   6585: 			  'ID',
1.157     albertel 6586: 			  'CODE',
                   6587: 			  'doublebubble',
                   6588: 			  'missingbubbles');
1.257     albertel 6589:     if (!$env{'form.validatepass'}) {
                   6590: 	$env{'form.validatepass'} = 0;
1.157     albertel 6591:     }
1.257     albertel 6592:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6593: 
1.448     foxr     6594: 
1.157     albertel 6595:     my $stop=0;
                   6596:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6597: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6598: 	$r->rflush();
                   6599: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6600: 	{
                   6601: 	    no strict 'refs';
                   6602: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6603: 	}
                   6604:     }
                   6605:     if (!$stop) {
1.650     raeburn  6606: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6607: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6608:                   $warning.
                   6609:                   &mt('Perform verification for each student after storage of submissions?').
                   6610:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6611:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6612:                   ('&nbsp;'x3).'<label>'.
                   6613:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6614:                   '</label></span><br />'.
                   6615:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6616:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6617:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6618:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6619:     } else {
                   6620: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6621: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6622:     }
                   6623:     if ($stop) {
1.334     albertel 6624: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6625: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6626: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6627: 
1.650     raeburn  6628: 	    $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 6629: 	} else {
1.503     raeburn  6630:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6631: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6632:             } else {
1.539     riegler  6633:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6634:             }
1.492     albertel 6635: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6636: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6637: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6638: 	}
1.157     albertel 6639:     }
1.614     www      6640:     $r->print(" </form><br />");
1.157     albertel 6641:     return '';
                   6642: }
                   6643: 
1.423     albertel 6644: 
                   6645: =pod
                   6646: 
                   6647: =item scantron_remove_file
                   6648: 
1.659     raeburn  6649:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6650:    scantron_original_<filename> is never removed
                   6651: 
                   6652: 
1.423     albertel 6653: =cut
                   6654: 
1.200     albertel 6655: sub scantron_remove_file {
1.192     albertel 6656:     my ($which)=@_;
1.257     albertel 6657:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6658:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6659:     my $file='scantron_';
1.200     albertel 6660:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6661: 	$file.=$which.'_';
1.192     albertel 6662:     } else {
                   6663: 	return 'refused';
                   6664:     }
1.257     albertel 6665:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6666:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6667: }
                   6668: 
1.423     albertel 6669: 
                   6670: =pod
                   6671: 
                   6672: =item scantron_remove_scan_data
                   6673: 
1.659     raeburn  6674:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6675:    data file.  (In the case that both the are doing skipped records we need
                   6676:    to remember the old skipped lines for the time being so that element
                   6677:    persists for a while.)
                   6678: 
1.423     albertel 6679: =cut
                   6680: 
1.200     albertel 6681: sub scantron_remove_scan_data {
1.257     albertel 6682:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6684:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6685:     my @todelete;
1.257     albertel 6686:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6687:     foreach my $key (@keys) {
                   6688: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6689: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6690: 		$key=~/remember_skipping/) {
                   6691: 		next;
                   6692: 	    }
1.192     albertel 6693: 	    push(@todelete,$key);
                   6694: 	}
                   6695:     }
1.200     albertel 6696:     my $result;
1.192     albertel 6697:     if (@todelete) {
1.491     albertel 6698: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6699: 				       \@todelete,$cdom,$cname);
                   6700:     } else {
                   6701: 	$result = 'ok';
1.192     albertel 6702:     }
                   6703:     return $result;
                   6704: }
                   6705: 
1.423     albertel 6706: 
                   6707: =pod
                   6708: 
                   6709: =item scantron_getfile
                   6710: 
1.659     raeburn  6711:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6712:     the scan_data hash
                   6713:   
                   6714:   Arguments:
                   6715:     None
                   6716: 
                   6717:   Returns:
                   6718:     2 hash references
                   6719: 
                   6720:      - first one has 
                   6721:          orig      -
                   6722:          corrected -
                   6723:          skipped   -  each of which points to an array ref of the specified
                   6724:                       file broken up into individual lines
                   6725:          count     - number of scanlines
                   6726:  
                   6727:      - second is the scan_data hash possible keys are
1.425     albertel 6728:        ($number refers to scanline numbered $number and thus the key affects
                   6729:         only that scanline
                   6730:         $bubline refers to the specific bubble line element and the aspects
                   6731:         refers to that specific bubble line element)
                   6732: 
                   6733:        $number.user - username:domain to use
                   6734:        $number.CODE_ignore_dup 
                   6735:                     - ignore the duplicate CODE error 
                   6736:        $number.useCODE
                   6737:                     - use the CODE in the scanline as is
                   6738:        $number.no_bubble.$bubline
                   6739:                     - it is valid that there is no bubbled in bubble
                   6740:                       at $number $bubline
                   6741:        remember_skipping
                   6742:                     - a frozen hash containing keys of $number and values
                   6743:                       of either 
                   6744:                         1 - we are on a 'do skipped records pass' and plan
                   6745:                             on processing this line
                   6746:                         2 - we are on a 'do skipped records pass' and this
                   6747:                             scanline has been marked to skip yet again
1.424     albertel 6748: 
1.423     albertel 6749: =cut
                   6750: 
1.157     albertel 6751: sub scantron_getfile {
1.200     albertel 6752:     #FIXME really would prefer a scantron directory
1.257     albertel 6753:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6754:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6755:     my $lines;
                   6756:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6757: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6758:     my %scanlines;
                   6759:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6760:     my $temp=$scanlines{'orig'};
                   6761:     $scanlines{'count'}=$#$temp;
                   6762: 
                   6763:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6764: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6765:     if ($lines eq '-1') {
                   6766: 	$scanlines{'corrected'}=[];
                   6767:     } else {
                   6768: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6769:     }
                   6770:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6771: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6772:     if ($lines eq '-1') {
                   6773: 	$scanlines{'skipped'}=[];
                   6774:     } else {
                   6775: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6776:     }
1.175     albertel 6777:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6778:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6779:     my %scan_data = @tmp;
                   6780:     return (\%scanlines,\%scan_data);
                   6781: }
                   6782: 
1.423     albertel 6783: =pod
                   6784: 
                   6785: =item lonnet_putfile
                   6786: 
1.424     albertel 6787:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6788: 
                   6789:  Arguments:
                   6790:    $contents - data to store
                   6791:    $filename - filename to store $contents into
                   6792: 
                   6793:  Returns:
                   6794:    result value from &Apache::lonnet::finishuserfileupload
                   6795: 
1.423     albertel 6796: =cut
                   6797: 
1.157     albertel 6798: sub lonnet_putfile {
                   6799:     my ($contents,$filename)=@_;
1.257     albertel 6800:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6801:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6802:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6803:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6804: 
                   6805: }
                   6806: 
1.423     albertel 6807: =pod
                   6808: 
                   6809: =item scantron_putfile
                   6810: 
1.659     raeburn  6811:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6812:     scan_data hash. (Does not modify the original version only the
                   6813:     corrected and skipped versions.
                   6814: 
                   6815:  Arguments:
                   6816:     $scanlines - hash ref that looks like the first return value from
                   6817:                  &scantron_getfile()
                   6818:     $scan_data - hash ref that looks like the second return value from
                   6819:                  &scantron_getfile()
                   6820: 
1.423     albertel 6821: =cut
                   6822: 
1.157     albertel 6823: sub scantron_putfile {
                   6824:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6825:     #FIXME really would prefer a scantron directory
1.257     albertel 6826:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6827:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6828:     if ($scanlines) {
                   6829: 	my $prefix='scantron_';
1.157     albertel 6830: # no need to update orig, shouldn't change
                   6831: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6832: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6833: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6834: 			$prefix.'corrected_'.
1.257     albertel 6835: 			$env{'form.scantron_selectfile'});
1.200     albertel 6836: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6837: 			$prefix.'skipped_'.
1.257     albertel 6838: 			$env{'form.scantron_selectfile'});
1.200     albertel 6839:     }
1.175     albertel 6840:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6841: }
                   6842: 
1.423     albertel 6843: =pod
                   6844: 
                   6845: =item scantron_get_line
                   6846: 
1.424     albertel 6847:    Returns the correct version of the scanline
                   6848: 
                   6849:  Arguments:
                   6850:     $scanlines - hash ref that looks like the first return value from
                   6851:                  &scantron_getfile()
                   6852:     $scan_data - hash ref that looks like the second return value from
                   6853:                  &scantron_getfile()
                   6854:     $i         - number of the requested line (starts at 0)
                   6855: 
                   6856:  Returns:
                   6857:    A scanline, (either the original or the corrected one if it
                   6858:    exists), or undef if the requested scanline should be
                   6859:    skipped. (Either because it's an skipped scanline, or it's an
                   6860:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6861:    pass.
                   6862: 
1.423     albertel 6863: =cut
                   6864: 
1.157     albertel 6865: sub scantron_get_line {
1.200     albertel 6866:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6867:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6868:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6869:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6870:     return $scanlines->{'orig'}[$i]; 
                   6871: }
                   6872: 
1.423     albertel 6873: =pod
                   6874: 
                   6875: =item scantron_todo_count
                   6876: 
1.424     albertel 6877:     Counts the number of scanlines that need processing.
                   6878: 
                   6879:  Arguments:
                   6880:     $scanlines - hash ref that looks like the first return value from
                   6881:                  &scantron_getfile()
                   6882:     $scan_data - hash ref that looks like the second return value from
                   6883:                  &scantron_getfile()
                   6884: 
                   6885:  Returns:
                   6886:     $count - number of scanlines to process
                   6887: 
1.423     albertel 6888: =cut
                   6889: 
1.200     albertel 6890: sub get_todo_count {
                   6891:     my ($scanlines,$scan_data)=@_;
                   6892:     my $count=0;
                   6893:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6894: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6895: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6896: 	$count++;
                   6897:     }
                   6898:     return $count;
                   6899: }
                   6900: 
1.423     albertel 6901: =pod
                   6902: 
                   6903: =item scantron_put_line
                   6904: 
1.659     raeburn  6905:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 6906:     data file.
                   6907: 
                   6908:  Arguments:
                   6909:     $scanlines - hash ref that looks like the first return value from
                   6910:                  &scantron_getfile()
                   6911:     $scan_data - hash ref that looks like the second return value from
                   6912:                  &scantron_getfile()
                   6913:     $i         - line number to update
                   6914:     $newline   - contents of the updated scanline
                   6915:     $skip      - if true make the line for skipping and update the
                   6916:                  'skipped' file
                   6917: 
1.423     albertel 6918: =cut
                   6919: 
1.157     albertel 6920: sub scantron_put_line {
1.200     albertel 6921:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6922:     if ($skip) {
                   6923: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6924: 	&start_skipping($scan_data,$i);
1.157     albertel 6925: 	return;
                   6926:     }
                   6927:     $scanlines->{'corrected'}[$i]=$newline;
                   6928: }
                   6929: 
1.423     albertel 6930: =pod
                   6931: 
                   6932: =item scantron_clear_skip
                   6933: 
1.424     albertel 6934:    Remove a line from the 'skipped' file
                   6935: 
                   6936:  Arguments:
                   6937:     $scanlines - hash ref that looks like the first return value from
                   6938:                  &scantron_getfile()
                   6939:     $scan_data - hash ref that looks like the second return value from
                   6940:                  &scantron_getfile()
                   6941:     $i         - line number to update
                   6942: 
1.423     albertel 6943: =cut
                   6944: 
1.376     albertel 6945: sub scantron_clear_skip {
                   6946:     my ($scanlines,$scan_data,$i)=@_;
                   6947:     if (exists($scanlines->{'skipped'}[$i])) {
                   6948: 	undef($scanlines->{'skipped'}[$i]);
                   6949: 	return 1;
                   6950:     }
                   6951:     return 0;
                   6952: }
                   6953: 
1.423     albertel 6954: =pod
                   6955: 
                   6956: =item scantron_filter_not_exam
                   6957: 
1.424     albertel 6958:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6959:    filter out resources that are not marked as 'exam' mode
                   6960: 
1.423     albertel 6961: =cut
                   6962: 
1.334     albertel 6963: sub scantron_filter_not_exam {
                   6964:     my ($curres)=@_;
                   6965:     
                   6966:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6967: 	# if the user has asked to not have either hidden
                   6968: 	# or 'randomout' controlled resources to be graded
                   6969: 	# don't include them
                   6970: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6971: 	    && $curres->randomout) {
                   6972: 	    return 0;
                   6973: 	}
                   6974: 	return 1;
                   6975:     }
                   6976:     return 0;
                   6977: }
                   6978: 
1.423     albertel 6979: =pod
                   6980: 
                   6981: =item scantron_validate_sequence
                   6982: 
1.424     albertel 6983:     Validates the selected sequence, checking for resource that are
                   6984:     not set to exam mode.
                   6985: 
1.423     albertel 6986: =cut
                   6987: 
1.334     albertel 6988: sub scantron_validate_sequence {
                   6989:     my ($r,$currentphase) = @_;
                   6990: 
                   6991:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6992:     unless (ref($navmap)) {
                   6993:         $r->print(&navmap_errormsg());
                   6994:         return (1,$currentphase);
                   6995:     }
1.334     albertel 6996:     my (undef,undef,$sequence)=
                   6997: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6998: 
                   6999:     my $map=$navmap->getResourceByUrl($sequence);
                   7000: 
                   7001:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7002:                                     value="ignore" />');
                   7003:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7004: 	my @resources=
                   7005: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7006: 	if (@resources) {
1.357     banghart 7007: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 7008: 	    return (1,$currentphase);
                   7009: 	}
                   7010:     }
                   7011: 
                   7012:     return (0,$currentphase+1);
                   7013: }
                   7014: 
1.423     albertel 7015: 
                   7016: 
1.157     albertel 7017: sub scantron_validate_ID {
                   7018:     my ($r,$currentphase) = @_;
                   7019:     
                   7020:     #get student info
                   7021:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7022:     my %idmap=&username_to_idmap($classlist);
                   7023: 
                   7024:     #get scantron line setup
1.257     albertel 7025:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7026:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7027: 
                   7028:     my $nav_error;
1.649     raeburn  7029:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7030:     if ($nav_error) {
                   7031:         $r->print(&navmap_errormsg());
                   7032:         return(1,$currentphase);
                   7033:     }
1.157     albertel 7034: 
                   7035:     my %found=('ids'=>{},'usernames'=>{});
                   7036:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7037: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7038: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7039: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7040: 						 $scan_data);
                   7041: 	my $id=$$scan_record{'scantron.ID'};
                   7042: 	my $found;
                   7043: 	foreach my $checkid (keys(%idmap)) {
                   7044: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7045: 	}
                   7046: 	if ($found) {
                   7047: 	    my $username=$idmap{$found};
                   7048: 	    if ($found{'ids'}{$found}) {
                   7049: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7050: 					 $line,'duplicateID',$found);
1.194     albertel 7051: 		return(1,$currentphase);
1.157     albertel 7052: 	    } elsif ($found{'usernames'}{$username}) {
                   7053: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7054: 					 $line,'duplicateID',$username);
1.194     albertel 7055: 		return(1,$currentphase);
1.157     albertel 7056: 	    }
1.186     albertel 7057: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7058: 	    $found{'ids'}{$found}++;
                   7059: 	    $found{'usernames'}{$username}++;
                   7060: 	} else {
                   7061: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7062: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7063: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7064: 		    &scantron_get_correction($r,$i,$scan_record,
                   7065: 					     \%scantron_config,
                   7066: 					     $line,'duplicateID',$username);
1.194     albertel 7067: 		    return(1,$currentphase);
1.157     albertel 7068: 		} elsif (!defined($username)) {
                   7069: 		    &scantron_get_correction($r,$i,$scan_record,
                   7070: 					     \%scantron_config,
                   7071: 					     $line,'incorrectID');
1.194     albertel 7072: 		    return(1,$currentphase);
1.157     albertel 7073: 		}
                   7074: 		$found{'usernames'}{$username}++;
                   7075: 	    } else {
                   7076: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7077: 					 $line,'incorrectID');
1.194     albertel 7078: 		return(1,$currentphase);
1.157     albertel 7079: 	    }
                   7080: 	}
                   7081:     }
                   7082: 
                   7083:     return (0,$currentphase+1);
                   7084: }
                   7085: 
1.423     albertel 7086: 
1.157     albertel 7087: sub scantron_get_correction {
                   7088:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 7089: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7090: #to show both the current line and the previous one and allow skipping
                   7091: #the previous one or the current one
                   7092: 
1.333     albertel 7093:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7094:         $r->print(
                   7095:             '<p class="LC_warning">'
                   7096:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7097:                 "<b>$error</b>",
                   7098:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7099:            ."</p> \n");
1.157     albertel 7100:     } else {
1.658     bisitz   7101:         $r->print(
                   7102:             '<p class="LC_warning">'
                   7103:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7104:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7105:            ."</p> \n");
                   7106:     }
                   7107:     my $message =
                   7108:         '<p>'
                   7109:        .&mt('The ID on the form is [_1]',
                   7110:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7111:        .'<br />'
1.665     raeburn  7112:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7113:             $$scan_record{'scantron.LastName'},
                   7114:             $$scan_record{'scantron.FirstName'})
                   7115:        .'</p>';
1.242     albertel 7116: 
1.157     albertel 7117:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7118:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7119:                            # Array populated for doublebubble or
                   7120:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7121:                            # to validate radio button checking   
                   7122: 
1.157     albertel 7123:     if ($error =~ /ID$/) {
1.186     albertel 7124: 	if ($error eq 'incorrectID') {
1.658     bisitz   7125:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7126: 		      "</p>\n");
1.157     albertel 7127: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7128:             $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 7129: 	}
1.242     albertel 7130: 	$r->print($message);
1.492     albertel 7131: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7132: 	$r->print("\n<ul><li> ");
                   7133: 	#FIXME it would be nice if this sent back the user ID and
                   7134: 	#could do partial userID matches
                   7135: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7136: 				       'scantron_username','scantron_domain'));
                   7137: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   7138: 	$r->print("\n@".
1.257     albertel 7139: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7140: 
                   7141: 	$r->print('</li>');
1.186     albertel 7142:     } elsif ($error =~ /CODE$/) {
                   7143: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7144: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7145: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7146: 	    $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 7147: 	}
1.658     bisitz   7148: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7149: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7150:                  ."</p>\n");
1.242     albertel 7151: 	$r->print($message);
1.658     bisitz   7152: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7153: 	$r->print("\n<br /> ");
1.194     albertel 7154: 	my $i=0;
1.273     albertel 7155: 	if ($error eq 'incorrectCODE' 
                   7156: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7157: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7158: 	    if ($closest > 0) {
                   7159: 		foreach my $testcode (@{$closest}) {
                   7160: 		    my $checked='';
1.569     bisitz   7161: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7162: 		    $r->print("
                   7163:    <label>
1.569     bisitz   7164:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7165:        ".&mt("Use the similar CODE [_1] instead.",
                   7166: 	    "<b><tt>".$testcode."</tt></b>")."
                   7167:     </label>
                   7168:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7169: 		    $r->print("\n<br />");
                   7170: 		    $i++;
                   7171: 		}
1.194     albertel 7172: 	    }
                   7173: 	}
1.273     albertel 7174: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7175: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7176: 	    $r->print("
                   7177:     <label>
1.569     bisitz   7178:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7179:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7180: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7181:     </label>");
1.273     albertel 7182: 	    $r->print("\n<br />");
                   7183: 	}
1.194     albertel 7184: 
1.597     wenzelju 7185: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7186: function change_radio(field) {
1.190     albertel 7187:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7188:     var i;
                   7189:     for (i=0;i<slct.length;i++) {
                   7190:         if (slct[i].value==field) { slct[i].checked=true; }
                   7191:     }
                   7192: }
                   7193: ENDSCRIPT
1.187     albertel 7194: 	my $href="/adm/pickcode?".
1.359     www      7195: 	   "form=".&escape("scantronupload").
                   7196: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7197: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7198: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7199: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7200: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7201: 	    $r->print("
                   7202:     <label>
                   7203:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7204:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7205: 	     "<a target='_blank' href='$href'>","</a>")."
                   7206:     </label> 
1.558     bisitz   7207:     ".&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 7208: 	    $r->print("\n<br />");
                   7209: 	}
1.492     albertel 7210: 	$r->print("
                   7211:     <label>
                   7212:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7213:        ".&mt("Use [_1] as the CODE.",
                   7214: 	     "</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 7215: 	$r->print("\n<br /><br />");
1.157     albertel 7216:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7217: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7218: 
                   7219: 	# The form field scantron_questions is acutally a list of line numbers.
                   7220: 	# represented by this form so:
                   7221: 
                   7222: 	my $line_list = &questions_to_line_list($arg);
                   7223: 
1.157     albertel 7224: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7225: 		  $line_list.'" />');
1.242     albertel 7226: 	$r->print($message);
1.492     albertel 7227: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7228: 	foreach my $question (@{$arg}) {
1.503     raeburn  7229: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7230:                                                    $scan_record, $error);
1.524     raeburn  7231:             push(@lines_to_correct,@linenums);
1.157     albertel 7232: 	}
1.503     raeburn  7233:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7234:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7235: 	$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 7236: 	$r->print($message);
1.492     albertel 7237: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7238: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7239: 
1.503     raeburn  7240: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7241: 	# a list of question numbers. Therefore:
                   7242: 	#
                   7243: 	
                   7244: 	my $line_list = &questions_to_line_list($arg);
                   7245: 
1.157     albertel 7246: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7247: 		  $line_list.'" />');
1.157     albertel 7248: 	foreach my $question (@{$arg}) {
1.503     raeburn  7249: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7250:                                                    $scan_record, $error);
1.524     raeburn  7251:             push(@lines_to_correct,@linenums);
1.157     albertel 7252: 	}
1.503     raeburn  7253:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7254:     } else {
                   7255: 	$r->print("\n<ul>");
                   7256:     }
                   7257:     $r->print("\n</li></ul>");
1.497     foxr     7258: }
                   7259: 
1.503     raeburn  7260: sub verify_bubbles_checked {
                   7261:     my (@ansnums) = @_;
                   7262:     my $ansnumstr = join('","',@ansnums);
                   7263:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7264:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7265: function verify_bubble_radio(form) {
                   7266:     var ansnumArray = new Array ("$ansnumstr");
                   7267:     var need_bubble_count = 0;
                   7268:     for (var i=0; i<ansnumArray.length; i++) {
                   7269:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7270:             var bubble_picked = 0; 
                   7271:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7272:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7273:                     bubble_picked = 1;
                   7274:                 }
                   7275:             }
                   7276:             if (bubble_picked == 0) {
                   7277:                 need_bubble_count ++;
                   7278:             }
                   7279:         }
                   7280:     }
                   7281:     if (need_bubble_count) {
                   7282:         alert("$warning");
                   7283:         return;
                   7284:     }
                   7285:     form.submit(); 
                   7286: }
                   7287: ENDSCRIPT
                   7288:     return $output;
                   7289: }
                   7290: 
1.497     foxr     7291: =pod
                   7292: 
                   7293: =item  questions_to_line_list
1.157     albertel 7294: 
1.497     foxr     7295: Converts a list of questions into a string of comma separated
                   7296: line numbers in the answer sheet used by the questions.  This is
                   7297: used to fill in the scantron_questions form field.
                   7298: 
                   7299:   Arguments:
                   7300:      questions    - Reference to an array of questions.
                   7301: 
                   7302: =cut
                   7303: 
                   7304: 
                   7305: sub questions_to_line_list {
                   7306:     my ($questions) = @_;
                   7307:     my @lines;
                   7308: 
1.503     raeburn  7309:     foreach my $item (@{$questions}) {
                   7310:         my $question = $item;
                   7311:         my ($first,$count,$last);
                   7312:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7313:             $question = $1;
                   7314:             my $subquestion = $2;
                   7315:             $first = $first_bubble_line{$question-1} + 1;
                   7316:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7317:             my $subcount = 1;
                   7318:             while ($subcount<$subquestion) {
                   7319:                 $first += $subans[$subcount-1];
                   7320:                 $subcount ++;
                   7321:             }
                   7322:             $count = $subans[$subquestion-1];
                   7323:         } else {
                   7324: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7325: 	    $count   = $bubble_lines_per_response{$question-1};
                   7326:         }
1.506     raeburn  7327:         $last = $first+$count-1;
1.503     raeburn  7328:         push(@lines, ($first..$last));
1.497     foxr     7329:     }
                   7330:     return join(',', @lines);
                   7331: }
                   7332: 
                   7333: =pod 
                   7334: 
                   7335: =item prompt_for_corrections
                   7336: 
                   7337: Prompts for a potentially multiline correction to the
                   7338: user's bubbling (factors out common code from scantron_get_correction
                   7339: for multi and missing bubble cases).
                   7340: 
                   7341:  Arguments:
                   7342:    $r           - Apache request object.
                   7343:    $question    - The question number to prompt for.
                   7344:    $scan_config - The scantron file configuration hash.
                   7345:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7346:    $error       - Type of error
1.497     foxr     7347: 
                   7348:  Implicit inputs:
                   7349:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7350:                                   Numbered from 0 (but question numbers are from
                   7351:                                   1.
                   7352:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7353:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7354:                                   type problems render as separate sub-questions, 
1.503     raeburn  7355:                                   in exam mode. This hash contains a 
                   7356:                                   comma-separated list of the lines per 
                   7357:                                   sub-question.
1.510     raeburn  7358:    %responsetype_per_response   - essayresponse, formularesponse,
                   7359:                                   stringresponse, imageresponse, reactionresponse,
                   7360:                                   and organicresponse type problem parts can have
1.503     raeburn  7361:                                   multiple lines per response if the weight
                   7362:                                   assigned exceeds 10.  In this case, only
                   7363:                                   one bubble per line is permitted, but more 
                   7364:                                   than one line might contain bubbles, e.g.
                   7365:                                   bubbling of: line 1 - J, line 2 - J, 
                   7366:                                   line 3 - B would assign 22 points.  
1.497     foxr     7367: 
                   7368: =cut
                   7369: 
                   7370: sub prompt_for_corrections {
1.503     raeburn  7371:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7372:     my ($current_line,$lines);
                   7373:     my @linenums;
                   7374:     my $questionnum = $question;
                   7375:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7376:         $question = $1;
                   7377:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7378:         my $subquestion = $2;
                   7379:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7380:         my $subcount = 1;
                   7381:         while ($subcount<$subquestion) {
                   7382:             $current_line += $subans[$subcount-1];
                   7383:             $subcount ++;
                   7384:         }
                   7385:         $lines = $subans[$subquestion-1];
                   7386:     } else {
                   7387:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7388:         $lines        = $bubble_lines_per_response{$question-1};
                   7389:     }
1.497     foxr     7390:     if ($lines > 1) {
1.503     raeburn  7391:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7392:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7393:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7394:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7395:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7396:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7397:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7398:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&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.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7399:         } else {
                   7400:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7401:         }
1.497     foxr     7402:     }
                   7403:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7404:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7405: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7406: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7407:         push(@linenums,$current_line);
1.497     foxr     7408: 	$current_line++;
                   7409:     }
                   7410:     if ($lines > 1) {
                   7411: 	$r->print("<hr /><br />");
                   7412:     }
1.503     raeburn  7413:     return @linenums;
1.157     albertel 7414: }
1.423     albertel 7415: 
                   7416: =pod
                   7417: 
                   7418: =item scantron_bubble_selector
                   7419:   
                   7420:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7421:    possibly showing the existing the selected bubbles if known
1.423     albertel 7422: 
                   7423:  Arguments:
                   7424:     $r           - Apache request object
                   7425:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7426:     $line        - Number of the line being displayed.
1.503     raeburn  7427:     $questionnum - Question number (may include subquestion)
                   7428:     $error       - Type of error.
1.497     foxr     7429:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7430: 
                   7431: =cut
                   7432: 
1.157     albertel 7433: sub scantron_bubble_selector {
1.503     raeburn  7434:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7435:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7436: 
                   7437:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7438:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7439:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7440:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7441:             $max=$$scan_config{'BubblesPerRow'};
                   7442:             if (($scmode eq 'number') && ($max > 10)) {
                   7443:                 $max = 10;
                   7444:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7445:                 $max = 26;
                   7446:             }
                   7447:         } else {
                   7448:             $max = 10;
                   7449:         }
                   7450:     }
1.274     albertel 7451: 
1.157     albertel 7452:     my @alphabet=('A'..'Z');
1.503     raeburn  7453:     $r->print(&Apache::loncommon::start_data_table().
                   7454:               &Apache::loncommon::start_data_table_row());
                   7455:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7456:     for (my $i=0;$i<$max+1;$i++) {
                   7457: 	$r->print("\n".'<td align="center">');
                   7458: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7459: 	else { $r->print('&nbsp;'); }
                   7460: 	$r->print('</td>');
                   7461:     }
1.503     raeburn  7462:     $r->print(&Apache::loncommon::end_data_table_row().
                   7463:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7464:     for (my $i=0;$i<$max;$i++) {
                   7465: 	$r->print("\n".
                   7466: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7467: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7468:     }
1.503     raeburn  7469:     my $nobub_checked = ' ';
                   7470:     if ($error eq 'missingbubble') {
                   7471:         $nobub_checked = ' checked = "checked" ';
                   7472:     }
                   7473:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7474: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7475:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7476:               $line.'" value="'.$questionnum.'" /></td>');
                   7477:     $r->print(&Apache::loncommon::end_data_table_row().
                   7478:               &Apache::loncommon::end_data_table());
1.157     albertel 7479: }
                   7480: 
1.423     albertel 7481: =pod
                   7482: 
                   7483: =item num_matches
                   7484: 
1.424     albertel 7485:    Counts the number of characters that are the same between the two arguments.
                   7486: 
                   7487:  Arguments:
                   7488:    $orig - CODE from the scanline
                   7489:    $code - CODE to match against
                   7490: 
                   7491:  Returns:
                   7492:    $count - integer count of the number of same characters between the
                   7493:             two arguments
                   7494: 
1.423     albertel 7495: =cut
                   7496: 
1.194     albertel 7497: sub num_matches {
                   7498:     my ($orig,$code) = @_;
                   7499:     my @code=split(//,$code);
                   7500:     my @orig=split(//,$orig);
                   7501:     my $same=0;
                   7502:     for (my $i=0;$i<scalar(@code);$i++) {
                   7503: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7504:     }
                   7505:     return $same;
                   7506: }
                   7507: 
1.423     albertel 7508: =pod
                   7509: 
                   7510: =item scantron_get_closely_matching_CODEs
                   7511: 
1.424     albertel 7512:    Cycles through all CODEs and finds the set that has the greatest
                   7513:    number of same characters as the provided CODE
                   7514: 
                   7515:  Arguments:
                   7516:    $allcodes - hash ref returned by &get_codes()
                   7517:    $CODE     - CODE from the current scanline
                   7518: 
                   7519:  Returns:
                   7520:    2 element list
                   7521:     - first elements is number of how closely matching the best fit is 
                   7522:       (5 means best set has 5 matching characters)
                   7523:     - second element is an arrary ref containing the set of valid CODEs
                   7524:       that best fit the passed in CODE
                   7525: 
1.423     albertel 7526: =cut
                   7527: 
1.194     albertel 7528: sub scantron_get_closely_matching_CODEs {
                   7529:     my ($allcodes,$CODE)=@_;
                   7530:     my @CODEs;
                   7531:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7532: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7533:     }
                   7534: 
                   7535:     return ($#CODEs,$CODEs[-1]);
                   7536: }
                   7537: 
1.423     albertel 7538: =pod
                   7539: 
                   7540: =item get_codes
                   7541: 
1.424     albertel 7542:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7543:    set of remembered CODEs.
                   7544: 
                   7545:  Arguments:
                   7546:   $old_name - name of the set of remembered CODEs
                   7547:   $cdom     - domain of the course
                   7548:   $cnum     - internal course name
                   7549: 
                   7550:  Returns:
                   7551:   %allcodes - keys are the valid CODEs, values are all 1
                   7552: 
1.423     albertel 7553: =cut
                   7554: 
1.194     albertel 7555: sub get_codes {
1.280     foxr     7556:     my ($old_name, $cdom, $cnum) = @_;
                   7557:     if (!$old_name) {
                   7558: 	$old_name=$env{'form.scantron_CODElist'};
                   7559:     }
                   7560:     if (!$cdom) {
                   7561: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7562:     }
                   7563:     if (!$cnum) {
                   7564: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7565:     }
1.278     albertel 7566:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7567: 				    $cdom,$cnum);
                   7568:     my %allcodes;
                   7569:     if ($result{"type\0$old_name"} eq 'number') {
                   7570: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7571:     } else {
                   7572: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7573:     }
1.194     albertel 7574:     return %allcodes;
                   7575: }
                   7576: 
1.423     albertel 7577: =pod
                   7578: 
                   7579: =item scantron_validate_CODE
                   7580: 
1.424     albertel 7581:    Validates all scanlines in the selected file to not have any
                   7582:    invalid or underspecified CODEs and that none of the codes are
                   7583:    duplicated if this was requested.
                   7584: 
1.423     albertel 7585: =cut
                   7586: 
1.157     albertel 7587: sub scantron_validate_CODE {
                   7588:     my ($r,$currentphase) = @_;
1.257     albertel 7589:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7590:     if ($scantron_config{'CODElocation'} &&
                   7591: 	$scantron_config{'CODEstart'} &&
                   7592: 	$scantron_config{'CODElength'}) {
1.257     albertel 7593: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7594: 	    &FIXME_blow_up()
                   7595: 	}
                   7596:     } else {
                   7597: 	return (0,$currentphase+1);
                   7598:     }
                   7599:     
                   7600:     my %usedCODEs;
                   7601: 
1.194     albertel 7602:     my %allcodes=&get_codes();
1.186     albertel 7603: 
1.582     raeburn  7604:     my $nav_error;
1.649     raeburn  7605:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7606:     if ($nav_error) {
                   7607:         $r->print(&navmap_errormsg());
                   7608:         return(1,$currentphase);
                   7609:     }
1.447     foxr     7610: 
1.186     albertel 7611:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7612:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7613: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7614: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7615: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7616: 						 $scan_data);
                   7617: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7618: 	my $error=0;
1.224     albertel 7619: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7620: 	    &scantron_get_correction($r,$i,$scan_record,
                   7621: 				     \%scantron_config,
                   7622: 				     $line,'incorrectCODE',\%allcodes);
                   7623: 	    return(1,$currentphase);
                   7624: 	}
1.221     albertel 7625: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7626: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7627: 	    &scantron_get_correction($r,$i,$scan_record,
                   7628: 				     \%scantron_config,
1.194     albertel 7629: 				     $line,'incorrectCODE',\%allcodes);
                   7630: 	    return(1,$currentphase);
1.186     albertel 7631: 	}
1.214     albertel 7632: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7633: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7634: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7635: 	    &scantron_get_correction($r,$i,$scan_record,
                   7636: 				     \%scantron_config,
1.194     albertel 7637: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7638: 	    return(1,$currentphase);
1.186     albertel 7639: 	}
1.524     raeburn  7640: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7641:     }
1.157     albertel 7642:     return (0,$currentphase+1);
                   7643: }
                   7644: 
1.423     albertel 7645: =pod
                   7646: 
                   7647: =item scantron_validate_doublebubble
                   7648: 
1.424     albertel 7649:    Validates all scanlines in the selected file to not have any
                   7650:    bubble lines with multiple bubbles marked.
                   7651: 
1.423     albertel 7652: =cut
                   7653: 
1.157     albertel 7654: sub scantron_validate_doublebubble {
                   7655:     my ($r,$currentphase) = @_;
                   7656:     #get student info
                   7657:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7658:     my %idmap=&username_to_idmap($classlist);
                   7659: 
                   7660:     #get scantron line setup
1.257     albertel 7661:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7662:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7663:     my $nav_error;
1.649     raeburn  7664:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7665:     if ($nav_error) {
                   7666:         $r->print(&navmap_errormsg());
                   7667:         return(1,$currentphase);
                   7668:     }
1.447     foxr     7669: 
1.157     albertel 7670:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7671: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7672: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7673: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7674: 						 $scan_data);
                   7675: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7676: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7677: 				 'doublebubble',
                   7678: 				 $$scan_record{'scantron.doubleerror'});
                   7679:     	return (1,$currentphase);
                   7680:     }
                   7681:     return (0,$currentphase+1);
                   7682: }
                   7683: 
1.423     albertel 7684: 
1.503     raeburn  7685: sub scantron_get_maxbubble {
1.649     raeburn  7686:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7687:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7688: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7689: 	&restore_bubble_lines();
1.257     albertel 7690: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7691:     }
1.330     albertel 7692: 
1.447     foxr     7693:     my (undef, undef, $sequence) =
1.257     albertel 7694: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7695: 
1.447     foxr     7696:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7697:     unless (ref($navmap)) {
                   7698:         if (ref($nav_error)) {
                   7699:             $$nav_error = 1;
                   7700:         }
1.591     raeburn  7701:         return;
1.582     raeburn  7702:     }
1.191     albertel 7703:     my $map=$navmap->getResourceByUrl($sequence);
                   7704:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7705:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7706: 
                   7707:     &Apache::lonxml::clear_problem_counter();
                   7708: 
1.557     raeburn  7709:     my $uname       = $env{'user.name'};
                   7710:     my $udom        = $env{'user.domain'};
1.435     foxr     7711:     my $cid         = $env{'request.course.id'};
                   7712:     my $total_lines = 0;
                   7713:     %bubble_lines_per_response = ();
1.447     foxr     7714:     %first_bubble_line         = ();
1.503     raeburn  7715:     %subdivided_bubble_lines   = ();
                   7716:     %responsetype_per_response = ();
1.554     raeburn  7717: 
1.447     foxr     7718:     my $response_number = 0;
                   7719:     my $bubble_line     = 0;
1.191     albertel 7720:     foreach my $resource (@resources) {
1.672     raeburn  7721:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7722:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  7723:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7724: 	    foreach my $part_id (@{$parts}) {
                   7725:                 my $lines;
                   7726: 
                   7727: 	        # TODO - make this a persistent hash not an array.
                   7728: 
                   7729:                 # optionresponse, matchresponse and rankresponse type items 
                   7730:                 # render as separate sub-questions in exam mode.
                   7731:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7732:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7733:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7734:                     my ($numbub,$numshown);
                   7735:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7736:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7737:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7738:                         }
                   7739:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7740:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7741:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7742:                         }
                   7743:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7744:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7745:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7746:                         }
                   7747:                     }
                   7748:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7749:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7750:                     }
1.649     raeburn  7751:                     my $bubbles_per_row =
                   7752:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7753:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7754:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7755:                         $inner_bubble_lines++;
                   7756:                     }
                   7757:                     for (my $i=0; $i<$numshown; $i++) {
                   7758:                         $subdivided_bubble_lines{$response_number} .= 
                   7759:                             $inner_bubble_lines.',';
                   7760:                     }
                   7761:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7762:                     $lines = $numshown * $inner_bubble_lines;
                   7763:                 } else {
                   7764:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7765:                 }
1.542     raeburn  7766: 
                   7767:                 $first_bubble_line{$response_number} = $bubble_line;
                   7768: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7769:                 $responsetype_per_response{$response_number} = 
                   7770:                     $analysis->{$part_id.'.type'};
                   7771: 	        $response_number++;
                   7772: 
                   7773: 	        $bubble_line +=  $lines;
                   7774: 	        $total_lines +=  $lines;
                   7775: 	    }
                   7776:         }
                   7777:     }
1.552     raeburn  7778:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7779: 
                   7780:     &save_bubble_lines();
                   7781:     $env{'form.scantron_maxbubble'} =
                   7782: 	$total_lines;
                   7783:     return $env{'form.scantron_maxbubble'};
                   7784: }
1.523     raeburn  7785: 
1.649     raeburn  7786: sub bubblesheet_bubbles_per_row {
                   7787:     my ($scantron_config) = @_;
                   7788:     my $bubbles_per_row;
                   7789:     if (ref($scantron_config) eq 'HASH') {
                   7790:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7791:     }
                   7792:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7793:         $bubbles_per_row = 10;
                   7794:     }
                   7795:     return $bubbles_per_row;
                   7796: }
                   7797: 
1.157     albertel 7798: sub scantron_validate_missingbubbles {
                   7799:     my ($r,$currentphase) = @_;
                   7800:     #get student info
                   7801:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7802:     my %idmap=&username_to_idmap($classlist);
                   7803: 
                   7804:     #get scantron line setup
1.257     albertel 7805:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7806:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7807:     my $nav_error;
1.649     raeburn  7808:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7809:     if ($nav_error) {
                   7810:         return(1,$currentphase);
                   7811:     }
1.157     albertel 7812:     if (!$max_bubble) { $max_bubble=2**31; }
                   7813:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7814: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7815: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7816: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7817: 						 $scan_data);
                   7818: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7819: 	my @to_correct;
1.470     foxr     7820: 	
                   7821: 	# Probably here's where the error is...
                   7822: 
1.157     albertel 7823: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7824:             my $lastbubble;
                   7825:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7826:                my $question = $1;
                   7827:                my $subquestion = $2;
                   7828:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7829:                my $first = $first_bubble_line{$question-1};
                   7830:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7831:                my $subcount = 1;
                   7832:                while ($subcount<$subquestion) {
                   7833:                    $first += $subans[$subcount-1];
                   7834:                    $subcount ++;
                   7835:                }
                   7836:                my $count = $subans[$subquestion-1];
                   7837:                $lastbubble = $first + $count;
                   7838:             } else {
                   7839:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7840:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7841:             }
                   7842:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7843: 	    push(@to_correct,$missing);
                   7844: 	}
                   7845: 	if (@to_correct) {
                   7846: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7847: 				     $line,'missingbubble',\@to_correct);
                   7848: 	    return (1,$currentphase);
                   7849: 	}
                   7850: 
                   7851:     }
                   7852:     return (0,$currentphase+1);
                   7853: }
                   7854: 
1.663     raeburn  7855: sub hand_bubble_option {
                   7856:     my (undef, undef, $sequence) =
                   7857:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7858:     return if ($sequence eq '');
                   7859:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7860:     unless (ref($navmap)) {
                   7861:         return;
                   7862:     }
                   7863:     my $needs_hand_bubbles;
                   7864:     my $map=$navmap->getResourceByUrl($sequence);
                   7865:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7866:     foreach my $res (@resources) {
                   7867:         if (ref($res)) {
                   7868:             if ($res->is_problem()) {
                   7869:                 my $partlist = $res->parts();
                   7870:                 foreach my $part (@{ $partlist }) {
                   7871:                     my @types = $res->responseType($part);
                   7872:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   7873:                         $needs_hand_bubbles = 1;
                   7874:                         last;
                   7875:                     }
                   7876:                 }
                   7877:             }
                   7878:         }
                   7879:     }
                   7880:     if ($needs_hand_bubbles) {
                   7881:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7882:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7883:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   7884:                &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 />').
                   7885:                '<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;'.
                   7886:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   7887:     }
                   7888:     return;
                   7889: }
1.423     albertel 7890: 
1.82      albertel 7891: sub scantron_process_students {
1.608     www      7892:     my ($r,$symb) = @_;
1.513     foxr     7893: 
1.257     albertel 7894:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7895:     if (!$symb) {
                   7896: 	return '';
                   7897:     }
1.324     albertel 7898:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7899: 
1.257     albertel 7900:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7901:     my $bubbles_per_row =
                   7902:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7903:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7904:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7905:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7906:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7907:     unless (ref($navmap)) {
                   7908:         $r->print(&navmap_errormsg());
                   7909:         return '';
                   7910:     }  
1.83      albertel 7911:     my $map=$navmap->getResourceByUrl($sequence);
                   7912:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7913:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7914:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7915:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7916:     my $resource_error;
1.557     raeburn  7917:     foreach my $resource (@resources) {
1.586     raeburn  7918:         my $ressymb;
                   7919:         if (ref($resource)) {
                   7920:             $ressymb = $resource->symb();
                   7921:         } else {
                   7922:             $resource_error = 1;
                   7923:             last;
                   7924:         }
1.557     raeburn  7925:         my ($analysis,$parts) =
                   7926:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  7927:                                       $env{'user.name'},$env{'user.domain'},
                   7928:                                       1,$bubbles_per_row);
1.557     raeburn  7929:         $grader_partids_by_symb{$ressymb} = $parts;
                   7930:         if (ref($analysis) eq 'HASH') {
                   7931:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7932:                 $grader_randomlists_by_symb{$ressymb} = 
                   7933:                     $analysis->{'parts_withrandomlist'};
                   7934:             }
                   7935:         }
                   7936:     }
1.586     raeburn  7937:     if ($resource_error) {
                   7938:         $r->print(&navmap_errormsg());
                   7939:         return '';
                   7940:     }
1.557     raeburn  7941: 
1.554     raeburn  7942:     my ($uname,$udom);
1.82      albertel 7943:     my $result= <<SCANTRONFORM;
1.81      albertel 7944: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7945:   <input type="hidden" name="command" value="scantron_configphase" />
                   7946:   $default_form_data
                   7947: SCANTRONFORM
1.82      albertel 7948:     $r->print($result);
                   7949: 
                   7950:     my @delayqueue;
1.542     raeburn  7951:     my (%completedstudents,%scandata);
1.140     albertel 7952:     
1.520     www      7953:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7954:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      7955:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   7956:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  7957:     $r->print('<br />');
1.140     albertel 7958:     my $start=&Time::HiRes::time();
1.158     albertel 7959:     my $i=-1;
1.542     raeburn  7960:     my $started;
1.447     foxr     7961: 
1.582     raeburn  7962:     my $nav_error;
1.649     raeburn  7963:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7964:     if ($nav_error) {
                   7965:         $r->print(&navmap_errormsg());
                   7966:         return '';
                   7967:     }
                   7968: 
1.513     foxr     7969:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7970:     # the user and return.
                   7971: 
                   7972:     if ($ssi_error) {
                   7973: 	$r->print("</form>");
                   7974: 	&ssi_print_error($r);
1.520     www      7975:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7976: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7977:     }
1.447     foxr     7978: 
1.542     raeburn  7979:     my %lettdig = &letter_to_digits();
                   7980:     my $numletts = scalar(keys(%lettdig));
                   7981: 
1.157     albertel 7982:     while ($i<$scanlines->{'count'}) {
                   7983:  	($uname,$udom)=('','');
                   7984:  	$i++;
1.200     albertel 7985:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7986:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7987: 	if ($started) {
1.667     www      7988: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 7989: 	}
                   7990: 	$started=1;
1.157     albertel 7991:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7992:  						 $scan_data);
                   7993:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7994:  					      \%idmap,$i)) {
                   7995:   	    &scantron_add_delay(\@delayqueue,$line,
                   7996:  				'Unable to find a student that matches',1);
                   7997:  	    next;
                   7998:   	}
                   7999:  	if (exists $completedstudents{$uname}) {
                   8000:  	    &scantron_add_delay(\@delayqueue,$line,
                   8001:  				'Student '.$uname.' has multiple sheets',2);
                   8002:  	    next;
                   8003:  	}
                   8004:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8005: 
1.586     raeburn  8006:         my (%partids_by_symb,$res_error);
1.554     raeburn  8007:         foreach my $resource (@resources) {
1.586     raeburn  8008:             my $ressymb;
                   8009:             if (ref($resource)) {
                   8010:                 $ressymb = $resource->symb();
                   8011:             } else {
                   8012:                 $res_error = 1;
                   8013:                 last;
                   8014:             }
1.557     raeburn  8015:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8016:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8017:                 my ($analysis,$parts) =
1.672     raeburn  8018:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8019:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8020:                 $partids_by_symb{$ressymb} = $parts;
                   8021:             } else {
                   8022:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8023:             }
1.554     raeburn  8024:         }
                   8025: 
1.586     raeburn  8026:         if ($res_error) {
                   8027:             &scantron_add_delay(\@delayqueue,$line,
                   8028:                                 'An error occurred while grading student '.$uname,2);
                   8029:             next;
                   8030:         }
                   8031: 
1.330     albertel 8032: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8033:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8034: 
                   8035: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8036: 	    &scantron_putfile($scanlines,$scan_data);
                   8037: 	}
1.161     albertel 8038: 	
1.542     raeburn  8039:         my $scancode;
                   8040:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8041:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8042:             $scancode = $scan_record->{'scantron.CODE'};
                   8043:         } else {
                   8044:             $scancode = '';
                   8045:         }
                   8046: 
                   8047:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  8048:                                    \@resources,\%partids_by_symb,
                   8049:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  8050:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8051:             $r->print("</form>");
                   8052:             &ssi_print_error($r);
                   8053:             &Apache::lonnet::remove_lock($lock);
                   8054:             return '';      # Why return ''?  Beats me.
                   8055:         }
1.513     foxr     8056: 
1.140     albertel 8057: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8058:         if ($env{'form.verifyrecord'}) {
                   8059:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8060:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8061:             chomp($studentdata);
                   8062:             $studentdata =~ s/\r$//;
                   8063:             my $studentrecord = '';
                   8064:             my $counter = -1;
                   8065:             foreach my $resource (@resources) {
1.554     raeburn  8066:                 my $ressymb = $resource->symb();
1.542     raeburn  8067:                 ($counter,my $recording) =
                   8068:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8069:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  8070:                                              \%scantron_config,\%lettdig,$numletts);
                   8071:                 $studentrecord .= $recording;
                   8072:             }
                   8073:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8074:                 &Apache::lonxml::clear_problem_counter();
                   8075:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  8076:                                            \@resources,\%partids_by_symb,
                   8077:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  8078:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8079:                     $r->print("</form>");
                   8080:                     &ssi_print_error($r);
                   8081:                     &Apache::lonnet::remove_lock($lock);
                   8082:                     delete($completedstudents{$uname});
                   8083:                     return '';
                   8084:                 }
1.542     raeburn  8085:                 $counter = -1;
                   8086:                 $studentrecord = '';
                   8087:                 foreach my $resource (@resources) {
1.554     raeburn  8088:                     my $ressymb = $resource->symb();
1.542     raeburn  8089:                     ($counter,my $recording) =
                   8090:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8091:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  8092:                                                  \%scantron_config,\%lettdig,$numletts);
                   8093:                     $studentrecord .= $recording;
                   8094:                 }
                   8095:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8096:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8097:                     if ($scancode eq '') {
1.658     bisitz   8098:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8099:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8100:                     } else {
1.658     bisitz   8101:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8102:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8103:                     }
                   8104:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8105:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8106:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8107:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8108:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8109:                               '<td>'.&mt('Bubblesheet').'</td>'.
                   8110:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8111:                               &Apache::loncommon::end_data_table_row().
                   8112:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8113:                               '<td>'.&mt('Stored submissions').'</td>'.
                   8114:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8115:                               &Apache::loncommon::end_data_table_row().
                   8116:                               &Apache::loncommon::end_data_table().'</p>');
                   8117:                 } else {
                   8118:                     $r->print('<br /><span class="LC_warning">'.
                   8119:                              &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 />'.
                   8120:                              &mt("As a consequence, this user's submission history records two tries.").
                   8121:                                  '</span><br />');
                   8122:                 }
                   8123:             }
                   8124:         }
1.543     raeburn  8125:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8126:     } continue {
1.330     albertel 8127: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8128: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8129:     }
1.140     albertel 8130:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8131:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8132: #    my $lasttime = &Time::HiRes::time()-$start;
                   8133: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8134: 
1.200     albertel 8135:     $r->print("</form>");
1.157     albertel 8136:     return '';
1.75      albertel 8137: }
1.157     albertel 8138: 
1.557     raeburn  8139: sub graders_resources_pass {
1.649     raeburn  8140:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8141:         $bubbles_per_row) = @_;
1.557     raeburn  8142:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8143:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8144:         foreach my $resource (@{$resources}) {
                   8145:             my $ressymb = $resource->symb();
                   8146:             my ($analysis,$parts) =
                   8147:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8148:                                           $env{'user.name'},$env{'user.domain'},
                   8149:                                           1,$bubbles_per_row);
1.557     raeburn  8150:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8151:             if (ref($analysis) eq 'HASH') {
                   8152:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8153:                     $grader_randomlists_by_symb->{$ressymb} =
                   8154:                         $analysis->{'parts_withrandomlist'};
                   8155:                 }
                   8156:             }
                   8157:         }
                   8158:     }
                   8159:     return;
                   8160: }
                   8161: 
1.542     raeburn  8162: sub grade_student_bubbles {
1.649     raeburn  8163:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   8164: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  8165:     if (ref($resources) eq 'ARRAY') {
                   8166:         my $count = 0;
                   8167:         foreach my $resource (@{$resources}) {
                   8168:             my $ressymb = $resource->symb();
                   8169:             my %form = ('submitted'      => 'scantron',
                   8170:                         'grade_target'   => 'grade',
                   8171:                         'grade_username' => $uname,
                   8172:                         'grade_domain'   => $udom,
                   8173:                         'grade_courseid' => $env{'request.course.id'},
                   8174:                         'grade_symb'     => $ressymb,
                   8175:                         'CODE'           => $scancode
                   8176:                        );
1.649     raeburn  8177:             if ($bubbles_per_row ne '') {
                   8178:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8179:             }
1.663     raeburn  8180:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8181:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8182:             }
1.554     raeburn  8183:             if (ref($parts) eq 'HASH') {
                   8184:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8185:                     foreach my $part (@{$parts->{$ressymb}}) {
                   8186:                         $form{'scantron_questnum_start.'.$part} =
                   8187:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   8188:                         $count++;
                   8189:                     }
                   8190:                 }
                   8191:             }
                   8192:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8193:             return 'ssi_error' if ($ssi_error);
                   8194:             last if (&Apache::loncommon::connection_aborted($r));
                   8195:         }
1.542     raeburn  8196:     }
                   8197:     return;
                   8198: }
                   8199: 
1.157     albertel 8200: sub scantron_upload_scantron_data {
1.608     www      8201:     my ($r,$symb)=@_;
1.565     raeburn  8202:     my $dom = $env{'request.role.domain'};
                   8203:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8204:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8205:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8206: 							  'domainid',
1.565     raeburn  8207: 							  'coursename',$dom);
                   8208:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8209:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8210:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8211:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8212:     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 8213:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8214:     function checkUpload(formname) {
                   8215: 	if (formname.upfile.value == "") {
1.579     raeburn  8216: 	    alert("'.$nofile_alert.'");
1.157     albertel 8217: 	    return false;
                   8218: 	}
1.565     raeburn  8219:         if (formname.courseid.value == "") {
1.579     raeburn  8220:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8221:             return false;
                   8222:         }
1.157     albertel 8223: 	formname.submit();
                   8224:     }
1.565     raeburn  8225: 
                   8226:     function ToSyllabus() {
                   8227:         var cdom = '."'$dom'".';
                   8228:         var cnum = document.rules.courseid.value;
                   8229:         if (cdom == "" || cdom == null) {
                   8230:             return;
                   8231:         }
                   8232:         if (cnum == "" || cnum == null) {
                   8233:            return;
                   8234:         }
                   8235:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8236:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8237:         return;
                   8238:     }
                   8239: 
1.597     wenzelju 8240: '));
                   8241:     $r->print('
1.648     bisitz   8242: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8243: 
1.492     albertel 8244: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8245: '.$default_form_data.
                   8246:   &Apache::lonhtmlcommon::start_pick_box().
                   8247:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8248:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8249:   &Apache::lonhtmlcommon::row_closure().
                   8250:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8251:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8252:   &Apache::lonhtmlcommon::row_closure().
                   8253:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8254:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8255:   &Apache::lonhtmlcommon::row_closure().
                   8256:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8257:   '<input type="file" name="upfile" size="50" />'.
                   8258:   &Apache::lonhtmlcommon::row_closure(1).
                   8259:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8260: 
1.492     albertel 8261: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8262: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8263: </form>
1.492     albertel 8264: ');
1.157     albertel 8265:     return '';
                   8266: }
                   8267: 
1.423     albertel 8268: 
1.157     albertel 8269: sub scantron_upload_scantron_data_save {
1.608     www      8270:     my($r,$symb)=@_;
1.182     albertel 8271:     my $doanotherupload=
                   8272: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8273: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8274: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8275: 	'</form>'."\n";
1.257     albertel 8276:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8277: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8278: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8279: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8280: 	unless ($symb) {
1.182     albertel 8281: 	    $r->print($doanotherupload);
                   8282: 	}
1.162     albertel 8283: 	return '';
                   8284:     }
1.257     albertel 8285:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8286:     my $uploadedfile;
1.567     raeburn  8287:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8288:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8289:         $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 8290:     } else {
1.568     raeburn  8291:         my $result = 
                   8292:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8293:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8294: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8295: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8296:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8297: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8298:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8299:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8300:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8301: 	} else {
1.567     raeburn  8302: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8303:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8304: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8305: 	}
                   8306:     }
1.174     albertel 8307:     if ($symb) {
1.612     www      8308: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8309:     } else {
1.182     albertel 8310: 	$r->print($doanotherupload);
1.174     albertel 8311:     }
1.157     albertel 8312:     return '';
                   8313: }
                   8314: 
1.567     raeburn  8315: sub validate_uploaded_scantron_file {
                   8316:     my ($cdom,$cname,$fname) = @_;
                   8317:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8318:     my @lines;
                   8319:     if ($scanlines ne '-1') {
                   8320:         @lines=split("\n",$scanlines,-1);
                   8321:     }
                   8322:     my $output;
                   8323:     if (@lines) {
                   8324:         my (%counts,$max_match_format);
                   8325:         my ($max_match_count,$max_match_pct) = (0,0);
                   8326:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8327:         my %idmap = &username_to_idmap($classlist);
                   8328:         foreach my $key (keys(%idmap)) {
                   8329:             my $lckey = lc($key);
                   8330:             $idmap{$lckey} = $idmap{$key};
                   8331:         }
                   8332:         my %unique_formats;
                   8333:         my @formatlines = &get_scantronformat_file();
                   8334:         foreach my $line (@formatlines) {
                   8335:             chomp($line);
                   8336:             my @config = split(/:/,$line);
                   8337:             my $idstart = $config[5];
                   8338:             my $idlength = $config[6];
                   8339:             if (($idstart ne '') && ($idlength > 0)) {
                   8340:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8341:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8342:                 } else {
                   8343:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8344:                 }
                   8345:             }
                   8346:         }
                   8347:         foreach my $key (keys(%unique_formats)) {
                   8348:             my ($idstart,$idlength) = split(':',$key);
                   8349:             %{$counts{$key}} = (
                   8350:                                'found'   => 0,
                   8351:                                'total'   => 0,
                   8352:                               );
                   8353:             foreach my $line (@lines) {
                   8354:                 next if ($line =~ /^#/);
                   8355:                 next if ($line =~ /^[\s\cz]*$/);
                   8356:                 my $id = substr($line,$idstart-1,$idlength);
                   8357:                 $id = lc($id);
                   8358:                 if (exists($idmap{$id})) {
                   8359:                     $counts{$key}{'found'} ++;
                   8360:                 }
                   8361:                 $counts{$key}{'total'} ++;
                   8362:             }
                   8363:             if ($counts{$key}{'total'}) {
                   8364:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8365:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8366:                     $max_match_pct = $percent_match;
                   8367:                     $max_match_format = $key;
                   8368:                     $max_match_count = $counts{$key}{'total'};
                   8369:                 }
                   8370:             }
                   8371:         }
                   8372:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8373:             my $format_descs;
                   8374:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8375:             for (my $i=0; $i<$numwithformat; $i++) {
                   8376:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8377:                 if ($i<$numwithformat-2) {
                   8378:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8379:                 } elsif ($i==$numwithformat-2) {
                   8380:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8381:                 } elsif ($i==$numwithformat-1) {
                   8382:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8383:                 }
                   8384:             }
                   8385:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8386:             $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).
                   8387:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8388:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8389:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8390:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8391:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8392:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8393:                        '</ul>';
                   8394:         }
                   8395:     } else {
                   8396:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8397:     }
                   8398:     return $output;
                   8399: }
                   8400: 
1.202     albertel 8401: sub valid_file {
                   8402:     my ($requested_file)=@_;
                   8403:     foreach my $filename (sort(&scantron_filenames())) {
                   8404: 	if ($requested_file eq $filename) { return 1; }
                   8405:     }
                   8406:     return 0;
                   8407: }
                   8408: 
                   8409: sub scantron_download_scantron_data {
1.608     www      8410:     my ($r,$symb)=@_;
                   8411:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8412:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8413:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8414:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8415:     if (! &valid_file($file)) {
1.492     albertel 8416: 	$r->print('
1.202     albertel 8417: 	<p>
1.492     albertel 8418: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8419:         </p>
1.492     albertel 8420: ');
1.202     albertel 8421: 	return;
                   8422:     }
                   8423:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8424:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8425:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8426:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8427:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8428:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8429:     $r->print('
1.202     albertel 8430:     <p>
1.492     albertel 8431: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8432: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8433:     </p>
                   8434:     <p>
1.492     albertel 8435: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8436: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8437:     </p>
                   8438:     <p>
1.492     albertel 8439: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8440: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8441:     </p>
1.492     albertel 8442: ');
1.202     albertel 8443:     return '';
                   8444: }
1.157     albertel 8445: 
1.523     raeburn  8446: sub checkscantron_results {
1.608     www      8447:     my ($r,$symb) = @_;
1.523     raeburn  8448:     if (!$symb) {return '';}
                   8449:     my $cid = $env{'request.course.id'};
1.542     raeburn  8450:     my %lettdig = &letter_to_digits();
1.523     raeburn  8451:     my $numletts = scalar(keys(%lettdig));
                   8452:     my $cnum = $env{'course.'.$cid.'.num'};
                   8453:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8454:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8455:     my %record;
                   8456:     my %scantron_config =
                   8457:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8458:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8459:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8460:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8461:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8462:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8463:     unless (ref($navmap)) {
                   8464:         $r->print(&navmap_errormsg());
                   8465:         return '';
                   8466:     }
1.523     raeburn  8467:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8468:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8469:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
1.673     raeburn  8470:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8471:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8472: 
1.554     raeburn  8473:     my ($uname,$udom);
1.523     raeburn  8474:     my (%scandata,%lastname,%bylast);
                   8475:     $r->print('
                   8476: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8477: 
                   8478:     my @delayqueue;
                   8479:     my %completedstudents;
                   8480: 
                   8481:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.667     www      8482:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.546     raeburn  8483:     my ($username,$domain,$started);
1.582     raeburn  8484:     my $nav_error;
1.649     raeburn  8485:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8486:     if ($nav_error) {
                   8487:         $r->print(&navmap_errormsg());
                   8488:         return '';
                   8489:     }
1.523     raeburn  8490: 
1.667     www      8491:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8492:     my $start=&Time::HiRes::time();
                   8493:     my $i=-1;
                   8494: 
                   8495:     while ($i<$scanlines->{'count'}) {
                   8496:         ($username,$domain,$uname)=('','','');
                   8497:         $i++;
                   8498:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8499:         if ($line=~/^[\s\cz]*$/) { next; }
                   8500:         if ($started) {
1.667     www      8501:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8502:         }
                   8503:         $started=1;
                   8504:         my $scan_record=
                   8505:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8506:                                                      $scan_data);
                   8507:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8508:                                                               \%idmap,$i)) {
                   8509:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8510:                                 'Unable to find a student that matches',1);
                   8511:             next;
                   8512:         }
                   8513:         if (exists $completedstudents{$uname}) {
                   8514:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8515:                                 'Student '.$uname.' has multiple sheets',2);
                   8516:             next;
                   8517:         }
                   8518:         my $pid = $scan_record->{'scantron.ID'};
                   8519:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8520:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8521:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8522:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8523:         chomp($scandata{$pid});
                   8524:         $scandata{$pid} =~ s/\r$//;
                   8525:         ($username,$domain)=split(/:/,$uname);
                   8526:         my $counter = -1;
                   8527:         foreach my $resource (@resources) {
1.557     raeburn  8528:             my $parts;
1.554     raeburn  8529:             my $ressymb = $resource->symb();
1.557     raeburn  8530:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8531:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8532:                 (my $analysis,$parts) =
1.672     raeburn  8533:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8534:                                               $username,$domain,undef,
                   8535:                                               $bubbles_per_row);
1.557     raeburn  8536:             } else {
                   8537:                 $parts = $grader_partids_by_symb{$ressymb};
                   8538:             }
1.542     raeburn  8539:             ($counter,my $recording) =
                   8540:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8541:                                          $scandata{$pid},$parts,
1.542     raeburn  8542:                                          \%scantron_config,\%lettdig,$numletts);
                   8543:             $record{$pid} .= $recording;
1.523     raeburn  8544:         }
                   8545:     }
                   8546:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8547:     $r->print('<br />');
                   8548:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8549:     $passed = 0;
                   8550:     $failed = 0;
                   8551:     $numstudents = 0;
                   8552:     foreach my $last (sort(keys(%bylast))) {
                   8553:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8554:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8555:                 my $showscandata = $scandata{$pid};
                   8556:                 my $showrecord = $record{$pid};
                   8557:                 $showscandata =~ s/\s/&nbsp;/g;
                   8558:                 $showrecord =~ s/\s/&nbsp;/g;
                   8559:                 if ($scandata{$pid} eq $record{$pid}) {
                   8560:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8561:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8562: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8563: '</tr>'."\n".
                   8564: '<tr class="'.$css_class.'">'."\n".
                   8565: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8566:                     $passed ++;
                   8567:                 } else {
                   8568:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8569:                     $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  8570: '</tr>'."\n".
                   8571: '<tr class="'.$css_class.'">'."\n".
                   8572: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8573: '</tr>'."\n";
                   8574:                     $failed ++;
                   8575:                 }
                   8576:                 $numstudents ++;
                   8577:             }
                   8578:         }
                   8579:     }
1.648     bisitz   8580:     $r->print(
                   8581:         '<p>'
                   8582:        .&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).',
                   8583:             '<b>',
                   8584:             $numstudents,
                   8585:             '</b>',
                   8586:             $env{'form.scantron_maxbubble'})
                   8587:        .'</p>'
                   8588:     );
1.523     raeburn  8589:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8590:     if ($passed) {
1.572     www      8591:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8592:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8593:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8594:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8595:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8596:                  $okstudents."\n".
                   8597:                  &Apache::loncommon::end_data_table().'<br />');
                   8598:     }
                   8599:     if ($failed) {
1.572     www      8600:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8601:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8602:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8603:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8604:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8605:                  $badstudents."\n".
                   8606:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8607:                  &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  8608:     }
1.614     www      8609:     $r->print('</form><br />');
1.523     raeburn  8610:     return;
                   8611: }
                   8612: 
1.542     raeburn  8613: sub verify_scantron_grading {
1.554     raeburn  8614:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8615:         $scantron_config,$lettdig,$numletts) = @_;
                   8616:     my ($record,%expected,%startpos);
                   8617:     return ($counter,$record) if (!ref($resource));
                   8618:     return ($counter,$record) if (!$resource->is_problem());
                   8619:     my $symb = $resource->symb();
1.554     raeburn  8620:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8621:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8622:         $counter ++;
                   8623:         $expected{$part_id} = 0;
                   8624:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8625:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8626:             foreach my $item (@sub_lines) {
                   8627:                 $expected{$part_id} += $item;
                   8628:             }
                   8629:         } else {
                   8630:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8631:         }
                   8632:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8633:     }
                   8634:     if ($symb) {
                   8635:         my %recorded;
                   8636:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8637:         if ($returnhash{'version'}) {
                   8638:             my %lasthash=();
                   8639:             my $version;
                   8640:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8641:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8642:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8643:                 }
                   8644:             }
                   8645:             foreach my $key (keys(%lasthash)) {
                   8646:                 if ($key =~ /\.scantron$/) {
                   8647:                     my $value = &unescape($lasthash{$key});
                   8648:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8649:                     if ($value eq '') {
                   8650:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8651:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8652:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8653:                             }
                   8654:                         }
                   8655:                     } else {
                   8656:                         my @tocheck;
                   8657:                         my @items = split(//,$value);
                   8658:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8659:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8660:                             if (@items < $expected{$part_id}) {
                   8661:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8662:                                 my @singles = split(//,$fragment);
                   8663:                                 foreach my $pos (@singles) {
                   8664:                                     if ($pos eq ' ') {
                   8665:                                         push(@tocheck,$pos);
                   8666:                                     } else {
                   8667:                                         my $next = shift(@items);
                   8668:                                         push(@tocheck,$next);
                   8669:                                     }
                   8670:                                 }
                   8671:                             } else {
                   8672:                                 @tocheck = @items;
                   8673:                             }
                   8674:                             foreach my $letter (@tocheck) {
                   8675:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8676:                                     if ($letter !~ /^[A-J]$/) {
                   8677:                                         $letter = $scantron_config->{'Qoff'};
                   8678:                                     }
                   8679:                                     $recorded{$part_id} .= $letter;
                   8680:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8681:                                     my $digit;
                   8682:                                     if ($letter !~ /^[A-J]$/) {
                   8683:                                         $digit = $scantron_config->{'Qoff'};
                   8684:                                     } else {
                   8685:                                         $digit = $lettdig->{$letter};
                   8686:                                     }
                   8687:                                     $recorded{$part_id} .= $digit;
                   8688:                                 }
                   8689:                             }
                   8690:                         } else {
                   8691:                             @tocheck = @items;
                   8692:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8693:                                 my $curr_sub = shift(@tocheck);
                   8694:                                 my $digit;
                   8695:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8696:                                     $digit = $lettdig->{$curr_sub}-1;
                   8697:                                 }
                   8698:                                 if ($curr_sub eq 'J') {
                   8699:                                     $digit += scalar($numletts);
                   8700:                                 }
                   8701:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8702:                                     if ($j == $digit) {
                   8703:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8704:                                     } else {
                   8705:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8706:                                     }
                   8707:                                 }
                   8708:                             }
                   8709:                         }
                   8710:                     }
                   8711:                 }
                   8712:             }
                   8713:         }
1.554     raeburn  8714:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8715:             if ($recorded{$part_id} eq '') {
                   8716:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8717:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8718:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8719:                     }
                   8720:                 }
                   8721:             }
                   8722:             $record .= $recorded{$part_id};
                   8723:         }
                   8724:     }
                   8725:     return ($counter,$record);
                   8726: }
                   8727: 
                   8728: sub letter_to_digits { 
                   8729:     my %lettdig = (
                   8730:                     A => 1,
                   8731:                     B => 2,
                   8732:                     C => 3,
                   8733:                     D => 4,
                   8734:                     E => 5,
                   8735:                     F => 6,
                   8736:                     G => 7,
                   8737:                     H => 8,
                   8738:                     I => 9,
                   8739:                     J => 0,
                   8740:                   );
                   8741:     return %lettdig;
                   8742: }
                   8743: 
1.423     albertel 8744: 
1.75      albertel 8745: #-------- end of section for handling grading scantron forms -------
                   8746: #
                   8747: #-------------------------------------------------------------------
                   8748: 
1.72      ng       8749: #-------------------------- Menu interface -------------------------
                   8750: #
1.614     www      8751: #--- Href with symb and command ---
                   8752: 
                   8753: sub href_symb_cmd {
                   8754:     my ($symb,$cmd)=@_;
1.669     raeburn  8755:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       8756: }
                   8757: 
1.443     banghart 8758: sub grading_menu {
1.608     www      8759:     my ($request,$symb) = @_;
1.443     banghart 8760:     if (!$symb) {return '';}
                   8761: 
                   8762:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8763:                   'command'=>'individual');
1.538     schulted 8764:     
1.598     www      8765:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8766: 
                   8767:     $fields{'command'}='ungraded';
                   8768:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8769: 
                   8770:     $fields{'command'}='table';
                   8771:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8772: 
                   8773:     $fields{'command'}='all_for_one';
                   8774:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8775: 
1.621     www      8776:     $fields{'command'}='downloadfilesselect';
                   8777:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8778: 
1.443     banghart 8779:     $fields{'command'} = 'csvform';
1.538     schulted 8780:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8781:     
1.443     banghart 8782:     $fields{'command'} = 'processclicker';
1.538     schulted 8783:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8784:     
1.443     banghart 8785:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8786:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8787: 
                   8788:     $fields{'command'} = 'initialverifyreceipt';
                   8789:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8790:     
1.598     www      8791:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8792:             items =>[
1.598     www      8793:                         {	linktext => 'Select individual students to grade',
                   8794:                     		url => $url1a,
1.538     schulted 8795:                     		permission => 'F',
1.636     wenzelju 8796:                     		icon => 'grade_students.png',
1.598     www      8797:                     		linktitle => 'Grade current resource for a selection of students.'
                   8798:                         }, 
                   8799:                         {       linktext => 'Grade ungraded submissions.',
                   8800:                                 url => $url1b,
                   8801:                                 permission => 'F',
1.636     wenzelju 8802:                                 icon => 'ungrade_sub.png',
1.598     www      8803:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8804:                         },
1.598     www      8805: 
                   8806:                         {       linktext => 'Grading table',
                   8807:                                 url => $url1c,
                   8808:                                 permission => 'F',
1.636     wenzelju 8809:                                 icon => 'grading_table.png',
1.598     www      8810:                                 linktitle => 'Grade current resource for all students.'
                   8811:                         },
1.615     www      8812:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8813:                                 url => $url1d,
                   8814:                                 permission => 'F',
1.636     wenzelju 8815:                                 icon => 'grade_PageFolder.png',
1.598     www      8816:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8817:                         },
                   8818:                         {       linktext => 'Download submissions',
                   8819:                                 url => $url1e,
                   8820:                                 permission => 'F',
1.636     wenzelju 8821:                                 icon => 'download_sub.png',
1.621     www      8822:                                 linktitle => 'Download all students submissions.'
1.598     www      8823:                         }]},
                   8824:                          { categorytitle=>'Automated Grading',
                   8825:                items =>[
                   8826: 
1.538     schulted 8827:                 	    {	linktext => 'Upload Scores',
                   8828:                     		url => $url2,
                   8829:                     		permission => 'F',
                   8830:                     		icon => 'uploadscores.png',
                   8831:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8832:                 	    },
                   8833:                 	    {	linktext => 'Process Clicker',
                   8834:                     		url => $url3,
                   8835:                     		permission => 'F',
                   8836:                     		icon => 'addClickerInfoFile.png',
                   8837:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8838:                 	    },
1.587     raeburn  8839:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8840:                     		url => $url4,
                   8841:                     		permission => 'F',
1.636     wenzelju 8842:                     		icon => 'bubblesheet.png',
1.648     bisitz   8843:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8844:                 	    },
1.616     www      8845:                             {   linktext => 'Verify Receipt Number',
1.602     www      8846:                                 url => $url5,
                   8847:                                 permission => 'F',
1.636     wenzelju 8848:                                 icon => 'receipt_number.png',
1.602     www      8849:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8850:                             }
                   8851: 
1.538     schulted 8852:                     ]
                   8853:             });
                   8854: 
1.443     banghart 8855:     # Create the menu
                   8856:     my $Str;
1.445     banghart 8857:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8858:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8859:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8860: 
1.602     www      8861:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8862:     return $Str;    
                   8863: }
                   8864: 
1.598     www      8865: 
                   8866: sub ungraded {
                   8867:     my ($request)=@_;
                   8868:     &submit_options($request);
                   8869: }
                   8870: 
1.599     www      8871: sub submit_options_sequence {
1.608     www      8872:     my ($request,$symb) = @_;
1.599     www      8873:     if (!$symb) {return '';}
1.600     www      8874:     &commonJSfunctions($request);
                   8875:     my $result;
1.599     www      8876: 
1.600     www      8877:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8878:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8879:     $result.=&selectfield(0).
1.601     www      8880:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8881:             <div>
                   8882:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8883:             </div>
                   8884:         </div>
                   8885:   </form>';
                   8886:     return $result;
                   8887: }
                   8888: 
                   8889: sub submit_options_table {
1.608     www      8890:     my ($request,$symb) = @_;
1.600     www      8891:     if (!$symb) {return '';}
1.599     www      8892:     &commonJSfunctions($request);
                   8893:     my $result;
                   8894: 
                   8895:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8896:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8897: 
1.632     www      8898:     $result.=&selectfield(0).
1.601     www      8899:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8900:             <div>
                   8901:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8902:             </div>
                   8903:         </div>
                   8904:   </form>';
                   8905:     return $result;
                   8906: }
1.443     banghart 8907: 
1.621     www      8908: sub submit_options_download {
                   8909:     my ($request,$symb) = @_;
                   8910:     if (!$symb) {return '';}
                   8911: 
                   8912:     &commonJSfunctions($request);
                   8913: 
                   8914:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8915:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8916:     $result.='
                   8917: <h2>
                   8918:   '.&mt('Select Students for Which to Download Submissions').'
                   8919: </h2>'.&selectfield(1).'
                   8920:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8921:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8922:             </div>
                   8923:           </div>
1.600     www      8924: 
                   8925: 
1.621     www      8926:   </form>';
                   8927:     return $result;
                   8928: }
                   8929: 
1.443     banghart 8930: #--- Displays the submissions first page -------
                   8931: sub submit_options {
1.608     www      8932:     my ($request,$symb) = @_;
1.72      ng       8933:     if (!$symb) {return '';}
                   8934: 
1.118     ng       8935:     &commonJSfunctions($request);
1.473     albertel 8936:     my $result;
1.533     bisitz   8937: 
1.72      ng       8938:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8939: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8940:     $result.=&selectfield(1).'
1.601     www      8941:                 <input type="hidden" name="command" value="submission" /> 
                   8942: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8943:             </div>
                   8944:           </div>
                   8945: 
                   8946: 
                   8947:   </form>';
                   8948:     return $result;
                   8949: }
1.533     bisitz   8950: 
1.601     www      8951: sub selectfield {
                   8952:    my ($full)=@_;
1.635     raeburn  8953:    my %options = 
                   8954:           (&Apache::lonlocal::texthash(
                   8955:              'yes'       => 'with submissions',
                   8956:              'queued'    => 'in grading queue',
                   8957:              'graded'    => 'with ungraded submissions',
                   8958:              'incorrect' => 'with incorrect submissions',
                   8959:              'all'       => 'with any status'),
                   8960:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8961:    my $result='<div class="LC_columnSection">
1.537     harmsja  8962:   
1.533     bisitz   8963:     <fieldset>
                   8964:       <legend>
                   8965:        '.&mt('Sections').'
                   8966:       </legend>
1.601     www      8967:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8968:     </fieldset>
1.537     harmsja  8969:   
1.533     bisitz   8970:     <fieldset>
                   8971:       <legend>
                   8972:         '.&mt('Groups').'
                   8973:       </legend>
                   8974:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8975:     </fieldset>
1.537     harmsja  8976:   
1.533     bisitz   8977:     <fieldset>
                   8978:       <legend>
                   8979:         '.&mt('Access Status').'
                   8980:       </legend>
1.601     www      8981:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8982:     </fieldset>';
                   8983:     if ($full) {
                   8984:        $result.='
1.533     bisitz   8985:     <fieldset>
                   8986:       <legend>
                   8987:         '.&mt('Submission Status').'
1.601     www      8988:       </legend>'.
1.635     raeburn  8989:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8990:    '</fieldset>';
                   8991:     }
                   8992:     $result.='</div><br />';
1.44      ng       8993:     return $result;
1.2       albertel 8994: }
                   8995: 
1.285     albertel 8996: sub reset_perm {
                   8997:     undef(%perm);
                   8998: }
                   8999: 
                   9000: sub init_perm {
                   9001:     &reset_perm();
1.300     albertel 9002:     foreach my $test_perm ('vgr','mgr','opa') {
                   9003: 
                   9004: 	my $scope = $env{'request.course.id'};
                   9005: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9006: 
                   9007: 	    $scope .= '/'.$env{'request.course.sec'};
                   9008: 	    if ( $perm{$test_perm}=
                   9009: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9010: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9011: 	    } else {
                   9012: 		delete($perm{$test_perm});
                   9013: 	    }
1.285     albertel 9014: 	}
                   9015:     }
                   9016: }
                   9017: 
1.674   ! raeburn  9018: sub init_old_essays {
        !          9019:     my ($symb,$apath,$adom,$aname) = @_;
        !          9020:     if ($symb ne '') {
        !          9021:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
        !          9022:         if (keys(%essays) > 0) {
        !          9023:             $old_essays{$symb} = \%essays;
        !          9024:         }
        !          9025:     }
        !          9026:     return;
        !          9027: }
        !          9028: 
        !          9029: sub reset_old_essays {
        !          9030:     undef(%old_essays);
        !          9031: }
        !          9032: 
1.400     www      9033: sub gather_clicker_ids {
1.408     albertel 9034:     my %clicker_ids;
1.400     www      9035: 
                   9036:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9037: 
                   9038:     # Set up a couple variables.
1.407     albertel 9039:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9040:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9041:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9042: 
1.407     albertel 9043:     foreach my $student (keys(%$classlist)) {
1.438     www      9044:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9045:         my $username = $classlist->{$student}->[$username_idx];
                   9046:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9047:         my $clickers =
1.408     albertel 9048: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9049:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9050:             $id=~s/^[\#0]+//;
1.421     www      9051:             $id=~s/[\-\:]//g;
1.407     albertel 9052:             if (exists($clicker_ids{$id})) {
1.408     albertel 9053: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9054:             } else {
1.408     albertel 9055: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9056:             }
                   9057:         }
                   9058:     }
1.407     albertel 9059:     return %clicker_ids;
1.400     www      9060: }
                   9061: 
1.402     www      9062: sub gather_adv_clicker_ids {
1.408     albertel 9063:     my %clicker_ids;
1.402     www      9064:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9065:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9066:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9067:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9068:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9069:             my ($puname,$pudom)=split(/\:/,$person);
                   9070:             my $clickers =
1.408     albertel 9071: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9072:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9073: 		$id=~s/^[\#0]+//;
1.421     www      9074:                 $id=~s/[\-\:]//g;
1.408     albertel 9075: 		if (exists($clicker_ids{$id})) {
                   9076: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9077: 		} else {
                   9078: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9079: 		}
1.405     www      9080:             }
1.402     www      9081:         }
                   9082:     }
1.407     albertel 9083:     return %clicker_ids;
1.402     www      9084: }
                   9085: 
1.413     www      9086: sub clicker_grading_parameters {
                   9087:     return ('gradingmechanism' => 'scalar',
                   9088:             'upfiletype' => 'scalar',
                   9089:             'specificid' => 'scalar',
                   9090:             'pcorrect' => 'scalar',
                   9091:             'pincorrect' => 'scalar');
                   9092: }
                   9093: 
1.400     www      9094: sub process_clicker {
1.608     www      9095:     my ($r,$symb)=@_;
1.400     www      9096:     if (!$symb) {return '';}
                   9097:     my $result=&checkforfile_js();
1.632     www      9098:     $result.=&Apache::loncommon::start_data_table().
                   9099:              &Apache::loncommon::start_data_table_header_row().
                   9100:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9101:              &Apache::loncommon::end_data_table_header_row().
                   9102:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9103: # Attempt to restore parameters from last session, set defaults if not present
                   9104:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9105:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9106:                                                  \%Saveable_Parameters);
                   9107:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9108:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9109:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9110:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9111: 
                   9112:     my %checked;
1.521     www      9113:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9114:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9115:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9116:        }
                   9117:     }
                   9118: 
1.632     www      9119:     my $upload=&mt("Evaluate File");
1.400     www      9120:     my $type=&mt("Type");
1.402     www      9121:     my $attendance=&mt("Award points just for participation");
                   9122:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9123:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9124:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9125:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9126:     my $pcorrect=&mt("Percentage points for correct solution");
                   9127:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9128:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9129: 						   {'iclicker' => 'i>clicker',
1.666     www      9130:                                                     'interwrite' => 'interwrite PRS',
                   9131:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9132:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9133:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9134: function sanitycheck() {
                   9135: // Accept only integer percentages
                   9136:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9137:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9138: // Find out grading choice
                   9139:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9140:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9141:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9142:       }
                   9143:    }
                   9144: // By default, new choice equals user selection
                   9145:    newgradingchoice=gradingchoice;
                   9146: // Not good to give more points for false answers than correct ones
                   9147:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9148:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9149:    }
                   9150: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9151:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9152:       document.forms.gradesupload.pcorrect.value=100;
                   9153:       document.forms.gradesupload.pincorrect.value=100;
                   9154:    }
                   9155: // If the values are different, cannot be attendance only
                   9156:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9157:        (gradingchoice=='attendance')) {
                   9158:        newgradingchoice='personnel';
                   9159:    }
                   9160: // Change grading choice to new one
                   9161:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9162:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9163:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9164:       } else {
                   9165:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9166:       }
                   9167:    }
                   9168: // Remember the old state
                   9169:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9170: }
1.597     wenzelju 9171: ENDUPFORM
                   9172:     $result.= <<ENDUPFORM;
1.400     www      9173: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9174: <input type="hidden" name="symb" value="$symb" />
                   9175: <input type="hidden" name="command" value="processclickerfile" />
                   9176: <input type="file" name="upfile" size="50" />
                   9177: <br /><label>$type: $selectform</label>
1.632     www      9178: ENDUPFORM
                   9179:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9180:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9181:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9182: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9183: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9184: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9185: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9186: <br />&nbsp;&nbsp;&nbsp;
                   9187: <input type="text" name="givenanswer" size="50" />
1.413     www      9188: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9189: ENDGRADINGFORM
                   9190:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9191:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9192:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9193: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9194: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9195: </form>'
1.632     www      9196: ENDPERCFORM
                   9197:     $result.='</td>'.
                   9198:              &Apache::loncommon::end_data_table_row().
                   9199:              &Apache::loncommon::end_data_table();
1.400     www      9200:     return $result;
                   9201: }
                   9202: 
                   9203: sub process_clicker_file {
1.608     www      9204:     my ($r,$symb)=@_;
1.400     www      9205:     if (!$symb) {return '';}
1.413     www      9206: 
                   9207:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9208:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9209:                                               \%Saveable_Parameters);
1.598     www      9210:     my $result='';
1.404     www      9211:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9212: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9213: 	return $result;
1.404     www      9214:     }
1.522     www      9215:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9216:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9217:         return $result;
1.521     www      9218:     }
1.522     www      9219:     my $foundgiven=0;
1.521     www      9220:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9221:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9222:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9223:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9224:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9225:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9226:         $foundgiven=$#answers+1;
1.521     www      9227:     }
1.407     albertel 9228:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9229:     my %correct_ids;
1.404     www      9230:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9231: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9232:     }
                   9233:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9234: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9235: 	   $correct_id=~tr/a-z/A-Z/;
                   9236: 	   $correct_id=~s/\s//gs;
                   9237: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9238:            $correct_id=~s/[\-\:]//g;
1.414     www      9239:            if ($correct_id) {
                   9240: 	      $correct_ids{$correct_id}='specified';
                   9241:            }
                   9242:         }
1.400     www      9243:     }
1.404     www      9244:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9245: 	$result.=&mt('Score based on attendance only');
1.521     www      9246:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9247:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9248:     } else {
1.408     albertel 9249: 	my $number=0;
1.411     www      9250: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9251: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9252: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9253: 	    if ($correct_ids{$id} eq 'specified') {
                   9254: 		$result.=&mt('specified');
                   9255: 	    } else {
                   9256: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9257: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9258: 	    }
                   9259: 	    $number++;
                   9260: 	}
1.411     www      9261:         $result.="</p>\n";
1.408     albertel 9262: 	if ($number==0) {
                   9263: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      9264: 	    return $result;
1.408     albertel 9265: 	}
1.404     www      9266:     }
1.405     www      9267:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9268:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9269: 		     '<span class="LC_error">',
                   9270: 		     '</span>',
                   9271: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      9272:         return $result;
1.405     www      9273:     }
1.410     www      9274: 
                   9275: # Were able to get all the info needed, now analyze the file
                   9276: 
1.411     www      9277:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9278:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9279:     $result.=&Apache::loncommon::start_data_table().
                   9280:              &Apache::loncommon::start_data_table_header_row().
                   9281:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9282:              &Apache::loncommon::end_data_table_header_row().
                   9283:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9284: <td>
1.410     www      9285: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9286: <input type="hidden" name="symb" value="$symb" />
                   9287: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9288: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9289: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9290: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9291: ENDHEADER
1.522     www      9292:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9293:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9294:     } 
1.408     albertel 9295:     my %responses;
                   9296:     my @questiontitles;
1.405     www      9297:     my $errormsg='';
                   9298:     my $number=0;
                   9299:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9300: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9301:     }
1.419     www      9302:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9303:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9304:     }
1.666     www      9305:     if ($env{'form.upfiletype'} eq 'turning') {
                   9306:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9307:     }
1.411     www      9308:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9309:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9310:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9311:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9312:              '<br />';
1.522     www      9313:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9314:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9315:        return $result;
1.522     www      9316:     } 
1.414     www      9317: # Remember Question Titles
                   9318: # FIXME: Possibly need delimiter other than ":"
                   9319:     for (my $i=0;$i<$number;$i++) {
                   9320:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9321:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9322:     }
1.411     www      9323:     my $correct_count=0;
                   9324:     my $student_count=0;
                   9325:     my $unknown_count=0;
1.414     www      9326: # Match answers with usernames
                   9327: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9328:     foreach my $id (keys(%responses)) {
1.410     www      9329:        if ($correct_ids{$id}) {
1.414     www      9330:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9331:           $correct_count++;
1.410     www      9332:        } elsif ($clicker_ids{$id}) {
1.437     www      9333:           if ($clicker_ids{$id}=~/\,/) {
                   9334: # More than one user with the same clicker!
1.632     www      9335:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9336:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9337:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9338:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9339:                            "<select name='multi".$id."'>";
                   9340:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9341:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9342:              }
                   9343:              $result.='</select>';
                   9344:              $unknown_count++;
                   9345:           } else {
                   9346: # Good: found one and only one user with the right clicker
                   9347:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9348:              $student_count++;
                   9349:           }
1.410     www      9350:        } else {
1.632     www      9351:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9352:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9353:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9354:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9355:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9356:                    "\n".&mt("Domain").": ".
                   9357:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9358:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9359:           $unknown_count++;
1.410     www      9360:        }
1.405     www      9361:     }
1.412     www      9362:     $result.='<hr />'.
                   9363:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9364:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9365:        if ($correct_count==0) {
                   9366:           $errormsg.="Found no correct answers answers for grading!";
                   9367:        } elsif ($correct_count>1) {
1.414     www      9368:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9369:        }
                   9370:     }
1.428     www      9371:     if ($number<1) {
                   9372:        $errormsg.="Found no questions.";
                   9373:     }
1.412     www      9374:     if ($errormsg) {
                   9375:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9376:     } else {
                   9377:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9378:     }
1.632     www      9379:     $result.='</form></td>'.
                   9380:              &Apache::loncommon::end_data_table_row().
                   9381:              &Apache::loncommon::end_data_table();
1.614     www      9382:     return $result;
1.400     www      9383: }
                   9384: 
1.405     www      9385: sub iclicker_eval {
1.406     www      9386:     my ($questiontitles,$responses)=@_;
1.405     www      9387:     my $number=0;
                   9388:     my $errormsg='';
                   9389:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9390:         my %components=&Apache::loncommon::record_sep($line);
                   9391:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9392: 	if ($entries[0] eq 'Question') {
                   9393: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9394: 		$$questiontitles[$number]=$entries[$i];
                   9395: 		$number++;
                   9396: 	    }
                   9397: 	}
                   9398: 	if ($entries[0]=~/^\#/) {
                   9399: 	    my $id=$entries[0];
                   9400: 	    my @idresponses;
                   9401: 	    $id=~s/^[\#0]+//;
                   9402: 	    for (my $i=0;$i<$number;$i++) {
                   9403: 		my $idx=3+$i*6;
1.644     www      9404:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9405: 		push(@idresponses,$entries[$idx]);
                   9406: 	    }
                   9407: 	    $$responses{$id}=join(',',@idresponses);
                   9408: 	}
1.405     www      9409:     }
                   9410:     return ($errormsg,$number);
                   9411: }
                   9412: 
1.419     www      9413: sub interwrite_eval {
                   9414:     my ($questiontitles,$responses)=@_;
                   9415:     my $number=0;
                   9416:     my $errormsg='';
1.420     www      9417:     my $skipline=1;
                   9418:     my $questionnumber=0;
                   9419:     my %idresponses=();
1.419     www      9420:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9421:         my %components=&Apache::loncommon::record_sep($line);
                   9422:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9423:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9424:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9425:         next if $skipline;
                   9426:         if ($entries[0]!=$questionnumber) {
                   9427:            $questionnumber=$entries[0];
                   9428:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9429:            $number++;
1.419     www      9430:         }
1.420     www      9431:         my $id=$entries[4];
                   9432:         $id=~s/^[\#0]+//;
1.421     www      9433:         $id=~s/^v\d*\://i;
                   9434:         $id=~s/[\-\:]//g;
1.420     www      9435:         $idresponses{$id}[$number]=$entries[6];
                   9436:     }
1.524     raeburn  9437:     foreach my $id (keys(%idresponses)) {
1.420     www      9438:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9439:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9440:     }
                   9441:     return ($errormsg,$number);
                   9442: }
                   9443: 
1.666     www      9444: sub turning_eval {
                   9445:     my ($questiontitles,$responses)=@_;
                   9446:     my $number=0;
                   9447:     my $errormsg='';
                   9448:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9449:         my %components=&Apache::loncommon::record_sep($line);
                   9450:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9451:         if ($#entries>$number) { $number=$#entries; }
                   9452:         my $id=$entries[0];
                   9453:         my @idresponses;
                   9454:         $id=~s/^[\#0]+//;
                   9455:         unless ($id) { next; }
                   9456:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9457:             $entries[$idx]=~s/\,/\;/g;
                   9458:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9459:             push(@idresponses,$entries[$idx]);
                   9460:         }
                   9461:         $$responses{$id}=join(',',@idresponses);
                   9462:     }
                   9463:     for (my $i=1; $i<=$number; $i++) {
                   9464:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9465:     }
                   9466:     return ($errormsg,$number);
                   9467: }
                   9468: 
                   9469: 
1.414     www      9470: sub assign_clicker_grades {
1.608     www      9471:     my ($r,$symb)=@_;
1.414     www      9472:     if (!$symb) {return '';}
1.416     www      9473: # See which part we are saving to
1.582     raeburn  9474:     my $res_error;
                   9475:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9476:     if ($res_error) {
                   9477:         return &navmap_errormsg();
                   9478:     }
1.416     www      9479: # FIXME: This should probably look for the first handgradeable part
                   9480:     my $part=$$partlist[0];
                   9481: # Start screen output
1.632     www      9482:     my $result=&Apache::loncommon::start_data_table().
                   9483:              &Apache::loncommon::start_data_table_header_row().
                   9484:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9485:              &Apache::loncommon::end_data_table_header_row().
                   9486:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9487: # Get correct result
                   9488: # FIXME: Possibly need delimiter other than ":"
                   9489:     my @correct=();
1.415     www      9490:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9491:     my $number=$env{'form.number'};
                   9492:     if ($gradingmechanism ne 'attendance') {
1.414     www      9493:        foreach my $key (keys(%env)) {
                   9494:           if ($key=~/^form\.correct\:/) {
                   9495:              my @input=split(/\,/,$env{$key});
                   9496:              for (my $i=0;$i<=$#input;$i++) {
                   9497:                  if (($correct[$i]) && ($input[$i]) &&
                   9498:                      ($correct[$i] ne $input[$i])) {
                   9499:                     $result.='<br /><span class="LC_warning">'.
                   9500:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9501:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9502:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9503:                     $correct[$i]=$input[$i];
                   9504:                  }
                   9505:              }
                   9506:           }
                   9507:        }
1.415     www      9508:        for (my $i=0;$i<$number;$i++) {
1.644     www      9509:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9510:              $result.='<br /><span class="LC_error">'.
                   9511:                       &mt('No correct result given for question "[_1]"!',
                   9512:                           $env{'form.question:'.$i}).'</span>';
                   9513:           }
                   9514:        }
1.644     www      9515:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9516:     }
                   9517: # Start grading
1.415     www      9518:     my $pcorrect=$env{'form.pcorrect'};
                   9519:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9520:     my $storecount=0;
1.632     www      9521:     my %users=();
1.415     www      9522:     foreach my $key (keys(%env)) {
1.420     www      9523:        my $user='';
1.415     www      9524:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9525:           $user=$1;
                   9526:        }
                   9527:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9528:           my $id=$1;
                   9529:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9530:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9531:           } elsif ($env{'form.multi'.$id}) {
                   9532:              $user=$env{'form.multi'.$id};
1.420     www      9533:           }
                   9534:        }
1.632     www      9535:        if ($user) {
                   9536:           if ($users{$user}) {
                   9537:              $result.='<br /><span class="LC_warning">'.
                   9538:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9539:                       '</span><br />';
                   9540:           }
                   9541:           $users{$user}=1; 
1.415     www      9542:           my @answer=split(/\,/,$env{$key});
                   9543:           my $sum=0;
1.522     www      9544:           my $realnumber=$number;
1.415     www      9545:           for (my $i=0;$i<$number;$i++) {
1.576     www      9546:              if  ($correct[$i] eq '-') {
                   9547:                 $realnumber--;
1.644     www      9548:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9549:                 if ($gradingmechanism eq 'attendance') {
                   9550:                    $sum+=$pcorrect;
1.576     www      9551:                 } elsif ($correct[$i] eq '*') {
1.522     www      9552:                    $sum+=$pcorrect;
1.415     www      9553:                 } else {
1.644     www      9554: # We actually grade if correct or not
                   9555:                    my $increment=$pincorrect;
                   9556: # Special case: numerical answer "0"
                   9557:                    if ($correct[$i] eq '0') {
                   9558:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9559:                          $increment=$pcorrect;
                   9560:                       }
                   9561: # General numerical answer, both evaluate to something non-zero
                   9562:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9563:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9564:                          $increment=$pcorrect;
                   9565:                       }
                   9566: # Must be just alphanumeric
                   9567:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9568:                       $increment=$pcorrect;
1.415     www      9569:                    }
1.644     www      9570:                    $sum+=$increment;
1.415     www      9571:                 }
                   9572:              }
                   9573:           }
1.522     www      9574:           my $ave=$sum/(100*$realnumber);
1.416     www      9575: # Store
                   9576:           my ($username,$domain)=split(/\:/,$user);
                   9577:           my %grades=();
                   9578:           $grades{"resource.$part.solved"}='correct_by_override';
                   9579:           $grades{"resource.$part.awarded"}=$ave;
                   9580:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9581:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9582:                                                  $env{'request.course.id'},
                   9583:                                                  $domain,$username);
                   9584:           if ($returncode ne 'ok') {
                   9585:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9586:           } else {
                   9587:              $storecount++;
                   9588:           }
1.415     www      9589:        }
                   9590:     }
                   9591: # We are done
1.549     hauer    9592:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9593:              '</td>'.
                   9594:              &Apache::loncommon::end_data_table_row().
                   9595:              &Apache::loncommon::end_data_table();
1.614     www      9596:     return $result;
1.414     www      9597: }
                   9598: 
1.582     raeburn  9599: sub navmap_errormsg {
                   9600:     return '<div class="LC_error">'.
                   9601:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9602:            &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  9603:            '</div>';
                   9604: }
1.607     droeschl 9605: 
1.609     www      9606: sub startpage {
1.671     raeburn  9607:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   9608:     if ($nomenu) {
                   9609:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   9610:     } else {
                   9611:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   9612:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   9613:                                                  {'bread_crumbs' => $crumbs}));
                   9614:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   9615:     }
1.613     www      9616:     unless ($nodisplayflag) {
1.671     raeburn  9617:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      9618:     }
1.607     droeschl 9619: }
1.582     raeburn  9620: 
1.622     www      9621: sub select_problem {
                   9622:     my ($r)=@_;
1.632     www      9623:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9624:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9625:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9626:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9627: }
                   9628: 
1.1       albertel 9629: sub handler {
1.41      ng       9630:     my $request=$_[0];
1.434     albertel 9631:     &reset_caches();
1.646     raeburn  9632:     if ($request->header_only) {
                   9633:         &Apache::loncommon::content_type($request,'text/html');
                   9634:         $request->send_http_header;
                   9635:         return OK;
                   9636:     }
                   9637:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9638: 
1.664     raeburn  9639: # see what command we need to execute
                   9640: 
                   9641:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9642:     my $command=$commands[0];
                   9643: 
1.646     raeburn  9644:     &init_perm();
                   9645:     if (!$env{'request.course.id'}) {
1.664     raeburn  9646:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   9647:                 ($command =~ /^scantronupload/)) {
                   9648:             # Not in a course.
                   9649:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9650:             return HTTP_NOT_ACCEPTABLE;
                   9651:         }
1.646     raeburn  9652:     } elsif (!%perm) {
                   9653:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9654:     }
1.646     raeburn  9655:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9656:     $request->send_http_header;
1.646     raeburn  9657: 
1.160     albertel 9658:     if ($#commands > 0) {
                   9659: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9660:     }
1.608     www      9661: 
                   9662: # see what the symb is
                   9663: 
                   9664:     my $symb=$env{'form.symb'};
                   9665:     unless ($symb) {
                   9666:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9667:        $symb=&Apache::lonnet::symbread($url);
                   9668:     }
1.646     raeburn  9669:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9670: 
1.513     foxr     9671:     $ssi_error = 0;
1.637     www      9672:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9673: #
1.637     www      9674: # Not called from a resource, but inside a course
1.601     www      9675: #    
1.622     www      9676:         &startpage($request,undef,[],1,1);
                   9677:         &select_problem($request);
1.41      ng       9678:     } else {
1.104     albertel 9679: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  9680:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   9681:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   9682:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   9683:                     &choose_task_version_form($symb,$env{'form.student'},
                   9684:                                               $env{'form.userdom'});
                   9685:             }
                   9686:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   9687:             if ($versionform) {
                   9688:                 $request->print($versionform);
                   9689:             }
                   9690:             $request->print('<br clear="all" />');
1.611     www      9691: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  9692:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   9693:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   9694:                 &choose_task_version_form($symb,$env{'form.student'},
                   9695:                                           $env{'form.userdom'},
                   9696:                                           $env{'form.inhibitmenu'});
                   9697:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   9698:             if ($versionform) {
                   9699:                 $request->print($versionform);
                   9700:             }
                   9701:             $request->print('<br clear="all" />');
                   9702:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 9703: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9704:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9705:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9706: 	    &pickStudentPage($request,$symb);
1.103     albertel 9707: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9708:             &startpage($request,$symb,
                   9709:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9710:                                        {href=>'',text=>'Select student'},
                   9711:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9712: 	    &displayPage($request,$symb);
1.104     albertel 9713: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9714:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9715:                                        {href=>'',text=>'Select student'},
                   9716:                                        {href=>'',text=>'Grade student'},
                   9717:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9718: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9719: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9720:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9721:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9722: 	    &processGroup($request,$symb);
1.104     albertel 9723: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9724:             &startpage($request,$symb);
                   9725: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9726: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9727:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9728: 	    $request->print(&submit_options($request,$symb));
1.598     www      9729:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9730:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9731:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9732:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9733:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9734:             $request->print(&submit_options_table($request,$symb));
1.598     www      9735:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9736:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9737:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9738: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9739:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9740: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9741: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9742:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9743:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9744: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9745: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9746:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9747:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9748:                                                                              text=>"Modify grades"},
                   9749:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9750: 	    $request->print(&editgrades($request,$symb));
1.602     www      9751:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9752:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9753:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9754: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9755:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9756:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9757: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9758:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9759:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9760:             $request->print(&process_clicker($request,$symb));
1.400     www      9761:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9762:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9763:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9764:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9765:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9766:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9767:                                        {href=>'', text=>'Process clicker file'},
                   9768:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9769:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9770: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9771:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9772: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9773: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9774:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9775: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9776: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9777:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9778: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9779: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9780: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9781:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9782: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9783: 	    } else {
1.257     albertel 9784: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9785: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9786: 		} else {
1.257     albertel 9787: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9788: 		}
1.627     www      9789:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9790: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9791: 	    }
1.246     albertel 9792: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9793:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9794: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9795: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9796:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9797: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9798:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9799:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9800:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9801: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9802:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9803: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9804: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9805:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9806: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9807:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9808:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9809: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9810:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9811:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9812:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9813:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9814: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9815:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9816:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9817:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9818: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9819:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9820:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9821:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9822:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9823:             $request->print(&checkscantron_results($request,$symb));
                   9824:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9825:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9826:             $request->print(&submit_options_download($request,$symb));
                   9827:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9828:             &startpage($request,$symb,
                   9829:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9830:     {href=>'', text=>'Download submissions'}]);
                   9831:             &submit_download_link($request,$symb);
1.106     albertel 9832: 	} elsif ($command) {
1.620     www      9833:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9834: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9835: 	}
1.2       albertel 9836:     }
1.513     foxr     9837:     if ($ssi_error) {
                   9838: 	&ssi_print_error($request);
                   9839:     }
1.671     raeburn  9840:     if ($env{'form.inhibitmenu'}) {
                   9841:         $request->print(&Apache::loncommon::end_page());
                   9842:     } else {
                   9843:         &Apache::lonquickgrades::endGradeScreen($request);
                   9844:     }
1.434     albertel 9845:     &reset_caches();
1.646     raeburn  9846:     return OK;
1.44      ng       9847: }
                   9848: 
1.1       albertel 9849: 1;
                   9850: 
1.13      albertel 9851: __END__;
1.531     jms      9852: 
                   9853: 
                   9854: =head1 NAME
                   9855: 
                   9856: Apache::grades
                   9857: 
                   9858: =head1 SYNOPSIS
                   9859: 
                   9860: Handles the viewing of grades.
                   9861: 
                   9862: This is part of the LearningOnline Network with CAPA project
                   9863: described at http://www.lon-capa.org.
                   9864: 
                   9865: =head1 OVERVIEW
                   9866: 
                   9867: Do an ssi with retries:
                   9868: While I'd love to factor out this with the vesrion in lonprintout,
                   9869: 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
                   9870: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9871: 
                   9872: At least the logic that drives this has been pulled out into loncommon.
                   9873: 
                   9874: 
                   9875: 
                   9876: ssi_with_retries - Does the server side include of a resource.
                   9877:                      if the ssi call returns an error we'll retry it up to
                   9878:                      the number of times requested by the caller.
                   9879:                      If we still have a proble, no text is appended to the
                   9880:                      output and we set some global variables.
                   9881:                      to indicate to the caller an SSI error occurred.  
                   9882:                      All of this is supposed to deal with the issues described
                   9883:                      in LonCAPA BZ 5631 see:
                   9884:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9885:                      by informing the user that this happened.
                   9886: 
                   9887: Parameters:
                   9888:   resource   - The resource to include.  This is passed directly, without
                   9889:                interpretation to lonnet::ssi.
                   9890:   form       - The form hash parameters that guide the interpretation of the resource
                   9891:                
                   9892:   retries    - Number of retries allowed before giving up completely.
                   9893: Returns:
                   9894:   On success, returns the rendered resource identified by the resource parameter.
                   9895: Side Effects:
                   9896:   The following global variables can be set:
                   9897:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9898:                               It is up to the caller to initialize this to false
                   9899:                               if desired.
                   9900:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9901:                               of the resource that could not be rendered by the ssi
                   9902:                               call.
                   9903:    ssi_error_message   - The error string fetched from the ssi response
                   9904:                               in the event of an error.
                   9905: 
                   9906: 
                   9907: =head1 HANDLER SUBROUTINE
                   9908: 
                   9909: ssi_with_retries()
                   9910: 
                   9911: =head1 SUBROUTINES
                   9912: 
                   9913: =over
                   9914: 
1.671     raeburn  9915: =head1 Routines to display previous version of a Task for a specific student
                   9916: 
                   9917: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   9918: can receive another opportunity. Access to tasks is slot-based. If a slot
                   9919: requires a proctor to check-in the student, a new version of the Task will
                   9920: be created when the student is checked in to the new opportunity.
                   9921: 
                   9922: If a particular student has tried two or more versions of a particular task,
                   9923: the submission screen provides a user with vgr privileges (e.g., a Course
                   9924: Coordinator) the ability to display a previous version worked on by the
                   9925: student.  By default, the current version is displayed. If a previous version
                   9926: has been selected for display, submission data are only shown that pertain
                   9927: to that particular version, and the interface to submit grades is not shown.
                   9928: 
                   9929: =over 4
                   9930: 
                   9931: =item show_previous_task_version()
                   9932: 
                   9933: Displays a specified version of a student's Task, as the student sees it.
                   9934: 
                   9935: Inputs: 2
                   9936:         request - request object
                   9937:         symb    - unique symb for current instance of resource
                   9938: 
                   9939: Output: None.
                   9940: 
                   9941: Side Effects: calls &show_problem() to print version of Task, with
                   9942:               version contained in form item: $env{'form.previousversion'}
                   9943: 
                   9944: =item choose_task_version_form()
                   9945: 
                   9946: Displays a web form used to select which version of a student's view of a
                   9947: Task should be displayed.  Either launches a pop-up window, or replaces
                   9948: content in existing pop-up, or replaces page in main window.
                   9949: 
                   9950: Inputs: 4
                   9951:         symb    - unique symb for current instance of resource
                   9952:         uname   - username of student
                   9953:         udom    - domain of student
                   9954:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   9955:                   breadcrumbs etc., are displayed
                   9956: 
                   9957: Output: 4
                   9958:         current   - student's current version
                   9959:         displayed - student's version being displayed
                   9960:         result    - scalar containing HTML for web form used to switch to
                   9961:                     a different version (or a link to close window, if pop-up).
                   9962:         js        - javascript for processing selection in versions web form
                   9963: 
                   9964: Side Effects: None.
                   9965: 
                   9966: =item previous_display_javascript()
                   9967: 
                   9968: Inputs: 2
                   9969:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   9970:                   breadcrumbs etc., are displayed.
                   9971:         current - student's current version number.
                   9972: 
                   9973: Output: 1
                   9974:         js      - javascript for processing selection in versions web form.
                   9975: 
                   9976: Side Effects: None.
                   9977: 
                   9978: =back
                   9979: 
                   9980: =head1 Routines to process bubblesheet data.
                   9981: 
                   9982: =over 4
                   9983: 
1.531     jms      9984: =item scantron_get_correction() : 
                   9985: 
                   9986:    Builds the interface screen to interact with the operator to fix a
                   9987:    specific error condition in a specific scanline
                   9988: 
                   9989:  Arguments:
                   9990:     $r           - Apache request object
                   9991:     $i           - number of the current scanline
                   9992:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9993:     $scan_config - hash ref as returned from &get_scantron_config()
                   9994:     $line        - full contents of the current scanline
                   9995:     $error       - error condition, valid values are
                   9996:                    'incorrectCODE', 'duplicateCODE',
                   9997:                    'doublebubble', 'missingbubble',
                   9998:                    'duplicateID', 'incorrectID'
                   9999:     $arg         - extra information needed
                   10000:        For errors:
                   10001:          - duplicateID   - paper number that this studentID was seen before on
                   10002:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10003:                            seen on before
                   10004:          - incorrectCODE - current incorrect CODE 
                   10005:          - doublebubble  - array ref of the bubble lines that have double
                   10006:                            bubble errors
                   10007:          - missingbubble - array ref of the bubble lines that have missing
                   10008:                            bubble errors
                   10009: 
                   10010: =item  scantron_get_maxbubble() : 
                   10011: 
1.582     raeburn  10012:    Arguments:
                   10013:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10014:                       failure to retrieve a navmap object.
                   10015:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10016:        calling routine should trap the error condition and display the warning
                   10017:        found in &navmap_errormsg().
                   10018: 
1.649     raeburn  10019:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10020: 
1.531     jms      10021:    Returns the maximum number of bubble lines that are expected to
                   10022:    occur. Does this by walking the selected sequence rendering the
                   10023:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10024:    for what the current value of the problem counter is.
                   10025: 
                   10026:    Caches the results to $env{'form.scantron_maxbubble'},
                   10027:    $env{'form.scantron.bubble_lines.n'}, 
                   10028:    $env{'form.scantron.first_bubble_line.n'} and
                   10029:    $env{"form.scantron.sub_bubblelines.n"}
                   10030:    which are the total number of bubble, lines, the number of bubble
                   10031:    lines for response n and number of the first bubble line for response n,
                   10032:    and a comma separated list of numbers of bubble lines for sub-questions
                   10033:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10034: 
                   10035: 
                   10036: =item  scantron_validate_missingbubbles() : 
                   10037: 
                   10038:    Validates all scanlines in the selected file to not have any
                   10039:     answers that don't have bubbles that have not been verified
                   10040:     to be bubble free.
                   10041: 
                   10042: =item  scantron_process_students() : 
                   10043: 
1.659     raeburn  10044:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10045: 
                   10046:    The parsed scanline hash is added to %env 
                   10047: 
                   10048:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10049:    foreach resource , with the form data of
                   10050: 
                   10051: 	'submitted'     =>'scantron' 
                   10052: 	'grade_target'  =>'grade',
                   10053: 	'grade_username'=> username of student
                   10054: 	'grade_domain'  => domain of student
                   10055: 	'grade_courseid'=> of course
                   10056: 	'grade_symb'    => symb of resource to grade
                   10057: 
                   10058:     This triggers a grading pass. The problem grading code takes care
                   10059:     of converting the bubbled letter information (now in %env) into a
                   10060:     valid submission.
                   10061: 
                   10062: =item  scantron_upload_scantron_data() :
                   10063: 
1.659     raeburn  10064:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10065: 
                   10066: =item  scantron_upload_scantron_data_save() : 
                   10067: 
                   10068:    Adds a provided bubble information data file to the course if user
                   10069:    has the correct privileges to do so. 
                   10070: 
                   10071: =item  valid_file() :
                   10072: 
                   10073:    Validates that the requested bubble data file exists in the course.
                   10074: 
                   10075: =item  scantron_download_scantron_data() : 
                   10076: 
                   10077:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10078:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10079:    course.
                   10080: 
                   10081: =item  scantron_validate_ID() : 
                   10082: 
                   10083:    Validates all scanlines in the selected file to not have any
1.556     weissno  10084:    invalid or underspecified student/employee IDs
1.531     jms      10085: 
1.582     raeburn  10086: =item navmap_errormsg() :
                   10087: 
                   10088:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10089:    Should be called whenever the request to instantiate a navmap object fails.
                   10090: 
                   10091: =back
1.582     raeburn  10092: 
1.531     jms      10093: =back
                   10094: 
                   10095: =cut

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