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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.654   ! raeburn     4: # $Id: grades.pm,v 1.653 2011/10/01 15:48:18 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.170     albertel   48: use String::Similarity;
1.359     www        49: use LONCAPA;
                     50: 
1.315     bowersj2   51: use POSIX qw(floor);
1.87      www        52: 
1.435     foxr       53: 
1.513     foxr       54: 
1.435     foxr       55: my %perm=();
1.447     foxr       56: 
1.513     foxr       57: #  These variables are used to recover from ssi errors
                     58: 
                     59: my $ssi_retries = 5;
                     60: my $ssi_error;
                     61: my $ssi_error_resource;
                     62: my $ssi_error_message;
                     63: 
                     64: 
                     65: sub ssi_with_retries {
                     66:     my ($resource, $retries, %form) = @_;
                     67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     68:     if ($response->is_error) {
                     69: 	$ssi_error          = 1;
                     70: 	$ssi_error_resource = $resource;
                     71: 	$ssi_error_message  = $response->code . " " . $response->message;
                     72:     }
                     73: 
                     74:     return $content;
                     75: 
                     76: }
                     77: #
                     78: #  Prodcuces an ssi retry failure error message to the user:
                     79: #
                     80: 
                     81: sub ssi_print_error {
                     82:     my ($r) = @_;
1.516     raeburn    83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     84:     $r->print('
                     85: <br />
                     86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     87: <p>
                     88: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     90: '.&mt('Error:').' '.$ssi_error_message.'
                     91: </p>
                     92: <p>'.
                     93: &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 />'.
                     94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     95: '</p>');
                     96:     return;
1.513     foxr       97: }
                     98: 
1.44      ng         99: #
1.146     albertel  100: # --- Retrieve the parts from the metadata file.---
1.598     www       101: # Returns an array of everything that the resources stores away
                    102: #
                    103: 
1.44      ng        104: sub getpartlist {
1.582     raeburn   105:     my ($symb,$errorref) = @_;
1.439     albertel  106: 
                    107:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   108:     unless (ref($navmap)) {
                    109:         if (ref($errorref)) { 
                    110:             $$errorref = 'navmap';
                    111:             return;
                    112:         }
                    113:     }
1.439     albertel  114:     my $res      = $navmap->getBySymb($symb);
                    115:     my $partlist = $res->parts();
                    116:     my $url      = $res->src();
                    117:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    118: 
1.146     albertel  119:     my @stores;
1.439     albertel  120:     foreach my $part (@{ $partlist }) {
1.146     albertel  121: 	foreach my $key (@metakeys) {
                    122: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    123: 	}
                    124:     }
                    125:     return @stores;
1.2       albertel  126: }
                    127: 
1.129     ng        128: #--- Format fullname, username:domain if different for display
                    129: #--- Use anywhere where the student names are listed
                    130: sub nameUserString {
                    131:     my ($type,$fullname,$uname,$udom) = @_;
                    132:     if ($type eq 'header') {
1.485     albertel  133: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        134:     } else {
1.398     albertel  135: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    136: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        137:     }
                    138: }
                    139: 
1.44      ng        140: #--- Get the partlist and the response type for a given problem. ---
                    141: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       142: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        143: sub response_type {
1.582     raeburn   144:     my ($symb,$response_error) = @_;
1.377     albertel  145: 
                    146:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   147:     unless (ref($navmap)) {
                    148:         if (ref($response_error)) {
                    149:             $$response_error = 1;
                    150:         }
                    151:         return;
                    152:     }
1.377     albertel  153:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   154:     unless (ref($res)) {
                    155:         $$response_error = 1;
                    156:         return;
                    157:     }
1.377     albertel  158:     my $partlist = $res->parts();
1.392     albertel  159:     my %vPart = 
                    160: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  161:     my (%response_types,%handgrade);
                    162:     foreach my $part (@{ $partlist }) {
1.392     albertel  163: 	next if (%vPart && !exists($vPart{$part}));
                    164: 
1.377     albertel  165: 	my @types = $res->responseType($part);
                    166: 	my @ids = $res->responseIds($part);
                    167: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    168: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    169: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    170: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    171: 				     '.handgrade',$symb);
1.41      ng        172: 	}
                    173:     }
1.377     albertel  174:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        175: }
                    176: 
1.375     albertel  177: sub flatten_responseType {
                    178:     my ($responseType) = @_;
                    179:     my @part_response_id =
                    180: 	map { 
                    181: 	    my $part = $_;
                    182: 	    map {
                    183: 		[$part,$_]
                    184: 		} sort(keys(%{ $responseType->{$part} }));
                    185: 	} sort(keys(%$responseType));
                    186:     return @part_response_id;
                    187: }
                    188: 
1.207     albertel  189: sub get_display_part {
1.324     albertel  190:     my ($partID,$symb)=@_;
1.207     albertel  191:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    192:     if (defined($display) and $display ne '') {
1.577     bisitz    193:         $display.= ' (<span class="LC_internal_info">'
                    194:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  195:     } else {
                    196: 	$display=$partID;
                    197:     }
                    198:     return $display;
                    199: }
1.269     raeburn   200: 
1.434     albertel  201: sub reset_caches {
                    202:     &reset_analyze_cache();
                    203:     &reset_perm();
                    204: }
                    205: 
                    206: {
                    207:     my %analyze_cache;
1.557     raeburn   208:     my %analyze_cache_formkeys;
1.148     albertel  209: 
1.434     albertel  210:     sub reset_analyze_cache {
                    211: 	undef(%analyze_cache);
1.557     raeburn   212:         undef(%analyze_cache_formkeys);
1.434     albertel  213:     }
                    214: 
                    215:     sub get_analyze {
1.649     raeburn   216: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  217: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   218:         if ($type eq 'randomizetry') {
                    219:             if ($trial ne '') {
                    220:                 $key .= "\0".$trial;
                    221:             }
                    222:         }
1.557     raeburn   223: 	if (exists($analyze_cache{$key})) {
                    224:             my $getupdate = 0;
                    225:             if (ref($add_to_hash) eq 'HASH') {
                    226:                 foreach my $item (keys(%{$add_to_hash})) {
                    227:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    228:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    229:                             $getupdate = 1;
                    230:                             last;
                    231:                         }
                    232:                     } else {
                    233:                         $getupdate = 1;
                    234:                     }
                    235:                 }
                    236:             }
                    237:             if (!$getupdate) {
                    238:                 return $analyze_cache{$key};
                    239:             }
                    240:         }
1.434     albertel  241: 
                    242: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    243: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   244:         my %form = ('grade_target'      => 'analyze',
                    245:                     'grade_domain'      => $udom,
                    246:                     'grade_symb'        => $symb,
                    247:                     'grade_courseid'    =>  $env{'request.course.id'},
                    248:                     'grade_username'    => $uname,
                    249:                     'grade_noincrement' => $no_increment);
1.649     raeburn   250:         if ($bubbles_per_row ne '') {
                    251:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    252:         }
1.640     raeburn   253:         if ($type eq 'randomizetry') {
                    254:             $form{'grade_questiontype'} = $type;
                    255:             if ($rndseed ne '') {
                    256:                 $form{'grade_rndseed'} = $rndseed;
                    257:             }
                    258:         }
1.557     raeburn   259:         if (ref($add_to_hash)) {
                    260:             %form = (%form,%{$add_to_hash});
1.640     raeburn   261:         }
1.557     raeburn   262: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  263: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    264: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   265:         if (ref($add_to_hash) eq 'HASH') {
                    266:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    267:         } else {
                    268:             $analyze_cache_formkeys{$key} = {};
                    269:         }
1.434     albertel  270: 	return $analyze_cache{$key} = \%analyze;
                    271:     }
                    272: 
                    273:     sub get_order {
1.640     raeburn   274: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    275: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  276: 	return $analyze->{"$partid.$respid.shown"};
                    277:     }
                    278: 
                    279:     sub get_radiobutton_correct_foil {
1.640     raeburn   280: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    281: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    282:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   283:         if (ref($foils) eq 'ARRAY') {
                    284: 	    foreach my $foil (@{$foils}) {
                    285: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    286: 		    return $foil;
                    287: 	        }
1.434     albertel  288: 	    }
                    289: 	}
                    290:     }
1.554     raeburn   291: 
                    292:     sub scantron_partids_tograde {
1.649     raeburn   293:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   294:         my (%analysis,@parts);
                    295:         if (ref($resource)) {
                    296:             my $symb = $resource->symb();
1.557     raeburn   297:             my $add_to_form;
                    298:             if ($check_for_randomlist) {
                    299:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    300:             }
1.649     raeburn   301:             my $analyze = 
                    302:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    303:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   304:             if (ref($analyze) eq 'HASH') {
                    305:                 %analysis = %{$analyze};
                    306:             }
                    307:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    308:                 foreach my $part (@{$analysis{'parts'}}) {
                    309:                     my ($id,$respid) = split(/\./,$part);
                    310:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    311:                         push(@parts,$part);
                    312:                     }
                    313:                 }
                    314:             }
                    315:         }
                    316:         return (\%analysis,\@parts);
                    317:     }
                    318: 
1.148     albertel  319: }
1.434     albertel  320: 
1.118     ng        321: #--- Clean response type for display
1.335     albertel  322: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    323: #        response types only.
1.118     ng        324: sub cleanRecord {
1.336     albertel  325:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   326: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  327:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  328:     if ($response =~ /^(option|rank)$/) {
                    329: 	my %answer=&Apache::lonnet::str2hash($answer);
                    330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    331: 	my ($toprow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    if ($grading{$foil} == 1) {
                    334: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    335: 	    } else {
                    336: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    337: 	    }
1.398     albertel  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  339: 	}
                    340: 	return '<blockquote><table border="1">'.
1.466     albertel  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  343: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    344:     } elsif ($response eq 'match') {
                    345: 	my %answer=&Apache::lonnet::str2hash($answer);
                    346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    347: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    348: 	my ($toprow,$middlerow,$bottomrow);
                    349: 	foreach my $foil (@$order) {
                    350: 	    my $item=shift(@items);
                    351: 	    if ($grading{$foil} == 1) {
                    352: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  353: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  354: 	    } else {
                    355: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  356: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  357: 	    }
1.398     albertel  358: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        359: 	}
1.126     ng        360: 	return '<blockquote><table border="1">'.
1.466     albertel  361: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    362: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  363: 	    $middlerow.'</tr>'.
1.466     albertel  364: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  365: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    366:     } elsif ($response eq 'radiobutton') {
                    367: 	my %answer=&Apache::lonnet::str2hash($answer);
                    368: 	my ($toprow,$bottomrow);
1.434     albertel  369: 	my $correct = 
1.640     raeburn   370: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  371: 	foreach my $foil (@$order) {
1.148     albertel  372: 	    if (exists($answer{$foil})) {
1.434     albertel  373: 		if ($foil eq $correct) {
1.466     albertel  374: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  375: 		} else {
1.466     albertel  376: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  377: 		}
                    378: 	    } else {
1.466     albertel  379: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  380: 	    }
1.398     albertel  381: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  382: 	}
                    383: 	return '<blockquote><table border="1">'.
1.466     albertel  384: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  386: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  387:     } elsif ($response eq 'essay') {
1.257     albertel  388: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        389: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  390: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    391: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        392: 
1.257     albertel  393: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    394: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    395: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    396: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    397: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    398: 	    $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        399: 	}
1.166     albertel  400: 	$answer =~ s-\n-<br />-g;
                    401: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  402:     } elsif ( $response eq 'organic') {
                    403: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    404: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    405: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    406: 	return $result;
1.335     albertel  407:     } elsif ( $response eq 'Task') {
                    408: 	if ( $answer eq 'SUBMITTED') {
                    409: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  410: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  411: 	    return $result;
                    412: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    413: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    414: 			       keys(%{$record}));
                    415: 	    return join('<br />',($version,@matches));
                    416: 			       
                    417: 			       
                    418: 	} else {
                    419: 	    my $result =
                    420: 		'<p>'
                    421: 		.&mt('Overall result: [_1]',
                    422: 		     $record->{$version."resource.$respid.$partid.status"})
                    423: 		.'</p>';
                    424: 	    
                    425: 	    $result .= '<ul>';
                    426: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    427: 			     keys(%{$record}));
                    428: 	    foreach my $grade (sort(@grade)) {
                    429: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    430: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    431: 				     $dim, $record->{$grade}).
                    432: 			  '</li>';
                    433: 	    }
                    434: 	    $result.='</ul>';
                    435: 	    return $result;
                    436: 	}
1.440     albertel  437:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    438: 	$answer = 
                    439: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    440: 							      $answer);
1.122     ng        441:     }
1.118     ng        442:     return $answer;
                    443: }
                    444: 
                    445: #-- A couple of common js functions
                    446: sub commonJSfunctions {
                    447:     my $request = shift;
1.597     wenzelju  448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        449:     function radioSelection(radioButton) {
                    450: 	var selection=null;
                    451: 	if (radioButton.length > 1) {
                    452: 	    for (var i=0; i<radioButton.length; i++) {
                    453: 		if (radioButton[i].checked) {
                    454: 		    return radioButton[i].value;
                    455: 		}
                    456: 	    }
                    457: 	} else {
                    458: 	    if (radioButton.checked) return radioButton.value;
                    459: 	}
                    460: 	return selection;
                    461:     }
                    462: 
                    463:     function pullDownSelection(selectOne) {
                    464: 	var selection="";
                    465: 	if (selectOne.length > 1) {
                    466: 	    for (var i=0; i<selectOne.length; i++) {
                    467: 		if (selectOne[i].selected) {
                    468: 		    return selectOne[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
1.138     albertel  472:             // only one value it must be the selected one
                    473: 	    return selectOne.value;
1.118     ng        474: 	}
                    475:     }
                    476: COMMONJSFUNCTIONS
                    477: }
                    478: 
1.44      ng        479: #--- Dumps the class list with usernames,list of sections,
                    480: #--- section, ids and fullnames for each user.
                    481: sub getclasslist {
1.449     banghart  482:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  483:     my @getsec;
1.450     banghart  484:     my @getgroup;
1.442     banghart  485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  486:     if (!ref($getsec)) {
                    487: 	if ($getsec ne '' && $getsec ne 'all') {
                    488: 	    @getsec=($getsec);
                    489: 	}
                    490:     } else {
                    491: 	@getsec=@{$getsec};
                    492:     }
                    493:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  494:     if (!ref($getgroup)) {
                    495: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    496: 	    @getgroup=($getgroup);
                    497: 	}
                    498:     } else {
                    499: 	@getgroup=@{$getgroup};
                    500:     }
                    501:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  502: 
1.449     banghart  503:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  504:     # Bail out if we were unable to get the classlist
1.56      matthew   505:     return if (! defined($classlist));
1.449     banghart  506:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   507:     #
                    508:     my %sections;
                    509:     my %fullnames;
1.205     matthew   510:     foreach my $student (keys(%$classlist)) {
                    511:         my $end      = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    513:         my $start    = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    515:         my $id       = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    517:         my $section  = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    519:         my $fullname = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    521:         my $status   = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  523:         my $group   = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        525: 	# filter students according to status selected
1.442     banghart  526: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    527: 	    if (!($stu_status =~ $status)) {
1.450     banghart  528: 		delete($classlist->{$student});
1.76      ng        529: 		next;
                    530: 	    }
                    531: 	}
1.450     banghart  532: 	# filter students according to groups selected
1.453     banghart  533: 	my @stu_groups = split(/,/,$group);
1.450     banghart  534: 	if (@getgroup) {
                    535: 	    my $exclude = 1;
1.454     banghart  536: 	    foreach my $grp (@getgroup) {
                    537: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  538: 	            if ($stu_group eq $grp) {
                    539: 	                $exclude = 0;
                    540:     	            } 
1.450     banghart  541: 	        }
1.453     banghart  542:     	        if (($grp eq 'none') && !$group) {
                    543:         	        $exclude = 0;
                    544:         	}
1.450     banghart  545: 	    }
                    546: 	    if ($exclude) {
                    547: 	        delete($classlist->{$student});
                    548: 	    }
                    549: 	}
1.205     matthew   550: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  551: 	if (&canview($section)) {
1.291     albertel  552: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  553: 		$sections{$section}++;
1.450     banghart  554: 		if ($classlist->{$student}) {
                    555: 		    $fullnames{$student}=$fullname;
                    556: 		}
1.103     albertel  557: 	    } else {
1.205     matthew   558: 		delete($classlist->{$student});
1.103     albertel  559: 	    }
                    560: 	} else {
1.205     matthew   561: 	    delete($classlist->{$student});
1.103     albertel  562: 	}
1.44      ng        563:     }
                    564:     my %seen = ();
1.56      matthew   565:     my @sections = sort(keys(%sections));
                    566:     return ($classlist,\@sections,\%fullnames);
1.44      ng        567: }
                    568: 
1.103     albertel  569: sub canmodify {
                    570:     my ($sec)=@_;
                    571:     if ($perm{'mgr'}) {
                    572: 	if (!defined($perm{'mgr_section'})) {
                    573: 	    # can modify whole class
                    574: 	    return 1;
                    575: 	} else {
                    576: 	    if ($sec eq $perm{'mgr_section'}) {
                    577: 		#can modify the requested section
                    578: 		return 1;
                    579: 	    } else {
                    580: 		# can't modify the request section
                    581: 		return 0;
                    582: 	    }
                    583: 	}
                    584:     }
                    585:     #can't modify
                    586:     return 0;
                    587: }
                    588: 
                    589: sub canview {
                    590:     my ($sec)=@_;
                    591:     if ($perm{'vgr'}) {
                    592: 	if (!defined($perm{'vgr_section'})) {
                    593: 	    # can modify whole class
                    594: 	    return 1;
                    595: 	} else {
                    596: 	    if ($sec eq $perm{'vgr_section'}) {
                    597: 		#can modify the requested section
                    598: 		return 1;
                    599: 	    } else {
                    600: 		# can't modify the request section
                    601: 		return 0;
                    602: 	    }
                    603: 	}
                    604:     }
                    605:     #can't modify
                    606:     return 0;
                    607: }
                    608: 
1.44      ng        609: #--- Retrieve the grade status of a student for all the parts
                    610: sub student_gradeStatus {
1.324     albertel  611:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  612:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        613:     my %partstatus = ();
                    614:     foreach (@$partlist) {
1.128     ng        615: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        616: 	$status              = 'nothing' if ($status eq '');
                    617: 	$partstatus{$_}      = $status;
                    618: 	my $subkey           = "resource.$_.submitted_by";
                    619: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    620:     }
                    621:     return %partstatus;
                    622: }
                    623: 
1.45      ng        624: # hidden form and javascript that calls the form
                    625: # Use by verifyscript and viewgrades
                    626: # Shows a student's view of problem and submission
                    627: sub jscriptNform {
1.324     albertel  628:     my ($symb) = @_;
1.442     banghart  629:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  630:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        631: 	'    function viewOneStudent(user,domain) {'."\n".
                    632: 	'	document.onestudent.student.value = user;'."\n".
                    633: 	'	document.onestudent.userdom.value = domain;'."\n".
                    634: 	'	document.onestudent.submit();'."\n".
                    635: 	'    }'."\n".
1.597     wenzelju  636: 	"\n");
1.45      ng        637:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  639: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        640: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    641: 	'<input type="hidden" name="student" value="" />'."\n".
                    642: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    643: 	'</form>'."\n";
                    644:     return $jscript;
                    645: }
1.39      ng        646: 
1.447     foxr      647: 
                    648: 
1.315     bowersj2  649: # Given the score (as a number [0-1] and the weight) what is the final
                    650: # point value? This function will round to the nearest tenth, third,
                    651: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  652: sub compute_points {
1.315     bowersj2  653:     my ($score, $weight) = @_;
                    654:     
                    655:     my $tolerance = .00001;
                    656:     my $points = $score * $weight;
                    657: 
                    658:     # Check for nearness to 1/x.
                    659:     my $check_for_nearness = sub {
                    660:         my ($factor) = @_;
                    661:         my $num = ($points * $factor) + $tolerance;
                    662:         my $floored_num = floor($num);
1.316     albertel  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  664:             return $floored_num / $factor;
                    665:         }
                    666:         return $points;
                    667:     };
                    668: 
                    669:     $points = $check_for_nearness->(10);
                    670:     $points = $check_for_nearness->(3);
                    671:     $points = $check_for_nearness->(4);
                    672:     
                    673:     return $points;
                    674: }
                    675: 
1.44      ng        676: #------------------ End of general use routines --------------------
1.87      www       677: 
                    678: #
                    679: # Find most similar essay
                    680: #
                    681: 
                    682: sub most_similar {
1.426     albertel  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       684: 
                    685: # ignore spaces and punctuation
                    686: 
                    687:     $uessay=~s/\W+/ /gs;
                    688: 
1.282     www       689: # ignore empty submissions (occuring when only files are sent)
                    690: 
1.598     www       691:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       692: 
1.87      www       693: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       694:     my $limit=0.6;
1.87      www       695:     my $sname='';
                    696:     my $sdom='';
                    697:     my $scrsid='';
                    698:     my $sessay='';
                    699: # go through all essays ...
1.426     albertel  700:     foreach my $tkey (keys(%$old_essays)) {
                    701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       702: # ... except the same student
1.426     albertel  703:         next if (($tname eq $uname) && ($tdom eq $udom));
                    704: 	my $tessay=$old_essays->{$tkey};
                    705: 	$tessay=~s/\W+/ /gs;
1.87      www       706: # String similarity gives up if not even limit
1.426     albertel  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       708: # Found one
1.426     albertel  709: 	if ($tsimilar>$limit) {
                    710: 	    $limit=$tsimilar;
                    711: 	    $sname=$tname;
                    712: 	    $sdom=$tdom;
                    713: 	    $scrsid=$tcrsid;
                    714: 	    $sessay=$old_essays->{$tkey};
                    715: 	}
1.87      www       716:     }
1.88      www       717:     if ($limit>0.6) {
1.87      www       718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    719:     } else {
                    720:        return ('','','','',0);
                    721:     }
                    722: }
                    723: 
1.44      ng        724: #-------------------------------------------------------------------
                    725: 
                    726: #------------------------------------ Receipt Verification Routines
1.45      ng        727: #
1.602     www       728: 
                    729: sub initialverifyreceipt {
1.608     www       730:    my ($request,$symb) = @_;
1.602     www       731:    &commonJSfunctions($request);
1.605     www       732:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       733:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    734:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       735:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    736:         '<input type="hidden" name="command" value="verify" />'.
                    737:         "</form>\n";
1.602     www       738: }
                    739: 
1.44      ng        740: #--- Check whether a receipt number is valid.---
                    741: sub verifyreceipt {
1.608     www       742:     my ($request,$symb)  = @_;
1.44      ng        743: 
1.257     albertel  744:     my $courseid = $env{'request.course.id'};
1.184     www       745:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  746: 	$env{'form.receipt'};
1.44      ng        747:     $receipt     =~ s/[^\-\d]//g;
                    748: 
1.487     albertel  749:     my $title.=
                    750: 	'<h3><span class="LC_info">'.
1.605     www       751: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    752: 	'</span></h3>'."\n";
1.44      ng        753: 
                    754:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   755:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  756:     
                    757:     my $receiptparts=0;
1.390     albertel  758:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    759: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  760:     my $parts=['0'];
1.582     raeburn   761:     if ($receiptparts) {
                    762:         my $res_error; 
                    763:         ($parts)=&response_type($symb,\$res_error);
                    764:         if ($res_error) {
                    765:             return &navmap_errormsg();
                    766:         } 
                    767:     }
1.486     albertel  768:     
                    769:     my $header = 
                    770: 	&Apache::loncommon::start_data_table().
                    771: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  772: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    773: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    774: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  775:     if ($receiptparts) {
1.487     albertel  776: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  777:     }
                    778:     $header.=
                    779: 	&Apache::loncommon::end_data_table_header_row();
                    780: 
1.294     albertel  781:     foreach (sort 
                    782: 	     {
                    783: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    784: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    785: 		 }
                    786: 		 return $a cmp $b;
                    787: 	     } (keys(%$fullname))) {
1.44      ng        788: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  789: 	foreach my $part (@$parts) {
                    790: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  791: 		$contents.=
                    792: 		    &Apache::loncommon::start_data_table_row().
                    793: 		    '<td>&nbsp;'."\n".
1.177     albertel  794: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  795: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  796: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    797: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    798: 		if ($receiptparts) {
                    799: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    800: 		}
1.486     albertel  801: 		$contents.= 
                    802: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  803: 		
                    804: 		$matches++;
                    805: 	    }
1.44      ng        806: 	}
                    807:     }
                    808:     if ($matches == 0) {
1.584     bisitz    809:         $string = $title
                    810:                  .'<p class="LC_warning">'
                    811:                  .&mt('No match found for the above receipt number.')
                    812:                  .'</p>';
1.44      ng        813:     } else {
1.324     albertel  814: 	$string = &jscriptNform($symb).$title.
1.487     albertel  815: 	    '<p>'.
1.584     bisitz    816: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  817: 	    '</p>'.
1.486     albertel  818: 	    $header.
                    819: 	    $contents.
                    820: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        821:     }
1.614     www       822:     return $string;
1.44      ng        823: }
                    824: 
                    825: #--- This is called by a number of programs.
                    826: #--- Called from the Grading Menu - View/Grade an individual student
                    827: #--- Also called directly when one clicks on the subm button 
                    828: #    on the problem page.
1.30      ng        829: sub listStudents {
1.617     www       830:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  831: 
1.257     albertel  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       836:     unless ($submitonly) {
                    837:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    838:     }
1.49      albertel  839: 
1.632     www       840:     my $result='';
1.623     www       841:     my $res_error;
                    842:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  843: 
1.559     raeburn   844:     my %lt = &Apache::lonlocal::texthash (
                    845: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    846: 		'single'   => 'Please select the student before clicking on the Next button.',
                    847: 	     );
1.597     wenzelju  848:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        849:     function checkSelect(checkBox) {
                    850: 	var ctr=0;
                    851: 	var sense="";
                    852: 	if (checkBox.length > 1) {
                    853: 	    for (var i=0; i<checkBox.length; i++) {
                    854: 		if (checkBox[i].checked) {
                    855: 		    ctr++;
                    856: 		}
                    857: 	    }
1.485     albertel  858: 	    sense = '$lt{'multiple'}';
1.110     ng        859: 	} else {
                    860: 	    if (checkBox.checked) {
                    861: 		ctr = 1;
                    862: 	    }
1.485     albertel  863: 	    sense = '$lt{'single'}';
1.110     ng        864: 	}
                    865: 	if (ctr == 0) {
1.485     albertel  866: 	    alert(sense);
1.110     ng        867: 	    return false;
                    868: 	}
                    869: 	document.gradesub.submit();
                    870:     }
                    871: 
                    872:     function reLoadList(formname) {
1.112     ng        873: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        874: 	formname.command.value = 'submission';
                    875: 	formname.submit();
                    876:     }
1.45      ng        877: LISTJAVASCRIPT
                    878: 
1.118     ng        879:     &commonJSfunctions($request);
1.41      ng        880:     $request->print($result);
1.39      ng        881: 
1.154     albertel  882:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       883: 	"\n";
1.485     albertel  884: 	
1.561     bisitz    885:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    886:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    887:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    888:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    889:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    890:                   .&Apache::lonhtmlcommon::row_closure();
                    891:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    892:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    893:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    894:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    895:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  896: 
                    897:     my $submission_options;
1.442     banghart  898:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    899:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  900:     $env{'form.Status'} = $saveStatus;
1.485     albertel  901:     $submission_options.=
1.592     bisitz    902:         '<span class="LC_nobreak">'.
1.624     www       903:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    904:         &mt('last submission only').' </label></span>'."\n".
                    905:         '<span class="LC_nobreak">'.
                    906:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    907:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    908:         '<span class="LC_nobreak">'.
1.628     www       909:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    910:         &mt('by dates and submissions').'</label></span>'."\n".
                    911:         '<span class="LC_nobreak">'.
                    912:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    913:         &mt('all details').'</label></span>';
1.561     bisitz    914:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    915:                   .$submission_options
                    916:                   .&Apache::lonhtmlcommon::row_closure();
                    917: 
                    918:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    919:                   .'<select name="increment">'
                    920:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    921:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    922:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    923:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    924:                   .'</select>'
                    925:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  926: 
                    927:     $gradeTable .= 
1.432     banghart  928:         &build_section_inputs().
1.45      ng        929: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  930: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        931: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    932: 
1.618     www       933:     if (exists($env{'form.Status'})) {
1.561     bisitz    934: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        935:     } else {
1.561     bisitz    936:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    937:                       .&Apache::lonhtmlcommon::StatusOptions(
                    938:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    939:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        940:     }
1.112     ng        941: 
1.561     bisitz    942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    943:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    944:                   .&Apache::lonhtmlcommon::row_closure(1)
                    945:                   .&Apache::lonhtmlcommon::end_pick_box();
                    946: 
                    947:     $gradeTable .= '<p>'
1.618     www       948:                   .&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    949:                   .'<input type="hidden" name="command" value="processGroup" />'
                    950:                   .'</p>';
1.249     albertel  951: 
                    952: # checkall buttons
                    953:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        954:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    955:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    956:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  957:     $gradeTable.=&check_buttons();
1.450     banghart  958:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  959:     $gradeTable.= &Apache::loncommon::start_data_table().
                    960: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        961:     my $loop = 0;
                    962:     while ($loop < 2) {
1.485     albertel  963: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    964: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       965: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  966: 	    foreach my $part (sort(@$partlist)) {
                    967: 		my $display_part=
                    968: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    969: 		$gradeTable.=
                    970: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        971: 	    }
1.301     albertel  972: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  973: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        974: 	}
                    975: 	$loop++;
1.126     ng        976: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        977:     }
1.474     albertel  978:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        979: 
1.45      ng        980:     my $ctr = 0;
1.294     albertel  981:     foreach my $student (sort 
                    982: 			 {
                    983: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    984: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    985: 			     }
                    986: 			     return $a cmp $b;
                    987: 			 }
                    988: 			 (keys(%$fullname))) {
1.41      ng        989: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  990: 
1.110     ng        991: 	my %status = ();
1.301     albertel  992: 
                    993: 	if ($submitonly eq 'queued') {
                    994: 	    my %queue_status = 
                    995: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    996: 							$udom,$uname);
                    997: 	    next if (!defined($queue_status{'gradingqueue'}));
                    998: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    999: 	}
                   1000: 
1.618     www      1001: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1002: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1003: 	    my $submitted = 0;
1.164     albertel 1004: 	    my $graded = 0;
1.248     albertel 1005: 	    my $incorrect = 0;
1.110     ng       1006: 	    foreach (keys(%status)) {
1.145     albertel 1007: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1008: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1009: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1010: 		
1.110     ng       1011: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1012: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1013: 		    $submitted = 0;
1.150     albertel 1014: 		    my ($part)=split(/\./,$partid);
1.110     ng       1015: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1016: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1017: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1018: 		}
1.41      ng       1019: 	    }
1.248     albertel 1020: 	    
1.156     albertel 1021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1022: 				     $submitonly eq 'incorrect' ||
                   1023: 				     $submitonly eq 'graded'));
1.248     albertel 1024: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1026: 	}
1.34      ng       1027: 
1.45      ng       1028: 	$ctr++;
1.249     albertel 1029: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1030:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1031: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1032: 	    if ($ctr%2 ==1) {
                   1033: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1034: 	    }
1.126     ng       1035: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1036:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1037:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1038: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1039: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1040: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1041: 
1.618     www      1042: 	    if ($submitonly ne 'all') {
1.524     raeburn  1043: 		foreach (sort(keys(%status))) {
1.485     albertel 1044: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1045: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1046: 		}
1.41      ng       1047: 	    }
1.126     ng       1048: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1049: 	    if ($ctr%2 ==0) {
                   1050: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1051: 	    }
1.41      ng       1052: 	}
                   1053:     }
1.110     ng       1054:     if ($ctr%2 ==1) {
1.126     ng       1055: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1056: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1057: 		foreach (@$partlist) {
                   1058: 		    $gradeTable.='<td>&nbsp;</td>';
                   1059: 		}
1.301     albertel 1060: 	    } elsif ($submitonly eq 'queued') {
                   1061: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1062: 	    }
1.474     albertel 1063: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1064:     }
                   1065: 
1.474     albertel 1066:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1067:         '<input type="button" '.
                   1068:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1069:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1070:     if ($ctr == 0) {
1.96      albertel 1071: 	my $num_students=(scalar(keys(%$fullname)));
                   1072: 	if ($num_students eq 0) {
1.485     albertel 1073: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1074: 	} else {
1.171     albertel 1075: 	    my $submissions='submissions';
                   1076: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1077: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1078: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1079: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1080: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1081: 		    $num_students).
                   1082: 		'</span><br />';
1.96      albertel 1083: 	}
1.46      ng       1084:     } elsif ($ctr == 1) {
1.474     albertel 1085: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1086:     }
                   1087:     $request->print($gradeTable);
1.44      ng       1088:     return '';
1.10      ng       1089: }
                   1090: 
1.44      ng       1091: #---- Called from the listStudents routine
1.249     albertel 1092: 
                   1093: sub check_script {
                   1094:     my ($form, $type)=@_;
1.597     wenzelju 1095:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1096:     function checkall() {
                   1097:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1098:             ele = document.forms.'.$form.'.elements[i];
                   1099:             if (ele.name == "'.$type.'") {
                   1100:             document.forms.'.$form.'.elements[i].checked=true;
                   1101:                                        }
                   1102:         }
                   1103:     }
                   1104: 
                   1105:     function checksec() {
                   1106:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1107:             ele = document.forms.'.$form.'.elements[i];
                   1108:            string = document.forms.'.$form.'.chksec.value;
                   1109:            if
                   1110:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1111:               document.forms.'.$form.'.elements[i].checked=true;
                   1112:             }
                   1113:         }
                   1114:     }
                   1115: 
                   1116: 
                   1117:     function uncheckall() {
                   1118:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1119:             ele = document.forms.'.$form.'.elements[i];
                   1120:             if (ele.name == "'.$type.'") {
                   1121:             document.forms.'.$form.'.elements[i].checked=false;
                   1122:                                        }
                   1123:         }
                   1124:     }
                   1125: 
1.597     wenzelju 1126: '."\n");
1.249     albertel 1127:     return $chkallscript;
                   1128: }
                   1129: 
                   1130: sub check_buttons {
1.485     albertel 1131:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1132:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1133:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1134:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1135:     return $buttons;
                   1136: }
                   1137: 
1.44      ng       1138: #     Displays the submissions for one student or a group of students
1.34      ng       1139: sub processGroup {
1.619     www      1140:     my ($request,$symb)  = @_;
1.41      ng       1141:     my $ctr        = 0;
1.155     albertel 1142:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1143:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1144: 
1.396     banghart 1145:     foreach my $student (@stuchecked) {
                   1146: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1147: 	$env{'form.student'}        = $uname;
                   1148: 	$env{'form.userdom'}        = $udom;
                   1149: 	$env{'form.fullname'}       = $fullname;
1.619     www      1150: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1151: 	$ctr++;
                   1152:     }
                   1153:     return '';
1.35      ng       1154: }
1.34      ng       1155: 
1.44      ng       1156: #------------------------------------------------------------------------------------
                   1157: #
                   1158: #-------------------------- Next few routines handles grading by student, essentially
                   1159: #                           handles essay response type problem/part
                   1160: #
                   1161: #--- Javascript to handle the submission page functionality ---
                   1162: sub sub_page_js {
                   1163:     my $request = shift;
1.539     riegler  1164: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1165:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1166:     function updateRadio(formname,id,weight) {
1.125     ng       1167: 	var gradeBox = formname["GD_BOX"+id];
                   1168: 	var radioButton = formname["RADVAL"+id];
                   1169: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1170: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1171: 	gradeBox.value = pts;
                   1172: 	var resetbox = false;
                   1173: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1174: 	    alert("$alertmsg"+pts);
1.71      ng       1175: 	    for (var i=0; i<radioButton.length; i++) {
                   1176: 		if (radioButton[i].checked) {
                   1177: 		    gradeBox.value = i;
                   1178: 		    resetbox = true;
                   1179: 		}
                   1180: 	    }
                   1181: 	    if (!resetbox) {
                   1182: 		formtextbox.value = "";
                   1183: 	    }
                   1184: 	    return;
1.44      ng       1185: 	}
1.71      ng       1186: 
                   1187: 	if (pts > weight) {
                   1188: 	    var resp = confirm("You entered a value ("+pts+
                   1189: 			       ") greater than the weight for the part. Accept?");
                   1190: 	    if (resp == false) {
1.125     ng       1191: 		gradeBox.value = oldpts;
1.71      ng       1192: 		return;
                   1193: 	    }
1.44      ng       1194: 	}
1.13      albertel 1195: 
1.71      ng       1196: 	for (var i=0; i<radioButton.length; i++) {
                   1197: 	    radioButton[i].checked=false;
                   1198: 	    if (pts == i && pts != "") {
                   1199: 		radioButton[i].checked=true;
                   1200: 	    }
                   1201: 	}
                   1202: 	updateSelect(formname,id);
1.125     ng       1203: 	formname["stores"+id].value = "0";
1.41      ng       1204:     }
1.5       albertel 1205: 
1.72      ng       1206:     function writeBox(formname,id,pts) {
1.125     ng       1207: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1208: 	if (checkSolved(formname,id) == 'update') {
                   1209: 	    gradeBox.value = pts;
                   1210: 	} else {
1.125     ng       1211: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1212: 	    gradeBox.value = oldpts;
1.125     ng       1213: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1214: 	    for (var i=0; i<radioButton.length; i++) {
                   1215: 		radioButton[i].checked=false;
1.72      ng       1216: 		if (i == oldpts) {
1.71      ng       1217: 		    radioButton[i].checked=true;
                   1218: 		}
                   1219: 	    }
1.41      ng       1220: 	}
1.125     ng       1221: 	formname["stores"+id].value = "0";
1.71      ng       1222: 	updateSelect(formname,id);
                   1223: 	return;
1.41      ng       1224:     }
1.44      ng       1225: 
1.71      ng       1226:     function clearRadBox(formname,id) {
                   1227: 	if (checkSolved(formname,id) == 'noupdate') {
                   1228: 	    updateSelect(formname,id);
                   1229: 	    return;
                   1230: 	}
1.125     ng       1231: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1232: 	for (var i=0; i<gradeSelect.length; i++) {
                   1233: 	    if (gradeSelect[i].selected) {
                   1234: 		var selectx=i;
                   1235: 	    }
                   1236: 	}
1.125     ng       1237: 	var stores = formname["stores"+id];
1.71      ng       1238: 	if (selectx == stores.value) { return };
1.125     ng       1239: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1240: 	gradeBox.value = "";
1.125     ng       1241: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1242: 	for (var i=0; i<radioButton.length; i++) {
                   1243: 	    radioButton[i].checked=false;
                   1244: 	}
                   1245: 	stores.value = selectx;
                   1246:     }
1.5       albertel 1247: 
1.71      ng       1248:     function checkSolved(formname,id) {
1.125     ng       1249: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1250: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1251: 	    if (!reply) {return "noupdate";}
1.120     ng       1252: 	    formname.overRideScore.value = 'yes';
1.41      ng       1253: 	}
1.71      ng       1254: 	return "update";
1.13      albertel 1255:     }
1.71      ng       1256: 
                   1257:     function updateSelect(formname,id) {
1.125     ng       1258: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1259: 	return;
1.41      ng       1260:     }
1.33      ng       1261: 
1.121     ng       1262: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1263:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1264: 	formname.gradeOpt.value = val;
1.71      ng       1265: 	if (val == "Save & Next") {
                   1266: 	    for (i=0;i<=total;i++) {
                   1267: 		for (j=0;j<parttot;j++) {
1.125     ng       1268: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1269: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1270: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1271: 			if (points == "") {
1.125     ng       1272: 			    var name = formname["name"+i].value;
1.129     ng       1273: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1274: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1275: 					       ", part "+partid+". Continue?");
1.71      ng       1276: 			    if (resp == false) {
1.125     ng       1277: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1278: 				return false;
                   1279: 			    }
                   1280: 			}
                   1281: 		    }
                   1282: 		    
                   1283: 		}
                   1284: 	    }
                   1285: 	    
                   1286: 	}
1.120     ng       1287: 	formname.submit();
                   1288:     }
                   1289: 
1.71      ng       1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1291:     function checkSubmitPage(formname,total) {
                   1292: 	noscore = new Array(100);
                   1293: 	var ptr = 0;
                   1294: 	for (i=1;i<total;i++) {
1.125     ng       1295: 	    var partid = formname["q_"+i].value;
1.127     ng       1296: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1297: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1298: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1299: 		if (points == "" && status != "correct_by_student") {
                   1300: 		    noscore[ptr] = i;
                   1301: 		    ptr++;
                   1302: 		}
                   1303: 	    }
                   1304: 	}
                   1305: 	if (ptr != 0) {
                   1306: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1307: 	    var prolist = "";
                   1308: 	    if (ptr == 1) {
                   1309: 		prolist = noscore[0];
                   1310: 	    } else {
                   1311: 		var i = 0;
                   1312: 		while (i < ptr-1) {
                   1313: 		    prolist += noscore[i]+", ";
                   1314: 		    i++;
                   1315: 		}
                   1316: 		prolist += "and "+noscore[i];
                   1317: 	    }
                   1318: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1319: 	    if (resp == false) {
                   1320: 		return false;
                   1321: 	    }
                   1322: 	}
1.45      ng       1323: 
1.71      ng       1324: 	formname.submit();
                   1325:     }
                   1326: SUBJAVASCRIPT
                   1327: }
1.45      ng       1328: 
1.71      ng       1329: #--- javascript for essay type problem --
                   1330: sub sub_page_kw_js {
                   1331:     my $request = shift;
1.80      ng       1332:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1333:     &commonJSfunctions($request);
1.350     albertel 1334: 
1.629     www      1335:     my $inner_js_msg_central= (<<INNERJS);
                   1336: <script type="text/javascript">
1.350     albertel 1337:     function checkInput() {
                   1338:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1339:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1340:       var usrctr = document.msgcenter.usrctr.value;
                   1341:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1342:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1343: 
                   1344:       var msgchk = "";
                   1345:       if (document.msgcenter.subchk.checked) {
                   1346:          msgchk = "msgsub,";
                   1347:       }
                   1348:       var includemsg = 0;
                   1349:       for (var i=1; i<=nmsg; i++) {
                   1350:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1351:           var frmmsg = document.msgcenter["msg"+i];
                   1352:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1353:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1354:           showflg.value = "1";
                   1355:           var chkbox = document.msgcenter["msgn"+i];
                   1356:           if (chkbox.checked) {
                   1357:              msgchk += "savemsg"+i+",";
                   1358:              includemsg = 1;
                   1359:           }
                   1360:       }
                   1361:       if (document.msgcenter.newmsgchk.checked) {
                   1362:          msgchk += "newmsg"+usrctr;
                   1363:          includemsg = 1;
                   1364:       }
                   1365:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1366:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1367:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1368:       includemsg.value = msgchk;
                   1369: 
                   1370:       self.close()
                   1371: 
                   1372:     }
1.629     www      1373: </script>
1.350     albertel 1374: INNERJS
                   1375: 
1.629     www      1376:     my $inner_js_highlight_central= (<<INNERJS);
                   1377: <script type="text/javascript">
1.351     albertel 1378:     function updateChoice(flag) {
                   1379:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1380:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1381:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1382:       opener.document.SCORE.refresh.value = "on";
                   1383:       if (opener.document.SCORE.keywords.value!=""){
                   1384:          opener.document.SCORE.submit();
                   1385:       }
                   1386:       self.close()
                   1387:     }
1.629     www      1388: </script>
1.351     albertel 1389: INNERJS
                   1390: 
                   1391:     my $start_page_msg_central = 
                   1392:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1393: 				       {'js_ready'  => 1,
                   1394: 					'only_body' => 1,
                   1395: 					'bgcolor'   =>'#FFFFFF',});
                   1396:     my $end_page_msg_central = 
                   1397: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1398: 
                   1399: 
                   1400:     my $start_page_highlight_central = 
                   1401:         &Apache::loncommon::start_page('Highlight Central',
                   1402: 				       $inner_js_highlight_central,
1.350     albertel 1403: 				       {'js_ready'  => 1,
                   1404: 					'only_body' => 1,
                   1405: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1406:     my $end_page_highlight_central = 
1.350     albertel 1407: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1408: 
1.219     www      1409:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1410:     $docopen=~s/^document\.//;
1.652     raeburn  1411:     my %lt = &Apache::lonlocal::texthash(
                   1412:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1413:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1414:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1415:                 comp => 'Compose Message for: ',
                   1416:                 incl => 'Include',
                   1417:                 subj => 'Subject',
                   1418:                 mesa => 'Message',
                   1419:                 new  => 'New',
                   1420:                 save => 'Save',
                   1421:                 canc => 'Cancel',
                   1422:                 kehi => 'Keyword Highlight Options',
                   1423:                 txtc => 'Text Color',
                   1424:                 font => 'Font Size',
                   1425:              );
1.597     wenzelju 1426:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1427: 
1.44      ng       1428: //===================== Show list of keywords ====================
1.122     ng       1429:   function keywords(formname) {
1.652     raeburn  1430:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1431:     if (nret==null) return;
1.122     ng       1432:     formname.keywords.value = nret;
1.44      ng       1433: 
1.122     ng       1434:     if (formname.keywords.value != "") {
1.128     ng       1435: 	formname.refresh.value = "on";
1.122     ng       1436: 	formname.submit();
1.44      ng       1437:     }
                   1438:     return;
                   1439:   }
                   1440: 
                   1441: //===================== Script to view submitted by ==================
                   1442:   function viewSubmitter(submitter) {
                   1443:     document.SCORE.refresh.value = "on";
                   1444:     document.SCORE.NCT.value = "1";
                   1445:     document.SCORE.unamedom0.value = submitter;
                   1446:     document.SCORE.submit();
                   1447:     return;
                   1448:   }
                   1449: 
                   1450: //===================== Script to add keyword(s) ==================
                   1451:   function getSel() {
                   1452:     if (document.getSelection) txt = document.getSelection();
                   1453:     else if (document.selection) txt = document.selection.createRange().text;
                   1454:     else return;
                   1455:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1456:     if (cleantxt=="") {
1.652     raeburn  1457: 	alert("$lt{'plse'}");
1.44      ng       1458: 	return;
                   1459:     }
1.652     raeburn  1460:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1461:     if (nret==null) return;
1.127     ng       1462:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1463:     if (document.SCORE.keywords.value != "") {
1.127     ng       1464: 	document.SCORE.refresh.value = "on";
1.44      ng       1465: 	document.SCORE.submit();
                   1466:     }
                   1467:     return;
                   1468:   }
                   1469: 
                   1470: //====================== Script for composing message ==============
1.80      ng       1471:    // preload images
                   1472:    img1 = new Image();
                   1473:    img1.src = "$iconpath/mailbkgrd.gif";
                   1474:    img2 = new Image();
                   1475:    img2.src = "$iconpath/mailto.gif";
                   1476: 
1.44      ng       1477:   function msgCenter(msgform,usrctr,fullname) {
                   1478:     var Nmsg  = msgform.savemsgN.value;
                   1479:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1480:     var subject = msgform.msgsub.value;
1.127     ng       1481:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1482:     re = /msgsub/;
                   1483:     var shwsel = "";
                   1484:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1485:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1486:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1487:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1488: 	var testmsg = "savemsg"+i+",";
                   1489: 	re = new RegExp(testmsg,"g");
1.44      ng       1490: 	shwsel = "";
                   1491: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1492: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1493: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1494: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1495: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1496:     }
1.125     ng       1497:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1498:     shwsel = "";
                   1499:     re = /newmsg/;
                   1500:     if (re.test(msgchk)) { shwsel = "checked" }
                   1501:     newMsg(newmsg,shwsel);
                   1502:     msgTail(); 
                   1503:     return;
                   1504:   }
                   1505: 
1.123     ng       1506:   function checkEntities(strx) {
                   1507:     if (strx.length == 0) return strx;
                   1508:     var orgStr = ["&", "<", ">", '"']; 
                   1509:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1510:     var counter = 0;
                   1511:     while (counter < 4) {
                   1512: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1513: 	counter++;
                   1514:     }
                   1515:     return strx;
                   1516:   }
                   1517: 
                   1518:   function strReplace(strx, orgStr, newStr) {
                   1519:     return strx.split(orgStr).join(newStr);
                   1520:   }
                   1521: 
1.44      ng       1522:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1523:     var height = 70*Nmsg+250;
1.44      ng       1524:     var scrollbar = "no";
                   1525:     if (height > 600) {
                   1526: 	height = 600;
                   1527: 	scrollbar = "yes";
                   1528:     }
1.118     ng       1529:     var xpos = (screen.width-600)/2;
                   1530:     xpos = (xpos < 0) ? '0' : xpos;
                   1531:     var ypos = (screen.height-height)/2-30;
                   1532:     ypos = (ypos < 0) ? '0' : ypos;
                   1533: 
1.647     bisitz   1534:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1535:     pWin.focus();
                   1536:     pDoc = pWin.document;
1.219     www      1537:     pDoc.$docopen;
1.351     albertel 1538:     pDoc.write('$start_page_msg_central');
1.76      ng       1539: 
                   1540:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1541:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.652     raeburn  1542:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1543: 
1.564     bisitz   1544:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1545:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.652     raeburn  1546:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1547: }
                   1548:     function displaySubject(msg,shwsel) {
1.76      ng       1549:     pDoc = pWin.document;
                   1550:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1551:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1552:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1553:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1554: }
                   1555: 
1.72      ng       1556:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1557:     pDoc = pWin.document;
                   1558:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1559:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1560:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1561:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1562: }
                   1563: 
                   1564:   function newMsg(newmsg,shwsel) {
1.76      ng       1565:     pDoc = pWin.document;
                   1566:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1567:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1568:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1569:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1570: }
                   1571: 
                   1572:   function msgTail() {
1.76      ng       1573:     pDoc = pWin.document;
1.465     albertel 1574:     pDoc.write("<\\/table>");
                   1575:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1576:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1577:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1578:     pDoc.write("<\\/form>");
1.351     albertel 1579:     pDoc.write('$end_page_msg_central');
1.128     ng       1580:     pDoc.close();
1.44      ng       1581: }
                   1582: 
                   1583: //====================== Script for keyword highlight options ==============
                   1584:   function kwhighlight() {
                   1585:     var kwclr    = document.SCORE.kwclr.value;
                   1586:     var kwsize   = document.SCORE.kwsize.value;
                   1587:     var kwstyle  = document.SCORE.kwstyle.value;
                   1588:     var redsel = "";
                   1589:     var grnsel = "";
                   1590:     var blusel = "";
                   1591:     if (kwclr=="red")   {var redsel="checked"};
                   1592:     if (kwclr=="green") {var grnsel="checked"};
                   1593:     if (kwclr=="blue")  {var blusel="checked"};
                   1594:     var sznsel = "";
                   1595:     var sz1sel = "";
                   1596:     var sz2sel = "";
                   1597:     if (kwsize=="0")  {var sznsel="checked"};
                   1598:     if (kwsize=="+1") {var sz1sel="checked"};
                   1599:     if (kwsize=="+2") {var sz2sel="checked"};
                   1600:     var synsel = "";
                   1601:     var syisel = "";
                   1602:     var sybsel = "";
                   1603:     if (kwstyle=="")    {var synsel="checked"};
                   1604:     if (kwstyle=="<i>") {var syisel="checked"};
                   1605:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1606:     highlightCentral();
                   1607:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1608:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1609:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1610:     highlightend();
                   1611:     return;
                   1612:   }
                   1613: 
                   1614:   function highlightCentral() {
1.76      ng       1615: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1616:     var xpos = (screen.width-400)/2;
                   1617:     xpos = (xpos < 0) ? '0' : xpos;
                   1618:     var ypos = (screen.height-330)/2-30;
                   1619:     ypos = (ypos < 0) ? '0' : ypos;
                   1620: 
1.206     albertel 1621:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1622:     hwdWin.focus();
                   1623:     var hDoc = hwdWin.document;
1.219     www      1624:     hDoc.$docopen;
1.351     albertel 1625:     hDoc.write('$start_page_highlight_central');
1.76      ng       1626:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1627:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1628: 
1.564     bisitz   1629:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1630:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.652     raeburn  1631:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1632:   }
                   1633: 
                   1634:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1635:     var hDoc = hwdWin.document;
                   1636:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1637:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1638:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1639:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1640:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1641:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1642:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1643:     hDoc.write("<\\/tr>");
1.44      ng       1644:   }
                   1645: 
                   1646:   function highlightend() { 
1.76      ng       1647:     var hDoc = hwdWin.document;
1.465     albertel 1648:     hDoc.write("<\\/table>");
                   1649:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1650:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1651:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1652:     hDoc.write("<\\/form>");
1.351     albertel 1653:     hDoc.write('$end_page_highlight_central');
1.128     ng       1654:     hDoc.close();
1.44      ng       1655:   }
                   1656: 
                   1657: SUBJAVASCRIPT
                   1658: }
                   1659: 
1.349     albertel 1660: sub get_increment {
1.348     bowersj2 1661:     my $increment = $env{'form.increment'};
                   1662:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1663:         $increment != .1) {
                   1664:         $increment = 1;
                   1665:     }
                   1666:     return $increment;
                   1667: }
                   1668: 
1.585     bisitz   1669: sub gradeBox_start {
                   1670:     return (
                   1671:         &Apache::loncommon::start_data_table()
                   1672:        .&Apache::loncommon::start_data_table_header_row()
                   1673:        .'<th>'.&mt('Part').'</th>'
                   1674:        .'<th>'.&mt('Points').'</th>'
                   1675:        .'<th>&nbsp;</th>'
                   1676:        .'<th>'.&mt('Assign Grade').'</th>'
                   1677:        .'<th>'.&mt('Weight').'</th>'
                   1678:        .'<th>'.&mt('Grade Status').'</th>'
                   1679:        .&Apache::loncommon::end_data_table_header_row()
                   1680:     );
                   1681: }
                   1682: 
                   1683: sub gradeBox_end {
                   1684:     return (
                   1685:         &Apache::loncommon::end_data_table()
                   1686:     );
                   1687: }
1.71      ng       1688: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1689: sub gradeBox {
1.322     albertel 1690:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1691:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1692: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1693:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1694:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1695:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1696:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1697:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1698: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1699:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1700:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1701:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1702: 				       [$partid]);
                   1703:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1704:     if ($last_resets{$partid}) {
                   1705:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1706:     }
1.585     bisitz   1707:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1708:     my $ctr = 0;
1.348     bowersj2 1709:     my $thisweight = 0;
1.349     albertel 1710:     my $increment = &get_increment();
1.485     albertel 1711: 
                   1712:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1713:     while ($thisweight<=$wgt) {
1.532     bisitz   1714: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1715:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1716: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1717: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1718: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1719:         $thisweight += $increment;
1.71      ng       1720: 	$ctr++;
                   1721:     }
1.485     albertel 1722:     $radio.='</tr></table>';
                   1723: 
                   1724:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1725: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1726: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1727: 	$wgt.')" /></td>'."\n";
1.485     albertel 1728:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1729: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1730: 	' </td>'."\n";
                   1731:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1732: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1733:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1734: 	$line.='<option></option>'.
                   1735: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1736:     } else {
1.485     albertel 1737: 	$line.='<option selected="selected"></option>'.
                   1738: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1739:     }
1.485     albertel 1740:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1741: 
                   1742: 
                   1743:     $result .= 
1.585     bisitz   1744: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1745:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1746:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1747: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1748: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1749: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1750:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1751:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1752:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1753:         $aggtries.'" />'."\n";
1.582     raeburn  1754:     my $res_error;
                   1755:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1756:     if ($res_error) {
                   1757:         return &navmap_errormsg();
                   1758:     }
1.318     banghart 1759:     return $result;
                   1760: }
1.322     albertel 1761: 
                   1762: sub handback_box {
1.623     www      1763:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1764:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1765:     my (@respids);
1.652     raeburn  1766:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1767:     foreach my $part_response_id (@part_response_id) {
                   1768:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1769:         if ($part eq $partid) {
1.375     albertel 1770:             push(@respids,$resp);
1.323     banghart 1771:         }
                   1772:     }
1.318     banghart 1773:     my $result;
1.323     banghart 1774:     foreach my $respid (@respids) {
1.322     albertel 1775: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1776: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1777: 	next if (!@$files);
1.654   ! raeburn  1778: 	my $file_counter = 0;
1.313     banghart 1779: 	foreach my $file (@$files) {
1.368     banghart 1780: 	    if ($file =~ /\/portfolio\//) {
1.654   ! raeburn  1781:                 $file_counter++;
1.368     banghart 1782:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1783:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1784:     	        $file_disp = "$name.$ext";
                   1785:     	        $file = $file_path.$file_disp;
                   1786:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1787:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1788:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654   ! raeburn  1789:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1790: 	    }
1.322     albertel 1791: 	}
1.654   ! raeburn  1792:         if ($file_counter) {
        !          1793:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
        !          1794:                        '<span class="LC_info">'.
        !          1795:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
        !          1796:         }
1.313     banghart 1797:     }
1.318     banghart 1798:     return $result;    
1.71      ng       1799: }
1.44      ng       1800: 
1.58      albertel 1801: sub show_problem {
1.382     albertel 1802:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1803:     my $rendered;
1.382     albertel 1804:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1805:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1806:     if ($mode eq 'both' or $mode eq 'text') {
                   1807: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1808: 						       $env{'request.course.id'},
                   1809: 						       undef,\%form);
1.144     albertel 1810:     }
1.58      albertel 1811:     if ($removeform) {
                   1812: 	$rendered=~s|<form(.*?)>||g;
                   1813: 	$rendered=~s|</form>||g;
1.374     albertel 1814: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1815:     }
1.144     albertel 1816:     my $companswer;
                   1817:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1818: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1819: 	$companswer=
                   1820: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1821: 						    $env{'request.course.id'},
                   1822: 						    %form);
1.144     albertel 1823:     }
1.58      albertel 1824:     if ($removeform) {
                   1825: 	$companswer=~s|<form(.*?)>||g;
                   1826: 	$companswer=~s|</form>||g;
1.144     albertel 1827: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1828:     }
1.468     albertel 1829:     $rendered=
1.588     bisitz   1830:         '<div class="LC_Box">'
                   1831:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1832:        .$rendered
                   1833:        .'</div>';
1.468     albertel 1834:     $companswer=
1.588     bisitz   1835:         '<div class="LC_Box">'
                   1836:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1837:        .$companswer
                   1838:        .'</div>';
1.468     albertel 1839:     my $result;
1.144     albertel 1840:     if ($mode eq 'both') {
1.588     bisitz   1841:         $result=$rendered.$companswer;
1.144     albertel 1842:     } elsif ($mode eq 'text') {
1.588     bisitz   1843:         $result=$rendered;
1.144     albertel 1844:     } elsif ($mode eq 'answer') {
1.588     bisitz   1845:         $result=$companswer;
1.144     albertel 1846:     }
1.71      ng       1847:     return $result;
1.58      albertel 1848: }
1.397     albertel 1849: 
1.396     banghart 1850: sub files_exist {
                   1851:     my ($r, $symb) = @_;
                   1852:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1853: 
1.396     banghart 1854:     foreach my $student (@students) {
                   1855:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1856:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1857: 					      $udom,$uname);
1.396     banghart 1858:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1859:         foreach my $submission (@$string) {
                   1860:             my ($partid,$respid) =
                   1861: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1862:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1863: 					   \%record);
                   1864:             return 1 if (@$files);
1.396     banghart 1865:         }
                   1866:     }
1.397     albertel 1867:     return 0;
1.396     banghart 1868: }
1.397     albertel 1869: 
1.394     banghart 1870: sub download_all_link {
                   1871:     my ($r,$symb) = @_;
1.621     www      1872:     unless (&files_exist($r, $symb)) {
                   1873:        $r->print(&mt('There are currently no submitted documents.'));
                   1874:        return;
                   1875:     }
                   1876: 
1.395     albertel 1877:     my $all_students = 
                   1878: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1879: 
                   1880:     my $parts =
                   1881: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1882: 
1.394     banghart 1883:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1884:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1885:                              'cgi.'.$identifier.'.symb' => $symb,
                   1886:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1887:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1888: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1889:     return;
                   1890: }
                   1891: 
                   1892: sub submit_download_link {
                   1893:     my ($request,$symb) = @_;
                   1894:     if (!$symb) { return ''; }
                   1895: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1896:     &download_all_link($request,$symb);
1.394     banghart 1897: }
1.395     albertel 1898: 
1.432     banghart 1899: sub build_section_inputs {
                   1900:     my $section_inputs;
                   1901:     if ($env{'form.section'} eq '') {
                   1902:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1903:     } else {
                   1904:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1905:         foreach my $section (@sections) {
1.432     banghart 1906:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1907:         }
                   1908:     }
                   1909:     return $section_inputs;
                   1910: }
                   1911: 
1.44      ng       1912: # --------------------------- show submissions of a student, option to grade 
                   1913: sub submission {
1.608     www      1914:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1915:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1916:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1917:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1918:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1919: 
1.605     www      1920:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1921:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1922: 
                   1923:     if (!&canview($usec)) {
1.398     albertel 1924: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1925: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1926: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1927: 	return;
                   1928:     }
                   1929: 
1.257     albertel 1930:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1931:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1932:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1933:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1934:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1935: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1936: 	'/check.gif" height="16" border="0" />';
1.41      ng       1937: 
1.426     albertel 1938:     my %old_essays;
1.41      ng       1939:     # header info
                   1940:     if ($counter == 0) {
                   1941: 	&sub_page_js($request);
1.621     www      1942: 	&sub_page_kw_js($request);
1.118     ng       1943: 
1.44      ng       1944: 	# option to display problem, only once else it cause problems 
                   1945:         # with the form later since the problem has a form.
1.257     albertel 1946: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1947: 	    my $mode;
1.257     albertel 1948: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1949: 		$mode='both';
1.257     albertel 1950: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1951: 		$mode='text';
1.257     albertel 1952: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1953: 		$mode='answer';
                   1954: 	    }
1.329     albertel 1955: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1956: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1957: 	}
1.441     www      1958: 
1.44      ng       1959: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1960:         # if this subroutine has been called once.
1.41      ng       1961: 	my %keyhash = ();
1.624     www      1962: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1963:         if (1) {
1.41      ng       1964: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1965: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1966: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1967: 
1.257     albertel 1968: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1969: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1970: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1971: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1972: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1973: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1974: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1975: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1976: 	}
1.257     albertel 1977: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1978: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1979: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1980: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1981: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1982: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1983: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1984: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1985: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1986: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1987: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1988: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1989: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1990: 			&build_section_inputs().
1.326     albertel 1991: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1992: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1993: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1994: #	if ($env{'form.handgrade'} eq 'yes') {
                   1995:         if (1) {
1.257     albertel 1996: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1997: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1998: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1999: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2000: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2001: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2002: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2003: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2004: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2005: 	    }
1.123     ng       2006: 	}
1.41      ng       2007: 	
                   2008: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2009: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2010: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2011: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2012: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2013: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2014: 		'" />'."\n".
                   2015: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2016: 	    $cts++;
                   2017: 	}
                   2018: 	$request->print($prnmsg);
1.32      ng       2019: 
1.624     www      2020: #	if ($env{'form.handgrade'} eq 'yes') {
                   2021:         if (1) {
1.652     raeburn  2022: 
                   2023:             my %lt = &Apache::lonlocal::texthash(
                   2024:                           keyw => 'Keyword Options',
                   2025:                           past => 'Paste Selection to List',
                   2026:                           high => 'Hightlight Attribute',
                   2027:                      );    
1.88      www      2028: #
                   2029: # Print out the keyword options line
                   2030: #
1.41      ng       2031: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2032: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.417     albertel 2033: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2034: <a href="#" onmousedown="javascript:getSel(); return false"
1.652     raeburn  2035:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2036: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2037: KEYWORDS
1.88      www      2038: #
                   2039: # Load the other essays for similarity check
                   2040: #
1.324     albertel 2041:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2042: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2043: 	    $apath=&escape($apath);
1.88      www      2044: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2045: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2046:         }
                   2047:     }
1.44      ng       2048: 
1.441     www      2049: # This is where output for one specific student would start
1.592     bisitz   2050:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2051:     $request->print(
                   2052:         "\n\n"
                   2053:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2054:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2055:        ."\n"
                   2056:     );
1.441     www      2057: 
1.592     bisitz   2058:     # Show additional functions if allowed
                   2059:     if ($perm{'vgr'}) {
                   2060:         $request->print(
                   2061:             &Apache::loncommon::track_student_link(
                   2062:                 &mt('View recent activity'),
                   2063:                 $uname,$udom,'check')
                   2064:            .' '
                   2065:         );
                   2066:     }
                   2067:     if ($perm{'opa'}) {
                   2068:         $request->print(
                   2069:             &Apache::loncommon::pprmlink(
                   2070:                 &mt('Set/Change parameters'),
                   2071:                 $uname,$udom,$symb,'check'));
                   2072:     }
                   2073: 
                   2074:     # Show Problem
1.257     albertel 2075:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2076: 	my $mode;
1.257     albertel 2077: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2078: 	    $mode='both';
1.257     albertel 2079: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2080: 	    $mode='text';
1.257     albertel 2081: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2082: 	    $mode='answer';
                   2083: 	}
1.329     albertel 2084: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2085: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2086:     }
1.144     albertel 2087: 
1.257     albertel 2088:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2089:     my $res_error;
                   2090:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2091:     if ($res_error) {
                   2092:         $request->print(&navmap_errormsg());
                   2093:         return;
                   2094:     }
1.41      ng       2095: 
1.44      ng       2096:     # Display student info
1.41      ng       2097:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2098: 
                   2099:     my $result='<div class="LC_Box">'
                   2100:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2101:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2102:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2103: #    if ($env{'form.handgrade'} eq 'no') {
                   2104:     if (1) {
1.588     bisitz   2105:         $result.='<p class="LC_info">'
                   2106:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2107:                 ."</p>\n";
1.469     albertel 2108:     }
                   2109: 
1.118     ng       2110:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2111:     my $fullname;
                   2112:     my $col_fullnames = [];
1.624     www      2113: #    if ($env{'form.handgrade'} eq 'yes') {
                   2114:     if (1) {
1.464     albertel 2115: 	(my $sub_result,$fullname,$col_fullnames)=
                   2116: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2117: 				 $counter);
                   2118: 	$result.=$sub_result;
1.41      ng       2119:     }
1.44      ng       2120:     $request->print($result."\n");
1.588     bisitz   2121: 
1.44      ng       2122:     # print student answer/submission
1.588     bisitz   2123:     # Options are (1) Handgraded submission only
1.44      ng       2124:     #             (2) Last submission, includes submission that is not handgraded 
                   2125:     #                  (for multi-response type part)
                   2126:     #             (3) Last submission plus the parts info
                   2127:     #             (4) The whole record for this student
1.257     albertel 2128:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2129: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2130: 	
                   2131: 	my $lastsubonly;
                   2132: 
1.588     bisitz   2133:         if ($$timestamp eq '') {
                   2134:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2135:         } else {
1.592     bisitz   2136:             $lastsubonly =
                   2137:                 '<div class="LC_grade_submissions_body">'
                   2138:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2139: 
1.151     albertel 2140: 	    my %seenparts;
1.375     albertel 2141: 	    my @part_response_id = &flatten_responseType($responseType);
                   2142: 	    foreach my $part (@part_response_id) {
1.393     albertel 2143: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2144: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2145: 
1.375     albertel 2146: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2147: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2148: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2149: 		    if (exists($seenparts{$partid})) { next; }
                   2150: 		    $seenparts{$partid}=1;
1.207     albertel 2151: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2152: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2153: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2154: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2155: 			'\');" target="_self">'.
1.257     albertel 2156: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2157: 		    $request->print($submitby);
                   2158: 		    next;
                   2159: 		}
                   2160: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2161: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2162:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2163:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2164:                         ' <span class="LC_internal_info">'.
1.623     www      2165:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2166:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2167: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2168: 		    next;
                   2169: 		}
1.468     albertel 2170: 		foreach my $submission (@$string) {
                   2171: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2172: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2173: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2174: 		    # Similarity check
                   2175: 		    my $similar='';
1.640     raeburn  2176:                     my ($type,$trial,$rndseed);
                   2177:                     if ($hide eq 'rand') {
                   2178:                         $type = 'randomizetry';
                   2179:                         $trial = $record{"resource.$partid.tries"};
                   2180:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2181:                     }
1.257     albertel 2182: 		    if($env{'form.checkPlag'}){
1.151     albertel 2183: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2184: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2185: 			if ($osim) {
                   2186: 			    $osim=int($osim*100.0);
1.426     albertel 2187: 			    my %old_course_desc = 
                   2188: 				&Apache::lonnet::coursedescription($ocrsid,
                   2189: 								   {'one_time' => 1});
                   2190: 
1.640     raeburn  2191:                             if ($hide eq 'anon') {
1.596     raeburn  2192:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2193:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2194:                             } else {
                   2195: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2196: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2197: 				        $osim,
                   2198: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2199: 				        $old_course_desc{'description'},
                   2200: 				        $old_course_desc{'num'},
                   2201: 				        $old_course_desc{'domain'}).
                   2202: 				    '</span></h3><blockquote><i>'.
                   2203: 				    &keywords_highlight($oessay).
                   2204: 				    '</i></blockquote><hr />';
                   2205:                             }
1.151     albertel 2206: 			}
1.150     albertel 2207: 		    }
1.640     raeburn  2208: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2209:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2210: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2211: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2212: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2213: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2214:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2215:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2216:                             ' <span class="LC_internal_info">'.
1.623     www      2217:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2218:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2219: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2220: 			if (@$files) {
1.640     raeburn  2221:                             if ($hide eq 'anon') {
1.596     raeburn  2222:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2223:                             } else {
                   2224:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2225:                                 foreach my $file (@$files) {
                   2226:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2227:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2228:                                 }
                   2229:                             }
1.236     albertel 2230: 			    $lastsubonly.='<br />';
1.41      ng       2231: 			}
1.640     raeburn  2232:                         if ($hide eq 'anon') {
1.596     raeburn  2233:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2234:                         } else {
                   2235: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2236: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2237: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2238:                         }
1.151     albertel 2239: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2240: 			$lastsubonly.='</div>';
1.41      ng       2241: 		    }
                   2242: 		}
                   2243: 	    }
1.588     bisitz   2244: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2245: 	}
                   2246: 	$request->print($lastsubonly);
1.468     albertel 2247:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2248:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2249: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2250:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2251: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2252: 								 $env{'request.course.id'},
1.44      ng       2253: 								 $last,'.submission',
                   2254: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2255:     }
1.121     ng       2256:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2257: 	.$udom.'" />'."\n");
1.44      ng       2258:     # return if view submission with no grading option
1.618     www      2259:     if (!&canmodify($usec)) {
1.633     www      2260: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2261: 	return;
1.180     albertel 2262:     } else {
1.468     albertel 2263: 	$request->print('</div>'."\n");
1.41      ng       2264:     }
1.33      ng       2265: 
1.121     ng       2266:     # essay grading message center
1.624     www      2267: #    if ($env{'form.handgrade'} eq 'yes') {
                   2268:     if (1) {
1.468     albertel 2269: 	my $result='<div class="LC_grade_message_center">';
                   2270:     
                   2271: 	$result.='<div class="LC_grade_message_center_header">'.
                   2272: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2273: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2274: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2275: 	if (scalar(@$col_fullnames) > 0) {
                   2276: 	    my $lastone = pop(@$col_fullnames);
                   2277: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2278: 	}
                   2279: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2280: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2281: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2282: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2283: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2284: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2285: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2286: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2287: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2288: 	    '<br />&nbsp;('.
1.468     albertel 2289: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2290: 	$result.='</div></div>';
1.121     ng       2291: 	$request->print($result);
1.118     ng       2292:     }
1.41      ng       2293: 
                   2294:     my %seen = ();
                   2295:     my @partlist;
1.129     ng       2296:     my @gradePartRespid;
1.375     albertel 2297:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2298:     $request->print(
1.588     bisitz   2299:         '<div class="LC_Box">'
                   2300:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2301:     );
1.592     bisitz   2302:     $request->print(&gradeBox_start());
1.375     albertel 2303:     foreach my $part_response_id (@part_response_id) {
                   2304:     	my ($partid,$respid) = @{ $part_response_id };
                   2305: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2306: 	next if ($seen{$partid} > 0);
1.41      ng       2307: 	$seen{$partid}++;
1.393     albertel 2308: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2309: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2310: 	push(@partlist,$partid);
                   2311: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2312: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2313:     }
1.585     bisitz   2314:     $request->print(&gradeBox_end()); # </div>
                   2315:     $request->print('</div>');
1.468     albertel 2316: 
                   2317:     $request->print('<div class="LC_grade_info_links">');
                   2318:     $request->print('</div>');
                   2319: 
1.45      ng       2320:     $result='<input type="hidden" name="partlist'.$counter.
                   2321: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2322:     $result.='<input type="hidden" name="gradePartRespid'.
                   2323: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2324:     my $ctr = 0;
                   2325:     while ($ctr < scalar(@partlist)) {
                   2326: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2327: 	    $partlist[$ctr].'" />'."\n";
                   2328: 	$ctr++;
                   2329:     }
1.468     albertel 2330:     $request->print($result.''."\n");
1.41      ng       2331: 
1.441     www      2332: # Done with printing info for one student
                   2333: 
1.468     albertel 2334:     $request->print('</div>');#LC_grade_show_user
1.441     www      2335: 
                   2336: 
1.41      ng       2337:     # print end of form
                   2338:     if ($counter == $total) {
1.592     bisitz   2339:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2340: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2341: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2342: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2343: 	my $ntstu ='<select name="NTSTU">'.
                   2344: 	    '<option>1</option><option>2</option>'.
                   2345: 	    '<option>3</option><option>5</option>'.
                   2346: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2347: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2348: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2349:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2350: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2351: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2352: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2353: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2354:         $endform.='<span class="LC_warning">'.
                   2355:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2356:                   '</span>'."\n" ;
1.349     albertel 2357:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2358:             "' name='increment' />";
1.485     albertel 2359: 	$endform.='</td></tr></table></form>';
1.41      ng       2360: 	$request->print($endform);
                   2361:     }
                   2362:     return '';
1.38      ng       2363: }
                   2364: 
1.464     albertel 2365: sub check_collaborators {
                   2366:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2367:     my ($result,@col_fullnames);
                   2368:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2369:     foreach my $part (keys(%$handgrade)) {
                   2370: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2371: 					'.maxcollaborators',
                   2372: 					$symb,$udom,$uname);
                   2373: 	next if ($ncol <= 0);
                   2374: 	$part =~ s/\_/\./g;
                   2375: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2376: 	my (@good_collaborators, @bad_collaborators);
                   2377: 	foreach my $possible_collaborator
1.630     www      2378: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2379: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2380: 	    next if ($possible_collaborator eq '');
1.631     www      2381: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2382: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2383: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2384: 	    # Doing this grep allows 'fuzzy' specification
                   2385: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2386: 			       keys(%$classlist));
                   2387: 	    if (! scalar(@matches)) {
                   2388: 		push(@bad_collaborators, $possible_collaborator);
                   2389: 	    } else {
                   2390: 		push(@good_collaborators, @matches);
                   2391: 	    }
                   2392: 	}
                   2393: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2394: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2395: 	    foreach my $name (@good_collaborators) {
                   2396: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2397: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2398: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2399: 	    }
1.630     www      2400: 	    $result.='</ol><br />'."\n";
1.466     albertel 2401: 	    my ($part)=split(/\./,$part);
1.464     albertel 2402: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2403: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2404: 		"\n";
                   2405: 	}
                   2406: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2407: 	    $result.='<div class="LC_warning">';
1.464     albertel 2408: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2409: 	    $result .= '</div>';
                   2410: 	}         
                   2411: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2412: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2413: 	    $result .= &mt('This student has submitted too many '.
                   2414: 		'collaborators.  Maximum is [_1].',$ncol);
                   2415: 	    $result .= '</div>';
                   2416: 	}
                   2417:     }
                   2418:     return ($result,$fullname,\@col_fullnames);
                   2419: }
                   2420: 
1.44      ng       2421: #--- Retrieve the last submission for all the parts
1.38      ng       2422: sub get_last_submission {
1.119     ng       2423:     my ($returnhash)=@_;
1.596     raeburn  2424:     my (@string,$timestamp,%lasthidden);
1.119     ng       2425:     if ($$returnhash{'version'}) {
1.46      ng       2426: 	my %lasthash=();
                   2427: 	my ($version);
1.119     ng       2428: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2429: 	    foreach my $key (sort(split(/\:/,
                   2430: 					$$returnhash{$version.':keys'}))) {
                   2431: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2432: 		$timestamp = 
1.545     raeburn  2433: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2434: 	    }
                   2435: 	}
1.640     raeburn  2436:         my (%typeparts,%randombytry);
1.596     raeburn  2437:         my $showsurv = 
                   2438:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2439:         foreach my $key (sort(keys(%lasthash))) {
                   2440:             if ($key =~ /\.type$/) {
                   2441:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2442:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2443:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2444:                     my ($ign,@parts) = split(/\./,$key);
                   2445:                     pop(@parts);
1.641     raeburn  2446:                     my $id = join('.',@parts);
1.640     raeburn  2447:                     if ($lasthash{$key} eq 'randomizetry') {
                   2448:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2449:                     } else {
                   2450:                         unless ($showsurv) {
                   2451:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2452:                         }
1.596     raeburn  2453:                     }
                   2454:                     delete($lasthash{$key});
                   2455:                 }
                   2456:             }
                   2457:         }
                   2458:         my @hidden = keys(%typeparts);
1.640     raeburn  2459:         my @randomize = keys(%randombytry);
1.397     albertel 2460: 	foreach my $key (keys(%lasthash)) {
                   2461: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2462:             my $hide;
                   2463:             if (@hidden) {
                   2464:                 foreach my $id (@hidden) {
                   2465:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2466:                         $hide = 'anon';
1.596     raeburn  2467:                         last;
                   2468:                     }
                   2469:                 }
                   2470:             }
1.640     raeburn  2471:             unless ($hide) {
                   2472:                 if (@randomize) {
                   2473:                     foreach my $id (@hidden) {
                   2474:                         if ($key =~ /^\Q$id\E/) {
                   2475:                             $hide = 'rand';
                   2476:                             last;
                   2477:                         }
                   2478:                     }
                   2479:                 }
                   2480:             }
1.397     albertel 2481: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2482: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2483: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2484: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2485: 	}
                   2486:     }
1.397     albertel 2487:     if (!@string) {
                   2488: 	$string[0] =
1.539     riegler  2489: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2490:     }
                   2491:     return (\@string,\$timestamp);
1.38      ng       2492: }
1.35      ng       2493: 
1.44      ng       2494: #--- High light keywords, with style choosen by user.
1.38      ng       2495: sub keywords_highlight {
1.44      ng       2496:     my $string    = shift;
1.257     albertel 2497:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2498:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2499:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2500:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2501:     foreach my $keyword (@keylist) {
                   2502: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2503:     }
                   2504:     return $string;
1.38      ng       2505: }
1.36      ng       2506: 
1.44      ng       2507: #--- Called from submission routine
1.38      ng       2508: sub processHandGrade {
1.608     www      2509:     my ($request,$symb) = @_;
1.324     albertel 2510:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2511:     my $button = $env{'form.gradeOpt'};
                   2512:     my $ngrade = $env{'form.NCT'};
                   2513:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2514:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2515:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2516: 
1.44      ng       2517:     if ($button eq 'Save & Next') {
                   2518: 	my $ctr = 0;
                   2519: 	while ($ctr < $ngrade) {
1.257     albertel 2520: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2521: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2522: 	    if ($errorflag eq 'no_score') {
                   2523: 		$ctr++;
                   2524: 		next;
                   2525: 	    }
1.104     albertel 2526: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2527: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2528: 		$ctr++;
                   2529: 		next;
                   2530: 	    }
1.257     albertel 2531: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2532: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2533: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2534:             my ($feedurl,$showsymb) =
                   2535: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2536: 	    my $messagetail;
1.62      albertel 2537: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2538: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2539: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2540: 		$subject.=' ['.$restitle.']';
1.44      ng       2541: 		my (@msgnum) = split(/,/,$includemsg);
                   2542: 		foreach (@msgnum) {
1.257     albertel 2543: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2544: 		}
1.80      ng       2545: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2546: 		if ($env{'form.withgrades'.$ctr}) {
                   2547: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2548: 		    $messagetail = " for <a href=\"".
1.605     www      2549: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2550: 		}
                   2551: 		$msgstatus = 
                   2552:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2553: 						     $message.$messagetail,
1.418     albertel 2554:                                                      undef,$feedurl,undef,
1.386     raeburn  2555:                                                      undef,undef,$showsymb,
                   2556:                                                      $restitle);
1.574     bisitz   2557: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2558: 				$msgstatus.'<br />');
1.44      ng       2559: 	    }
1.257     albertel 2560: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2561: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2562: 		foreach my $collabstr (@collabstrs) {
                   2563: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2564: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2565: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2566: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2567: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2568: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2569: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2570: 			    next;
1.418     albertel 2571: 			} elsif ($message ne '') {
                   2572: 			    my ($baseurl,$showsymb) = 
                   2573: 				&get_feedurl_and_symb($symb,$collaborator,
                   2574: 						      $udom);
                   2575: 			    if ($env{'form.withgrades'.$ctr}) {
                   2576: 				$messagetail = " for <a href=\"".
1.605     www      2577:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2578: 			    }
1.418     albertel 2579: 			    $msgstatus = 
                   2580: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2581: 			}
1.44      ng       2582: 		    }
                   2583: 		}
                   2584: 	    }
                   2585: 	    $ctr++;
                   2586: 	}
                   2587:     }
                   2588: 
1.624     www      2589: #    if ($env{'form.handgrade'} eq 'yes') {
                   2590:     if (1) {
1.119     ng       2591: 	# Keywords sorted in alphabatical order
1.257     albertel 2592: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2593: 	my %keyhash = ();
1.257     albertel 2594: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2595: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2596: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2597: 	$env{'form.keywords'} = join(' ',@keywords);
                   2598: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2599: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2600: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2601: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2602: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2603: 
                   2604: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2605: 	# New messages are saved in env for the next student.
1.119     ng       2606: 	# All messages are saved in nohist_handgrade.db
                   2607: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2608: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2609: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2610: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2611: 		$idx++;
                   2612: 	    }
                   2613: 	    $ctr++;
1.41      ng       2614: 	}
1.119     ng       2615: 	$ctr = 0;
                   2616: 	while ($ctr < $ngrade) {
1.257     albertel 2617: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2618: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2619: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2620: 		$idx++;
                   2621: 	    }
                   2622: 	    $ctr++;
1.41      ng       2623: 	}
1.257     albertel 2624: 	$env{'form.savemsgN'} = --$idx;
                   2625: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2626: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2627: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2628:     }
1.44      ng       2629:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2630:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2631:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2632: 	my ($ctr,$total) = (0,0);
                   2633: 	while ($ctr < $ngrade) {
1.257     albertel 2634: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2635: 	    $ctr++;
                   2636: 	}
1.257     albertel 2637: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2638: 	$ctr = 0;
                   2639: 	while ($ctr < $total) {
1.257     albertel 2640: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2641: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2642: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2643: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2644: 	    $ctr++;
                   2645: 	}
                   2646: 	return '';
                   2647:     }
1.36      ng       2648: 
1.44      ng       2649:     # Get the next/previous one or group of students
1.257     albertel 2650:     my $firststu = $env{'form.unamedom0'};
                   2651:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2652:     my $ctr = 2;
1.41      ng       2653:     while ($laststu eq '') {
1.257     albertel 2654: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2655: 	$ctr++;
                   2656: 	$laststu = $firststu if ($ctr > $ngrade);
                   2657:     }
1.44      ng       2658: 
1.41      ng       2659:     my (@parsedlist,@nextlist);
                   2660:     my ($nextflg) = 0;
1.524     raeburn  2661:     foreach my $item (sort 
1.294     albertel 2662: 	     {
                   2663: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2664: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2665: 		 }
                   2666: 		 return $a cmp $b;
                   2667: 	     } (keys(%$fullname))) {
1.605     www      2668: # FIXME: this is fishy, looks like the button label
1.41      ng       2669: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2670: 	    push(@parsedlist,$item);
1.41      ng       2671: 	}
1.524     raeburn  2672: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2673: 	if ($button eq 'Previous') {
1.524     raeburn  2674: 	    last if ($item eq $firststu);
                   2675: 	    push(@parsedlist,$item);
1.41      ng       2676: 	}
                   2677:     }
                   2678:     $ctr = 0;
1.605     www      2679: # FIXME: this is fishy, looks like the button label
1.41      ng       2680:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2681:     my $res_error;
                   2682:     my ($partlist) = &response_type($symb,\$res_error);
                   2683:     if ($res_error) {
                   2684:         $request->print(&navmap_errormsg());
                   2685:         return;
                   2686:     }
1.41      ng       2687:     foreach my $student (@parsedlist) {
1.257     albertel 2688: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2689: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2690: 	
                   2691: 	if ($submitonly eq 'queued') {
                   2692: 	    my %queue_status = 
                   2693: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2694: 							$udom,$uname);
                   2695: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2696: 	}
                   2697: 
1.156     albertel 2698: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2699: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2700: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2701: 	    my $submitted = 0;
1.248     albertel 2702: 	    my $ungraded = 0;
                   2703: 	    my $incorrect = 0;
1.524     raeburn  2704: 	    foreach my $item (keys(%status)) {
                   2705: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2706: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2707: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2708: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2709: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2710: 		    $submitted = 0;
                   2711: 		}
1.41      ng       2712: 	    }
1.156     albertel 2713: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2714: 				     $submitonly eq 'incorrect' ||
                   2715: 				     $submitonly eq 'graded'));
1.248     albertel 2716: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2717: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2718: 	}
1.524     raeburn  2719: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2720: 	last if ($ctr == $ntstu);
1.41      ng       2721: 	$ctr++;
                   2722:     }
1.36      ng       2723: 
1.41      ng       2724:     $ctr = 0;
                   2725:     my $total = scalar(@nextlist)-1;
1.39      ng       2726: 
1.524     raeburn  2727:     foreach (sort(@nextlist)) {
1.41      ng       2728: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2729: 	$env{'form.student'}  = $uname;
                   2730: 	$env{'form.userdom'}  = $udom;
                   2731: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2732: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2733: 	$ctr++;
                   2734:     }
                   2735:     if ($total < 0) {
1.653     raeburn  2736: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2737: 	$request->print($the_end);
                   2738:     }
                   2739:     return '';
1.38      ng       2740: }
1.36      ng       2741: 
1.44      ng       2742: #---- Save the score and award for each student, if changed
1.38      ng       2743: sub saveHandGrade {
1.324     albertel 2744:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2745:     my @version_parts;
1.104     albertel 2746:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2747: 					   $env{'request.course.id'});
1.104     albertel 2748:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2749:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2750:     my @parts_graded;
1.77      ng       2751:     my %newrecord  = ();
                   2752:     my ($pts,$wgt) = ('','');
1.269     raeburn  2753:     my %aggregate = ();
                   2754:     my $aggregateflag = 0;
1.301     albertel 2755:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2756:     foreach my $new_part (@parts) {
1.337     banghart 2757: 	#collaborator ($submi may vary for different parts
1.259     banghart 2758: 	if ($submitter && $new_part ne $part) { next; }
                   2759: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2760: 	if ($dropMenu eq 'excused') {
1.259     banghart 2761: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2762: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2763: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2764: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2765: 		}
1.364     banghart 2766: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2767: 	    }
1.125     ng       2768: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2769: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2770: 	    foreach my $key (keys(%record)) {
1.259     banghart 2771: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2772: 	    }
1.259     banghart 2773: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2774: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2775:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2776: 
                   2777:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2778: 					       [$new_part]);
                   2779:             my $aggtries =$totaltries;
1.269     raeburn  2780:             if ($last_resets{$new_part}) {
1.270     albertel 2781:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2782: 					   $new_part);
1.269     raeburn  2783:             }
1.270     albertel 2784: 
                   2785:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2786:             if ($aggtries > 0) {
1.327     albertel 2787:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2788:                 $aggregateflag = 1;
                   2789:             }
1.125     ng       2790: 	} elsif ($dropMenu eq '') {
1.259     banghart 2791: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2792: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2793: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2794: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2795: 		next;
                   2796: 	    }
1.259     banghart 2797: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2798: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2799: 	    my $partial= $pts/$wgt;
1.259     banghart 2800: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2801: 		#do not update score for part if not changed.
1.346     banghart 2802:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2803: 		next;
1.251     banghart 2804: 	    } else {
1.524     raeburn  2805: 	        push(@parts_graded,$new_part);
1.153     albertel 2806: 	    }
1.259     banghart 2807: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2808: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2809: 	    }
1.259     banghart 2810: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2811: 	    if ($partial == 0) {
1.153     albertel 2812: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2813: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2814: 		}
1.41      ng       2815: 	    } else {
1.153     albertel 2816: 		if ($record{$reckey} ne 'correct_by_override') {
                   2817: 		    $newrecord{$reckey} = 'correct_by_override';
                   2818: 		}
                   2819: 	    }	    
                   2820: 	    if ($submitter && 
1.259     banghart 2821: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2822: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2823: 	    }
1.259     banghart 2824: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2825: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2826: 	}
1.259     banghart 2827: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2828: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2829: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2830: 	        $dropMenu eq 'reset status')
                   2831: 	   {
1.524     raeburn  2832: 	    push(@version_parts,$new_part);
1.259     banghart 2833: 	}
1.41      ng       2834:     }
1.301     albertel 2835:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2836:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2837: 
1.344     albertel 2838:     if (%newrecord) {
                   2839:         if (@version_parts) {
1.364     banghart 2840:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2841:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2842: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2843: 	    foreach my $new_part (@version_parts) {
                   2844: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2845: 				$new_part,\%newrecord);
                   2846: 	    }
1.259     banghart 2847:         }
1.44      ng       2848: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2849: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2850: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2851: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2852:     }
1.269     raeburn  2853:     if ($aggregateflag) {
                   2854:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2855: 			      $cdom,$cnum);
1.269     raeburn  2856:     }
1.301     albertel 2857:     return ('',$pts,$wgt);
1.36      ng       2858: }
1.322     albertel 2859: 
1.380     albertel 2860: sub check_and_remove_from_queue {
                   2861:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2862:     my @ungraded_parts;
                   2863:     foreach my $part (@{$parts}) {
                   2864: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2865: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2866: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2867: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2868: 		) {
                   2869: 	    push(@ungraded_parts, $part);
                   2870: 	}
                   2871:     }
                   2872:     if ( !@ungraded_parts ) {
                   2873: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2874: 					       $cnum,$domain,$stuname);
                   2875:     }
                   2876: }
                   2877: 
1.337     banghart 2878: sub handback_files {
                   2879:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2880:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2881:     my $res_error;
                   2882:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2883:     if ($res_error) {
                   2884:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2885:         return;
                   2886:     }
1.654   ! raeburn  2887:     my @handedback;
        !          2888:     my $file_msg;
1.375     albertel 2889:     my @part_response_id = &flatten_responseType($responseType);
                   2890:     foreach my $part_response_id (@part_response_id) {
                   2891:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2892: 	my $part_resp = join('_',@{ $part_response_id });
1.654   ! raeburn  2893:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
        !          2894:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
        !          2895:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
        !          2896:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
        !          2897:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 2898:                     my ($directory,$answer_file) = 
1.654   ! raeburn  2899:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 2900:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2901: 		        &file_name_version_ext($answer_file);
1.355     banghart 2902: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2903:                     my $getpropath = 1;
                   2904: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2905: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2906:                     # fix file name
                   2907:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2908:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654   ! raeburn  2909:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 2910:             	                                $save_file_name);
1.337     banghart 2911:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2912:                         $request->print('<br /><span class="LC_error">'.
                   2913:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654   ! raeburn  2914:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  2915:                                         '</span>');
1.356     banghart 2916:                     } else {
1.360     banghart 2917:                         # mark the file as read only
1.654   ! raeburn  2918:                         push(@handedback,$save_file_name);
1.367     albertel 2919: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2920: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2921: 			}
                   2922:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654   ! raeburn  2923: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 2924:                     }
1.654   ! raeburn  2925:                     $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 2926:                 }
                   2927:             }
                   2928:         }
1.654   ! raeburn  2929:     }
        !          2930:     if (@handedback > 0) {
        !          2931:         $request->print('<br />');
        !          2932:         my @what = ($symb,$env{'request.course.id'},'handback');
        !          2933:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
        !          2934:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
        !          2935:         my ($subject,$message);
        !          2936:         if (scalar(@handedback) == 1) {
        !          2937:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
        !          2938:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
        !          2939:         } else {
        !          2940:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
        !          2941:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
        !          2942:         }
        !          2943:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
        !          2944:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
        !          2945:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
        !          2946:         my ($feedurl,$showsymb) =
        !          2947:             &get_feedurl_and_symb($symb,$domain,$stuname);
        !          2948:         my $restitle = &Apache::lonnet::gettitle($symb);
        !          2949:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
        !          2950:         my $msgstatus =
        !          2951:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
        !          2952:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
        !          2953:                  $restitle);
        !          2954:         if ($msgstatus) {
        !          2955:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
        !          2956:         }
        !          2957:     }
1.338     banghart 2958:     return;
1.337     banghart 2959: }
                   2960: 
1.418     albertel 2961: sub get_feedurl_and_symb {
                   2962:     my ($symb,$uname,$udom) = @_;
                   2963:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2964:     $url = &Apache::lonnet::clutter($url);
                   2965:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2966: 					$symb,$udom,$uname);
                   2967:     if ($encrypturl =~ /^yes$/i) {
                   2968: 	&Apache::lonenc::encrypted(\$url,1);
                   2969: 	&Apache::lonenc::encrypted(\$symb,1);
                   2970:     }
                   2971:     return ($url,$symb);
                   2972: }
                   2973: 
1.313     banghart 2974: sub get_submitted_files {
                   2975:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2976:     my @files;
                   2977:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2978:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2979:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2980:     	    push(@files,$file_url.$file);
                   2981:         }
                   2982:     }
                   2983:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2984:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2985:     }
                   2986:     return (\@files);
                   2987: }
1.322     albertel 2988: 
1.269     raeburn  2989: # ----------- Provides number of tries since last reset.
                   2990: sub get_num_tries {
                   2991:     my ($record,$last_reset,$part) = @_;
                   2992:     my $timestamp = '';
                   2993:     my $num_tries = 0;
                   2994:     if ($$record{'version'}) {
                   2995:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2996:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2997:                 $timestamp = $$record{$version.':timestamp'};
                   2998:                 if ($timestamp > $last_reset) {
                   2999:                     $num_tries ++;
                   3000:                 } else {
                   3001:                     last;
                   3002:                 }
                   3003:             }
                   3004:         }
                   3005:     }
                   3006:     return $num_tries;
                   3007: }
                   3008: 
                   3009: # ----------- Determine decrements required in aggregate totals 
                   3010: sub decrement_aggs {
                   3011:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3012:     my %decrement = (
                   3013:                         attempts => 0,
                   3014:                         users => 0,
                   3015:                         correct => 0
                   3016:                     );
                   3017:     $decrement{'attempts'} = $aggtries;
                   3018:     if ($solvedstatus =~ /^correct/) {
                   3019:         $decrement{'correct'} = 1;
                   3020:     }
                   3021:     if ($aggtries == $totaltries) {
                   3022:         $decrement{'users'} = 1;
                   3023:     }
1.524     raeburn  3024:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3025:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3026:     }
                   3027:     return;
                   3028: }
                   3029: 
                   3030: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3031: sub get_last_resets {
1.270     albertel 3032:     my ($symb,$courseid,$partids) =@_;
                   3033:     my %last_resets;
1.269     raeburn  3034:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3035:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3036:     my @keys;
                   3037:     foreach my $part (@{$partids}) {
                   3038: 	push(@keys,"$symb\0$part\0resettime");
                   3039:     }
                   3040:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3041: 				     $cdom,$cname);
                   3042:     foreach my $part (@{$partids}) {
                   3043: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3044:     }
1.270     albertel 3045:     return %last_resets;
1.269     raeburn  3046: }
                   3047: 
1.251     banghart 3048: # ----------- Handles creating versions for portfolio files as answers
                   3049: sub version_portfiles {
1.343     banghart 3050:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3051:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3052:     my @returned_keys;
1.255     banghart 3053:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3054:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3055:     foreach my $key (keys(%$record)) {
1.259     banghart 3056:         my $new_portfiles;
1.263     banghart 3057:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3058:             my @versioned_portfiles;
1.367     albertel 3059:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3060:             foreach my $file (@portfiles) {
1.306     banghart 3061:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3062:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3063: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3064: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3065:                 my $getpropath = 1;    
                   3066:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3067:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3068:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3069:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3070:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3071:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3072:                         [$directory.$new_answer],
1.306     banghart 3073:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3074:                 }
1.252     banghart 3075:             }
1.343     banghart 3076:             $$record{$key} = join(',',@versioned_portfiles);
                   3077:             push(@returned_keys,$key);
1.251     banghart 3078:         }
                   3079:     } 
1.343     banghart 3080:     return (@returned_keys);   
1.305     banghart 3081: }
                   3082: 
1.307     banghart 3083: sub get_next_version {
1.341     banghart 3084:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3085:     my $version;
                   3086:     foreach my $row (@$dir_list) {
                   3087:         my ($file) = split(/\&/,$row,2);
                   3088:         my ($file_name,$file_version,$file_ext) =
                   3089: 	    &file_name_version_ext($file);
                   3090:         if (($file_name eq $answer_name) && 
                   3091: 	    ($file_ext eq $answer_ext)) {
                   3092:                 # gets here if filename and extension match, regardless of version
                   3093:                 if ($file_version ne '') {
                   3094:                 # a versioned file is found  so save it for later
                   3095:                 if ($file_version > $version) {
                   3096: 		    $version = $file_version;
                   3097: 	        }
                   3098:             }
                   3099:         }
                   3100:     } 
                   3101:     $version ++;
                   3102:     return($version);
                   3103: }
                   3104: 
1.305     banghart 3105: sub version_selected_portfile {
1.306     banghart 3106:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3107:     my ($answer_name,$answer_ver,$answer_ext) =
                   3108:         &file_name_version_ext($file_name);
                   3109:     my $new_answer;
                   3110:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3111:     if($env{'form.copy'} eq '-1') {
                   3112:         $new_answer = 'problem getting file';
                   3113:     } else {
                   3114:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3115:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3116:                             $stu_name,$domain,'copy',
                   3117: 		        '/portfolio'.$directory.$new_answer);
                   3118:     }    
                   3119:     return ($new_answer);
1.251     banghart 3120: }
                   3121: 
1.304     albertel 3122: sub file_name_version_ext {
                   3123:     my ($file)=@_;
                   3124:     my @file_parts = split(/\./, $file);
                   3125:     my ($name,$version,$ext);
                   3126:     if (@file_parts > 1) {
                   3127: 	$ext=pop(@file_parts);
                   3128: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3129: 	    $version=pop(@file_parts);
                   3130: 	}
                   3131: 	$name=join('.',@file_parts);
                   3132:     } else {
                   3133: 	$name=join('.',@file_parts);
                   3134:     }
                   3135:     return($name,$version,$ext);
                   3136: }
                   3137: 
1.44      ng       3138: #--------------------------------------------------------------------------------------
                   3139: #
                   3140: #-------------------------- Next few routines handles grading by section or whole class
                   3141: #
                   3142: #--- Javascript to handle grading by section or whole class
1.42      ng       3143: sub viewgrades_js {
                   3144:     my ($request) = shift;
                   3145: 
1.539     riegler  3146:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3147:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3148:    function writePoint(partid,weight,point) {
1.125     ng       3149: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3150: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3151: 	if (point == "textval") {
1.125     ng       3152: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3153: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3154: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3155: 		var resetbox = false;
                   3156: 		for (var i=0; i<radioButton.length; i++) {
                   3157: 		    if (radioButton[i].checked) {
                   3158: 			textbox.value = i;
                   3159: 			resetbox = true;
                   3160: 		    }
                   3161: 		}
                   3162: 		if (!resetbox) {
                   3163: 		    textbox.value = "";
                   3164: 		}
                   3165: 		return;
                   3166: 	    }
1.109     matthew  3167: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3168: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3169: 				   ") greater than the weight for the part. Accept?");
                   3170: 		if (resp == false) {
                   3171: 		    textbox.value = "";
                   3172: 		    return;
                   3173: 		}
                   3174: 	    }
1.42      ng       3175: 	    for (var i=0; i<radioButton.length; i++) {
                   3176: 		radioButton[i].checked=false;
1.109     matthew  3177: 		if (parseFloat(point) == i) {
1.42      ng       3178: 		    radioButton[i].checked=true;
                   3179: 		}
                   3180: 	    }
1.41      ng       3181: 
1.42      ng       3182: 	} else {
1.125     ng       3183: 	    textbox.value = parseFloat(point);
1.42      ng       3184: 	}
1.41      ng       3185: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3186: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3187: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3188: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3189: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3190: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3191: 	    if (saveval != "correct") {
                   3192: 		scorename.value = point;
1.43      ng       3193: 		if (selname[0].selected != true) {
                   3194: 		    selname[0].selected = true;
                   3195: 		}
1.42      ng       3196: 	    }
                   3197: 	}
1.125     ng       3198: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3199:     }
                   3200: 
                   3201:     function writeRadText(partid,weight) {
1.125     ng       3202: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3203: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3204:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3205: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3206: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3207: 	    for (var i=0; i<radioButton.length; i++) {
                   3208: 		radioButton[i].checked=false;
                   3209: 
                   3210: 	    }
                   3211: 	    textbox.value = "";
                   3212: 
                   3213: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3214: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3215: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3216: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3217: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3218: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3219: 		if ((saveval != "correct") || override) {
1.42      ng       3220: 		    scorename.value = "";
1.125     ng       3221: 		    if (selval[1].selected) {
                   3222: 			selname[1].selected = true;
                   3223: 		    } else {
                   3224: 			selname[2].selected = true;
                   3225: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3226: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3227: 		    }
1.42      ng       3228: 		}
                   3229: 	    }
1.43      ng       3230: 	} else {
                   3231: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3232: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3233: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3234: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3235: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3236: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3237: 		if ((saveval != "correct") || override) {
1.125     ng       3238: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3239: 		    selname[0].selected = true;
                   3240: 		}
                   3241: 	    }
                   3242: 	}	    
1.42      ng       3243:     }
                   3244: 
                   3245:     function changeSelect(partid,user) {
1.125     ng       3246: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3247: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3248: 	var point  = textbox.value;
1.125     ng       3249: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3250: 
1.109     matthew  3251: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3252: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3253: 	    textbox.value = "";
                   3254: 	    return;
                   3255: 	}
1.109     matthew  3256: 	if (parseFloat(point) > parseFloat(weight)) {
                   3257: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3258: 			       ") greater than the weight of the part. Accept?");
                   3259: 	    if (resp == false) {
                   3260: 		textbox.value = "";
                   3261: 		return;
                   3262: 	    }
                   3263: 	}
1.42      ng       3264: 	selval[0].selected = true;
                   3265:     }
                   3266: 
                   3267:     function changeOneScore(partid,user) {
1.125     ng       3268: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3269: 	if (selval[1].selected || selval[2].selected) {
                   3270: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3271: 	    if (selval[2].selected) {
                   3272: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3273: 	    }
1.269     raeburn  3274:         }
1.42      ng       3275:     }
                   3276: 
                   3277:     function resetEntry(numpart) {
                   3278: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3279: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3280: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3281: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3282: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3283: 	    for (var i=0; i<radioButton.length; i++) {
                   3284: 		radioButton[i].checked=false;
                   3285: 
                   3286: 	    }
                   3287: 	    textbox.value = "";
                   3288: 	    selval[0].selected = true;
                   3289: 
                   3290: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3291: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3292: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3293: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3294: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3295: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3296: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3297: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3298: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3299: 		if (saveselval == "excused") {
1.43      ng       3300: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3301: 		} else {
1.43      ng       3302: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3303: 		}
                   3304: 	    }
1.41      ng       3305: 	}
1.42      ng       3306:     }
                   3307: 
1.41      ng       3308: VIEWJAVASCRIPT
1.42      ng       3309: }
                   3310: 
1.44      ng       3311: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3312: sub viewgrades {
1.608     www      3313:     my ($request,$symb) = @_;
1.42      ng       3314:     &viewgrades_js($request);
1.41      ng       3315: 
1.168     albertel 3316:     #need to make sure we have the correct data for later EXT calls, 
                   3317:     #thus invalidate the cache
                   3318:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3319:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3320:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3321:     &Apache::lonnet::clear_EXT_cache_status();
                   3322: 
1.398     albertel 3323:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3324: 
                   3325:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3326:     $result.=&jscriptNform($symb);
1.41      ng       3327: 
1.44      ng       3328:     #beginning of class grading form
1.442     banghart 3329:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3330:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3331: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3332: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3333: 	&build_section_inputs().
1.442     banghart 3334: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3335: 
1.560     raeburn  3336:     my ($common_header,$specific_header);
1.257     albertel 3337:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3338: 	$common_header = &mt('Assign Common Grade to Class');
                   3339:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3340:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3341:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3342: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3343:     } else {
1.560     raeburn  3344:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3345:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3346: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3347:     }
1.560     raeburn  3348:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3349:     #radio buttons/text box for assigning points for a section or class.
                   3350:     #handles different parts of a problem
1.582     raeburn  3351:     my $res_error;
                   3352:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3353:     if ($res_error) {
                   3354:         return &navmap_errormsg();
                   3355:     }
1.42      ng       3356:     my %weight = ();
                   3357:     my $ctsparts = 0;
1.45      ng       3358:     my %seen = ();
1.375     albertel 3359:     my @part_response_id = &flatten_responseType($responseType);
                   3360:     foreach my $part_response_id (@part_response_id) {
                   3361:     	my ($partid,$respid) = @{ $part_response_id };
                   3362: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3363: 	next if $seen{$partid};
                   3364: 	$seen{$partid}++;
1.375     albertel 3365: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3366: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3367: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3368: 
1.324     albertel 3369: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3370: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3371: 	my $ctr = 0;
1.42      ng       3372: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3373: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3374: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3375: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3376: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3377: 	    $ctr++;
                   3378: 	}
1.485     albertel 3379: 	$radio.='</tr></table>';
                   3380: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3381: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3382: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3383: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3384: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3385: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3386: 		$weight{$partid}.')"> '.
1.401     albertel 3387: 	    '<option selected="selected"> </option>'.
1.485     albertel 3388: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3389: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3390: 	    '</select></td>'.
                   3391:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3392: 	$line.='<input type="hidden" name="partid_'.
                   3393: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3394: 	$line.='<input type="hidden" name="weight_'.
                   3395: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3396: 
                   3397: 	$result.=
                   3398: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3399: 	    '<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 3400: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3401: 	$ctsparts++;
1.41      ng       3402:     }
1.474     albertel 3403:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3404: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3405:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3406: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3407: 
1.44      ng       3408:     #table listing all the students in a section/class
                   3409:     #header of table
1.560     raeburn  3410:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3411:               &Apache::loncommon::start_data_table().
                   3412: 	      &Apache::loncommon::start_data_table_header_row().
                   3413: 	      '<th>'.&mt('No.').'</th>'.
                   3414: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3415:     my $partserror;
                   3416:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3417:     if ($partserror) {
                   3418:         return &navmap_errormsg();
                   3419:     }
1.324     albertel 3420:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3421:     my @partids = ();
1.41      ng       3422:     foreach my $part (@parts) {
                   3423: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3424:         my $narrowtext = &mt('Tries');
                   3425: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3426: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3427: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3428:         push(@partids,$partid);
1.628     www      3429: #
                   3430: # FIXME: Looks like $display looks at English text
                   3431: #
1.324     albertel 3432: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3433: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3434: 	    $result.='<th>'.
                   3435: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3436: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3437: 	    next;
1.485     albertel 3438: 	    
1.207     albertel 3439: 	} else {
1.485     albertel 3440: 	    if ($display =~ /Problem Status/) {
                   3441: 		my $grade_status_mt = &mt('Grade Status');
                   3442: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3443: 	    }
                   3444: 	    my $part_mt = &mt('Part:');
                   3445: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3446: 	}
1.485     albertel 3447: 
1.474     albertel 3448: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3449:     }
1.474     albertel 3450:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3451: 
1.270     albertel 3452:     my %last_resets = 
                   3453: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3454: 
1.41      ng       3455:     #get info for each student
1.44      ng       3456:     #list all the students - with points and grade status
1.257     albertel 3457:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3458:     my $ctr = 0;
1.294     albertel 3459:     foreach (sort 
                   3460: 	     {
                   3461: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3462: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3463: 		 }
                   3464: 		 return $a cmp $b;
                   3465: 	     } (keys(%$fullname))) {
1.126     ng       3466: 	$ctr++;
1.324     albertel 3467: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3468: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3469:     }
1.474     albertel 3470:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3471:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3472:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3473: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3474:     if (scalar(%$fullname) eq 0) {
                   3475: 	my $colspan=3+scalar(@parts);
1.433     banghart 3476: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3477:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3478: 	$result='<span class="LC_warning">'.
1.485     albertel 3479: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3480: 	        $section_display, $stu_status).
1.433     banghart 3481: 	    '</span>';
1.96      albertel 3482:     }
1.41      ng       3483:     return $result;
                   3484: }
                   3485: 
1.44      ng       3486: #--- call by previous routine to display each student
1.41      ng       3487: sub viewstudentgrade {
1.324     albertel 3488:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3489:     my ($uname,$udom) = split(/:/,$student);
                   3490:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3491:     my %aggregates = (); 
1.474     albertel 3492:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3493: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3494: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3495: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3496: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3497: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3498:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3499:     foreach my $apart (@$parts) {
                   3500: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3501: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3502:         $result.='<td align="center">';
1.269     raeburn  3503:         my ($aggtries,$totaltries);
                   3504:         unless (exists($aggregates{$part})) {
1.270     albertel 3505: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3506: 
                   3507: 	    $aggtries = $totaltries;
1.269     raeburn  3508:             if ($$last_resets{$part}) {  
1.270     albertel 3509:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3510: 					   $part);
                   3511:             }
1.269     raeburn  3512:             $result.='<input type="hidden" name="'.
                   3513:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3514:             $result.='<input type="hidden" name="'.
                   3515:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3516:             $aggregates{$part} = 1;
                   3517:         }
1.41      ng       3518: 	if ($type eq 'awarded') {
1.320     albertel 3519: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3520: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3521: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3522: 	    $result.='<input type="text" name="'.
1.89      albertel 3523: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3524:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3525: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3526: 	} elsif ($type eq 'solved') {
                   3527: 	    my ($status,$foo)=split(/_/,$score,2);
                   3528: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3529: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3530: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3531: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3532: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3533:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3534: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3535: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3536: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3537: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3538: 	} else {
                   3539: 	    $result.='<input type="hidden" name="'.
                   3540: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3541: 		    "\n";
1.233     albertel 3542: 	    $result.='<input type="text" name="'.
1.122     ng       3543: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3544: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3545: 	}
                   3546:     }
1.474     albertel 3547:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3548:     return $result;
1.38      ng       3549: }
                   3550: 
1.44      ng       3551: #--- change scores for all the students in a section/class
                   3552: #    record does not get update if unchanged
1.38      ng       3553: sub editgrades {
1.608     www      3554:     my ($request,$symb) = @_;
1.41      ng       3555: 
1.433     banghart 3556:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3557:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3558:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3559: 
1.477     albertel 3560:     my $result= &Apache::loncommon::start_data_table().
                   3561: 	&Apache::loncommon::start_data_table_header_row().
                   3562: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3563: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3564:     my %scoreptr = (
                   3565: 		    'correct'  =>'correct_by_override',
                   3566: 		    'incorrect'=>'incorrect_by_override',
                   3567: 		    'excused'  =>'excused',
                   3568: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3569:                     'credited' =>'credit_attempted',
1.43      ng       3570: 		    'nothing'  => '',
                   3571: 		    );
1.257     albertel 3572:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3573: 
1.44      ng       3574:     my (@partid);
                   3575:     my %weight = ();
1.54      albertel 3576:     my %columns = ();
1.44      ng       3577:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3578: 
1.582     raeburn  3579:     my $partserror;
                   3580:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3581:     if ($partserror) {
                   3582:         return &navmap_errormsg();
                   3583:     }
1.54      albertel 3584:     my $header;
1.257     albertel 3585:     while ($ctr < $env{'form.totalparts'}) {
                   3586: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3587: 	push(@partid,$partid);
1.257     albertel 3588: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3589: 	$ctr++;
1.54      albertel 3590:     }
1.324     albertel 3591:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3592:     foreach my $partid (@partid) {
1.478     albertel 3593: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3594: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3595: 	$columns{$partid}=2;
                   3596: 	foreach my $stores (@parts) {
                   3597: 	    my ($part,$type) = &split_part_type($stores);
                   3598: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3599: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3600: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3601: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3602:             my $narrowtext = &mt('Tries');
                   3603: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3604: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3605: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3606: 	    $columns{$partid}+=2;
                   3607: 	}
                   3608:     }
                   3609:     foreach my $partid (@partid) {
1.324     albertel 3610: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3611: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3612: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3613: 	    '</th>';
1.54      albertel 3614: 
1.44      ng       3615:     }
1.477     albertel 3616:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3617: 	&Apache::loncommon::start_data_table_header_row().
                   3618: 	$header.
                   3619: 	&Apache::loncommon::end_data_table_header_row();
                   3620:     my @noupdate;
1.126     ng       3621:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3622:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3623: 	my $line;
1.257     albertel 3624: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3625: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3626: 	my %newrecord;
                   3627: 	my $updateflag = 0;
1.281     albertel 3628: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3629: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3630: 	if (!&canmodify($usec)) {
1.126     ng       3631: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3632: 	    push(@noupdate,
1.478     albertel 3633: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3634: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3635: 	    next;
                   3636: 	}
1.269     raeburn  3637:         my %aggregate = ();
                   3638:         my $aggregateflag = 0;
1.281     albertel 3639: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3640: 	foreach (@partid) {
1.257     albertel 3641: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3642: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3643: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3644: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3645: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3646: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3647: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3648: 	    my $score;
                   3649: 	    if ($partial eq '') {
1.257     albertel 3650: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3651: 	    } elsif ($partial > 0) {
                   3652: 		$score = 'correct_by_override';
                   3653: 	    } elsif ($partial == 0) {
                   3654: 		$score = 'incorrect_by_override';
                   3655: 	    }
1.257     albertel 3656: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3657: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3658: 
1.292     albertel 3659: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3660: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3661: 	    if ($dropMenu eq 'reset status' &&
                   3662: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3663: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3664: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3665: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3666: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3667: 		$updateflag = 1;
1.269     raeburn  3668:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3669:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3670:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3671:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3672:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3673:                     $aggregateflag = 1;
                   3674:                 }
1.139     albertel 3675: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3676: 		$updateflag = 1;
                   3677: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3678: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3679: 		$rec_update++;
1.125     ng       3680: 	    }
                   3681: 
1.93      albertel 3682: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3683: 		'<td align="center">'.$awarded.
                   3684: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3685: 
1.54      albertel 3686: 
                   3687: 	    my $partid=$_;
                   3688: 	    foreach my $stores (@parts) {
                   3689: 		my ($part,$type) = &split_part_type($stores);
                   3690: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3691: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3692: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3693: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3694: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3695: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3696: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3697: 		    $updateflag=1;
                   3698: 		}
1.93      albertel 3699: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3700: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3701: 	    }
1.44      ng       3702: 	}
1.477     albertel 3703: 	$line.="\n";
1.301     albertel 3704: 
                   3705: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3706: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3707: 
1.44      ng       3708: 	if ($updateflag) {
                   3709: 	    $count++;
1.257     albertel 3710: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3711: 				    $udom,$uname);
1.301     albertel 3712: 
                   3713: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3714: 					      $cnum,$udom,$uname)) {
                   3715: 		# need to figure out if should be in queue.
                   3716: 		my %record =  
                   3717: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3718: 					     $udom,$uname);
                   3719: 		my $all_graded = 1;
                   3720: 		my $none_graded = 1;
                   3721: 		foreach my $part (@parts) {
                   3722: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3723: 			$all_graded = 0;
                   3724: 		    } else {
                   3725: 			$none_graded = 0;
                   3726: 		    }
                   3727: 		}
                   3728: 
                   3729: 		if ($all_graded || $none_graded) {
                   3730: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3731: 							   $symb,$cdom,$cnum,
                   3732: 							   $udom,$uname);
                   3733: 		}
                   3734: 	    }
                   3735: 
1.477     albertel 3736: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3737: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3738: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3739: 	    $updateCtr++;
1.93      albertel 3740: 	} else {
1.477     albertel 3741: 	    push(@noupdate,
                   3742: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3743: 	    $noupdateCtr++;
1.44      ng       3744: 	}
1.269     raeburn  3745:         if ($aggregateflag) {
                   3746:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3747: 				  $cdom,$cnum);
1.269     raeburn  3748:         }
1.93      albertel 3749:     }
1.477     albertel 3750:     if (@noupdate) {
1.126     ng       3751: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3752: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3753: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3754: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3755: 	    &mt('No Changes Occurred For the Students Below').
                   3756: 	    '</td>'.
1.477     albertel 3757: 	    &Apache::loncommon::end_data_table_row();
                   3758: 	foreach my $line (@noupdate) {
                   3759: 	    $result.=
                   3760: 		&Apache::loncommon::start_data_table_row().
                   3761: 		$line.
                   3762: 		&Apache::loncommon::end_data_table_row();
                   3763: 	}
1.44      ng       3764:     }
1.614     www      3765:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3766:     my $msg = '<p><b>'.
                   3767: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3768: 	    $rec_update,$count).'</b><br />'.
                   3769: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3770: 	'</b></p>';
1.44      ng       3771:     return $title.$msg.$result;
1.5       albertel 3772: }
1.54      albertel 3773: 
                   3774: sub split_part_type {
                   3775:     my ($partstr) = @_;
                   3776:     my ($temp,@allparts)=split(/_/,$partstr);
                   3777:     my $type=pop(@allparts);
1.439     albertel 3778:     my $part=join('_',@allparts);
1.54      albertel 3779:     return ($part,$type);
                   3780: }
                   3781: 
1.44      ng       3782: #------------- end of section for handling grading by section/class ---------
                   3783: #
                   3784: #----------------------------------------------------------------------------
                   3785: 
1.5       albertel 3786: 
1.44      ng       3787: #----------------------------------------------------------------------------
                   3788: #
                   3789: #-------------------------- Next few routines handles grading by csv upload
                   3790: #
                   3791: #--- Javascript to handle csv upload
1.27      albertel 3792: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3793:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3794:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3795:   return(<<ENDPICK);
                   3796:   function verify(vf) {
                   3797:     var foundsomething=0;
                   3798:     var founduname=0;
1.243     albertel 3799:     var foundID=0;
1.27      albertel 3800:     for (i=0;i<=vf.nfields.value;i++) {
                   3801:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3802:       if (i==0 && tw!=0) { foundID=1; }
                   3803:       if (i==1 && tw!=0) { founduname=1; }
                   3804:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3805:     }
1.246     albertel 3806:     if (founduname==0 && foundID==0) {
                   3807: 	alert('$error1');
                   3808: 	return;
1.27      albertel 3809:     }
                   3810:     if (foundsomething==0) {
1.246     albertel 3811: 	alert('$error2');
                   3812: 	return;
1.27      albertel 3813:     }
                   3814:     vf.submit();
                   3815:   }
                   3816:   function flip(vf,tf) {
                   3817:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3818:     var i;
                   3819:     for (i=0;i<=vf.nfields.value;i++) {
                   3820:       //can not pick the same destination field for both name and domain
                   3821:       if (((i ==0)||(i ==1)) && 
                   3822:           ((tf==0)||(tf==1)) && 
                   3823:           (i!=tf) &&
                   3824:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3825:         eval('vf.f'+i+'.selectedIndex=0;')
                   3826:       }
                   3827:     }
                   3828:   }
                   3829: ENDPICK
                   3830: }
                   3831: 
                   3832: sub csvupload_javascript_forward_associate {
1.573     bisitz   3833:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3834:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3835:   return(<<ENDPICK);
                   3836:   function verify(vf) {
                   3837:     var foundsomething=0;
                   3838:     var founduname=0;
1.243     albertel 3839:     var foundID=0;
1.27      albertel 3840:     for (i=0;i<=vf.nfields.value;i++) {
                   3841:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3842:       if (tw==1) { foundID=1; }
                   3843:       if (tw==2) { founduname=1; }
                   3844:       if (tw>3) { foundsomething=1; }
1.27      albertel 3845:     }
1.246     albertel 3846:     if (founduname==0 && foundID==0) {
                   3847: 	alert('$error1');
                   3848: 	return;
1.27      albertel 3849:     }
                   3850:     if (foundsomething==0) {
1.246     albertel 3851: 	alert('$error2');
                   3852: 	return;
1.27      albertel 3853:     }
                   3854:     vf.submit();
                   3855:   }
                   3856:   function flip(vf,tf) {
                   3857:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3858:     var i;
                   3859:     //can not pick the same destination field twice
                   3860:     for (i=0;i<=vf.nfields.value;i++) {
                   3861:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3862:         eval('vf.f'+i+'.selectedIndex=0;')
                   3863:       }
                   3864:     }
                   3865:   }
                   3866: ENDPICK
                   3867: }
                   3868: 
1.26      albertel 3869: sub csvuploadmap_header {
1.324     albertel 3870:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3871:     my $javascript;
1.257     albertel 3872:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3873: 	$javascript=&csvupload_javascript_reverse_associate();
                   3874:     } else {
                   3875: 	$javascript=&csvupload_javascript_forward_associate();
                   3876:     }
1.45      ng       3877: 
1.418     albertel 3878:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3879:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3880:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3881:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3882:     my $reverse=&mt("Reverse Association");
1.41      ng       3883:     $request->print(<<ENDPICK);
1.632     www      3884: <br />
                   3885: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3886: <input type="hidden" name="associate"  value="" />
                   3887: <input type="hidden" name="phase"      value="three" />
                   3888: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3889: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3890: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3891: <input type="hidden" name="upfile_associate" 
1.257     albertel 3892:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3893: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3894: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3895: <hr />
                   3896: ENDPICK
1.597     wenzelju 3897:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3898:     return '';
1.26      albertel 3899: 
                   3900: }
                   3901: 
                   3902: sub csvupload_fields {
1.582     raeburn  3903:     my ($symb,$errorref) = @_;
                   3904:     my (@parts) = &getpartlist($symb,$errorref);
                   3905:     if (ref($errorref)) {
                   3906:         if ($$errorref) {
                   3907:             return;
                   3908:         }
                   3909:     }
                   3910: 
1.556     weissno  3911:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3912: 		['username','Student Username'],
                   3913: 		['domain','Student Domain']);
1.324     albertel 3914:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3915:     foreach my $part (sort(@parts)) {
                   3916: 	my @datum;
                   3917: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3918: 	my $name=$part;
                   3919: 	if  (!$display) { $display = $name; }
                   3920: 	@datum=($name,$display);
1.244     albertel 3921: 	if ($name=~/^stores_(.*)_awarded/) {
                   3922: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3923: 	}
1.41      ng       3924: 	push(@fields,\@datum);
                   3925:     }
                   3926:     return (@fields);
1.26      albertel 3927: }
                   3928: 
                   3929: sub csvuploadmap_footer {
1.41      ng       3930:     my ($request,$i,$keyfields) =@_;
                   3931:     $request->print(<<ENDPICK);
1.26      albertel 3932: </table>
                   3933: <input type="hidden" name="nfields" value="$i" />
                   3934: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3935: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3936: </form>
                   3937: ENDPICK
                   3938: }
                   3939: 
1.283     albertel 3940: sub checkforfile_js {
1.638     www      3941:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3942:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3943:     function checkUpload(formname) {
                   3944: 	if (formname.upfile.value == "") {
1.539     riegler  3945: 	    alert("$alertmsg");
1.86      ng       3946: 	    return false;
                   3947: 	}
                   3948: 	formname.submit();
                   3949:     }
                   3950: CSVFORMJS
1.283     albertel 3951:     return $result;
                   3952: }
                   3953: 
                   3954: sub upcsvScores_form {
1.608     www      3955:     my ($request,$symb) = @_;
1.283     albertel 3956:     if (!$symb) {return '';}
                   3957:     my $result=&checkforfile_js();
1.632     www      3958:     $result.=&Apache::loncommon::start_data_table().
                   3959:              &Apache::loncommon::start_data_table_header_row().
                   3960:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3961:              &Apache::loncommon::end_data_table_header_row().
                   3962:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3963:     my $upload=&mt("Upload Scores");
1.86      ng       3964:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3965:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3966:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3967:     $result.=<<ENDUPFORM;
1.106     albertel 3968: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3969: <input type="hidden" name="symb" value="$symb" />
                   3970: <input type="hidden" name="command" value="csvuploadmap" />
                   3971: $upfile_select
1.589     bisitz   3972: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3973: </form>
                   3974: ENDUPFORM
1.370     www      3975:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3976:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3977:              '</td>'.
                   3978:             &Apache::loncommon::end_data_table_row().
                   3979:             &Apache::loncommon::end_data_table();
1.86      ng       3980:     return $result;
                   3981: }
                   3982: 
                   3983: 
1.26      albertel 3984: sub csvuploadmap {
1.608     www      3985:     my ($request,$symb)= @_;
1.41      ng       3986:     if (!$symb) {return '';}
1.72      ng       3987: 
1.41      ng       3988:     my $datatoken;
1.257     albertel 3989:     if (!$env{'form.datatoken'}) {
1.41      ng       3990: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3991:     } else {
1.257     albertel 3992: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3993: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3994:     }
1.41      ng       3995:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3996:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3997:     my ($i,$keyfields);
                   3998:     if (@records) {
1.582     raeburn  3999:         my $fieldserror;
                   4000: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4001:         if ($fieldserror) {
                   4002:             $request->print(&navmap_errormsg());
                   4003:             return;
                   4004:         }
1.257     albertel 4005: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4006: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4007: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4008: 							  \@fields);
                   4009: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4010: 	    chop($keyfields);
                   4011: 	} else {
                   4012: 	    unshift(@fields,['none','']);
                   4013: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4014: 							    \@fields);
1.311     banghart 4015:             foreach my $rec (@records) {
                   4016:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4017:                 if (%temp) {
                   4018:                     $keyfields=join(',',sort(keys(%temp)));
                   4019:                     last;
                   4020:                 }
                   4021:             }
1.41      ng       4022: 	}
                   4023:     }
                   4024:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4025: 
1.41      ng       4026:     return '';
1.27      albertel 4027: }
                   4028: 
1.246     albertel 4029: sub csvuploadoptions {
1.608     www      4030:     my ($request,$symb)= @_;
1.632     www      4031:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4032:     $request->print(<<ENDPICK);
                   4033: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4034: <input type="hidden" name="command"    value="csvuploadassign" />
                   4035: <p>
                   4036: <label>
                   4037:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4038:    $overwrite
1.246     albertel 4039: </label>
                   4040: </p>
                   4041: ENDPICK
                   4042:     my %fields=&get_fields();
                   4043:     if (!defined($fields{'domain'})) {
1.257     albertel 4044: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4045: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4046:     }
1.257     albertel 4047:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4048: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4049: 	my $cleankey=$1;
                   4050: 	if ($cleankey eq 'command') { next; }
                   4051: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4052: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4053:     }
                   4054:     # FIXME do a check for any duplicated user ids...
                   4055:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4056:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4057: <hr /></form>'."\n");
1.246     albertel 4058:     return '';
                   4059: }
                   4060: 
                   4061: sub get_fields {
                   4062:     my %fields;
1.257     albertel 4063:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4064:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4065: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4066: 	    if ($env{'form.f'.$i} ne 'none') {
                   4067: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4068: 	    }
                   4069: 	} else {
1.257     albertel 4070: 	    if ($env{'form.f'.$i} ne 'none') {
                   4071: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4072: 	    }
                   4073: 	}
1.27      albertel 4074:     }
1.246     albertel 4075:     return %fields;
                   4076: }
                   4077: 
                   4078: sub csvuploadassign {
1.608     www      4079:     my ($request,$symb)= @_;
1.246     albertel 4080:     if (!$symb) {return '';}
1.345     bowersj2 4081:     my $error_msg = '';
1.246     albertel 4082:     &Apache::loncommon::load_tmp_file($request);
                   4083:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4084:     my %fields=&get_fields();
1.257     albertel 4085:     my $courseid=$env{'request.course.id'};
1.97      albertel 4086:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4087:     my @notallowed;
1.41      ng       4088:     my @skipped;
                   4089:     my $countdone=0;
                   4090:     foreach my $grade (@gradedata) {
                   4091: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4092: 	my $domain;
                   4093: 	if ($entries{$fields{'domain'}}) {
                   4094: 	    $domain=$entries{$fields{'domain'}};
                   4095: 	} else {
1.257     albertel 4096: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4097: 	}
1.243     albertel 4098: 	$domain=~s/\s//g;
1.41      ng       4099: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4100: 	$username=~s/\s//g;
1.243     albertel 4101: 	if (!$username) {
                   4102: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4103: 	    $id=~s/\s//g;
1.243     albertel 4104: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4105: 	    $username=$ids{$id};
                   4106: 	}
1.41      ng       4107: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4108: 	    my $id=$entries{$fields{'ID'}};
                   4109: 	    $id=~s/\s//g;
                   4110: 	    if ($id) {
                   4111: 		push(@skipped,"$id:$domain");
                   4112: 	    } else {
                   4113: 		push(@skipped,"$username:$domain");
                   4114: 	    }
1.41      ng       4115: 	    next;
                   4116: 	}
1.108     albertel 4117: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4118: 	if (!&canmodify($usec)) {
                   4119: 	    push(@notallowed,"$username:$domain");
                   4120: 	    next;
                   4121: 	}
1.244     albertel 4122: 	my %points;
1.41      ng       4123: 	my %grades;
                   4124: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4125: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4126: 		$dest eq 'domain') { next; }
                   4127: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4128: 	    if ($dest=~/stores_(.*)_points/) {
                   4129: 		my $part=$1;
                   4130: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4131: 					      $symb,$domain,$username);
1.345     bowersj2 4132:                 if ($wgt) {
                   4133:                     $entries{$fields{$dest}}=~s/\s//g;
                   4134:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4135:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4136:                                           : 'correct_by_override';
1.638     www      4137:                     if ($pcr>1) {
                   4138:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4139:                     }
1.345     bowersj2 4140:                     $grades{"resource.$part.awarded"}=$pcr;
                   4141:                     $grades{"resource.$part.solved"}=$award;
                   4142:                     $points{$part}=1;
                   4143:                 } else {
                   4144:                     $error_msg = "<br />" .
                   4145:                         &mt("Some point values were assigned"
                   4146:                             ." for problems with a weight "
                   4147:                             ."of zero. These values were "
                   4148:                             ."ignored.");
                   4149:                 }
1.244     albertel 4150: 	    } else {
                   4151: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4152: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4153: 		my $store_key=$dest;
                   4154: 		$store_key=~s/^stores/resource/;
                   4155: 		$store_key=~s/_/\./g;
                   4156: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4157: 	    }
1.41      ng       4158: 	}
1.508     www      4159: 	if (! %grades) { 
                   4160:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4161:         } else {
                   4162: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4163: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4164: 					   $env{'request.course.id'},
                   4165: 					   $domain,$username);
1.508     www      4166: 	   if ($result eq 'ok') {
1.627     www      4167: # Successfully stored
1.508     www      4168: 	      $request->print('.');
1.627     www      4169: # Remove from grading queue
                   4170:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4171:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4172:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4173:                                              $domain,$username);
                   4174:               $countdone++;
                   4175:            } else {
1.508     www      4176: 	      $request->print("<p><span class=\"LC_error\">".
                   4177:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4178:                                   "$username:$domain",$result)."</span></p>");
                   4179: 	   }
                   4180: 	   $request->rflush();
                   4181:         }
1.41      ng       4182:     }
1.570     www      4183:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4184:     if (@skipped) {
1.571     www      4185: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4186:         $request->print(join(', ',@skipped));
1.106     albertel 4187:     }
                   4188:     if (@notallowed) {
1.571     www      4189: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4190: 	$request->print(join(', ',@notallowed));
1.41      ng       4191:     }
1.106     albertel 4192:     $request->print("<br />\n");
1.345     bowersj2 4193:     return $error_msg;
1.26      albertel 4194: }
1.44      ng       4195: #------------- end of section for handling csv file upload ---------
                   4196: #
                   4197: #-------------------------------------------------------------------
                   4198: #
1.122     ng       4199: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4200: #
                   4201: #--- Select a page/sequence and a student to grade
1.68      ng       4202: sub pickStudentPage {
1.608     www      4203:     my ($request,$symb) = @_;
1.68      ng       4204: 
1.539     riegler  4205:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4206:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4207: 
                   4208: function checkPickOne(formname) {
1.76      ng       4209:     if (radioSelection(formname.student) == null) {
1.539     riegler  4210: 	alert("$alertmsg");
1.68      ng       4211: 	return;
                   4212:     }
1.125     ng       4213:     ptr = pullDownSelection(formname.selectpage);
                   4214:     formname.page.value = formname["page"+ptr].value;
                   4215:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4216:     formname.submit();
                   4217: }
                   4218: 
                   4219: LISTJAVASCRIPT
1.118     ng       4220:     &commonJSfunctions($request);
1.608     www      4221: 
1.257     albertel 4222:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4223:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4224:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4225: 
1.398     albertel 4226:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4227: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4228: 
1.80      ng       4229:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4230:     my $map_error;
                   4231:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4232:     if ($map_error) {
                   4233:         $request->print(&navmap_errormsg());
                   4234:         return; 
                   4235:     }
1.137     albertel 4236:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4237: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4238: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4239:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4240:     my $ctr=0;
1.68      ng       4241:     foreach (@$titles) {
                   4242: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4243: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4244: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4245: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4246: 	$ctr++;
1.68      ng       4247:     }
1.485     albertel 4248:     $select.= '</select>';
1.539     riegler  4249:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4250: 
1.70      ng       4251:     $ctr=0;
                   4252:     foreach (@$titles) {
                   4253: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4254: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4255: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4256: 	$ctr++;
                   4257:     }
1.72      ng       4258:     $result.='<input type="hidden" name="page" />'."\n".
                   4259: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4260: 
1.485     albertel 4261:     my $options =
                   4262: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4263: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4264:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4265: 
                   4266:     $options =
                   4267: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4268: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4269: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4270:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4271:     
                   4272:     $result.=&build_section_inputs();
1.442     banghart 4273:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4274:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4275: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4276: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4277: 
1.539     riegler  4278:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4279: 
1.80      ng       4280:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4281:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4282: 
1.68      ng       4283:     $request->print($result);
                   4284: 
1.485     albertel 4285:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4286: 	&Apache::loncommon::start_data_table().
                   4287: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4288: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4289: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4290: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4291: 	'<th>'.&nameUserString('header').'</th>'.
                   4292: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4293:  
1.76      ng       4294:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4295:     my $ptr = 1;
1.294     albertel 4296:     foreach my $student (sort 
                   4297: 			 {
                   4298: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4299: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4300: 			     }
                   4301: 			     return $a cmp $b;
                   4302: 			 } (keys(%$fullname))) {
1.68      ng       4303: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4304: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4305:                                   : '</td>');
1.126     ng       4306: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4307: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4308: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4309: 	$studentTable.=
                   4310: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4311:                          : '');
1.68      ng       4312: 	$ptr++;
                   4313:     }
1.484     albertel 4314:     if ($ptr%2 == 0) {
                   4315: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4316: 	    &Apache::loncommon::end_data_table_row();
                   4317:     }
                   4318:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4319:     $studentTable.='<input type="button" '.
1.589     bisitz   4320:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4321: 
                   4322:     $request->print($studentTable);
                   4323: 
                   4324:     return '';
                   4325: }
                   4326: 
                   4327: sub getSymbMap {
1.582     raeburn  4328:     my ($map_error) = @_;
1.132     bowersj2 4329:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4330:     unless (ref($navmap)) {
                   4331:         if (ref($map_error)) {
                   4332:             $$map_error = 'navmap';
                   4333:         }
                   4334:         return;
                   4335:     }
1.68      ng       4336:     my %symbx = ();
                   4337:     my @titles = ();
1.117     bowersj2 4338:     my $minder = 0;
                   4339: 
                   4340:     # Gather every sequence that has problems.
1.240     albertel 4341:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4342: 					       1,0,1);
1.117     bowersj2 4343:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4344: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4345: 	    my $title = $minder.'.'.
                   4346: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4347: 	    push(@titles, $title); # minder in case two titles are identical
                   4348: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4349: 	    $minder++;
1.241     albertel 4350: 	}
1.68      ng       4351:     }
                   4352:     return \@titles,\%symbx;
                   4353: }
                   4354: 
1.72      ng       4355: #
                   4356: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4357: sub displayPage {
1.608     www      4358:     my ($request,$symb) = @_;
1.257     albertel 4359:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4360:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4361:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4362:     my $pageTitle = $env{'form.page'};
1.103     albertel 4363:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4364:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4365:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4366: 
                   4367:     #need to make sure we have the correct data for later EXT calls, 
                   4368:     #thus invalidate the cache
                   4369:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4370:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4371:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4372:     &Apache::lonnet::clear_EXT_cache_status();
                   4373: 
1.103     albertel 4374:     if (!&canview($usec)) {
1.485     albertel 4375: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4376: 	return;
                   4377:     }
1.398     albertel 4378:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4379:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4380: 	'</h3>'."\n";
1.500     albertel 4381:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4382:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4383: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4384:     } else {
                   4385: 	delete($env{'form.CODE'});
                   4386:     }
1.71      ng       4387:     &sub_page_js($request);
                   4388:     $request->print($result);
                   4389: 
1.132     bowersj2 4390:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4391:     unless (ref($navmap)) {
                   4392:         $request->print(&navmap_errormsg());
                   4393:         return;
                   4394:     }
1.257     albertel 4395:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4396:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4397:     if (!$map) {
1.485     albertel 4398: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4399: 	return; 
                   4400:     }
1.68      ng       4401:     my $iterator = $navmap->getIterator($map->map_start(),
                   4402: 					$map->map_finish());
                   4403: 
1.71      ng       4404:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4405: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4406: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4407: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4408: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4409: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4410: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4411: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4412: 
1.382     albertel 4413:     if (defined($env{'form.CODE'})) {
                   4414: 	$studentTable.=
                   4415: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4416:     }
1.381     albertel 4417:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4418: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4419: 
1.594     bisitz   4420:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4421:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4422:         '</span>'."\n".
1.484     albertel 4423: 	&Apache::loncommon::start_data_table().
                   4424: 	&Apache::loncommon::start_data_table_header_row().
                   4425: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4426: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4427: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4428: 
1.329     albertel 4429:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4430:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4431:     $iterator->next(); # skip the first BEGIN_MAP
                   4432:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4433:     while ($depth > 0) {
1.68      ng       4434:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4435:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4436: 
1.385     albertel 4437:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4438: 	    my $parts = $curRes->parts();
1.68      ng       4439:             my $title = $curRes->compTitle();
1.71      ng       4440: 	    my $symbx = $curRes->symb();
1.484     albertel 4441: 	    $studentTable.=
                   4442: 		&Apache::loncommon::start_data_table_row().
                   4443: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4444: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4445: 		                        : '<br />('.&mt('[_1]parts)',
                   4446: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4447: 		 ).
                   4448: 		 '</td>';
1.71      ng       4449: 	    $studentTable.='<td valign="top">';
1.382     albertel 4450: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4451: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4452: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4453: 					     undef,'both',\%form);
1.71      ng       4454: 	    } else {
1.382     albertel 4455: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4456: 		$companswer =~ s|<form(.*?)>||g;
                   4457: 		$companswer =~ s|</form>||g;
1.71      ng       4458: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4459: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4460: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4461: #		}
1.116     ng       4462: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4463: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4464: 	    }
                   4465: 
1.257     albertel 4466: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4467: 
1.257     albertel 4468: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4469: 		if ($record{'version'} eq '') {
1.485     albertel 4470: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4471: 		} else {
1.116     ng       4472: 		    my %responseType = ();
                   4473: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4474: 			my @responseIds =$curRes->responseIds($partid);
                   4475: 			my @responseType =$curRes->responseType($partid);
                   4476: 			my %responseIds;
                   4477: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4478: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4479: 			}
                   4480: 			$responseType{$partid} = \%responseIds;
1.116     ng       4481: 		    }
1.148     albertel 4482: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4483: 
1.71      ng       4484: 		}
1.257     albertel 4485: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4486: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4487: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4488: 									$env{'request.course.id'},
1.71      ng       4489: 									'','.submission');
                   4490:  
                   4491: 	    }
1.103     albertel 4492: 	    if (&canmodify($usec)) {
1.585     bisitz   4493:             $studentTable.=&gradeBox_start();
1.103     albertel 4494: 		foreach my $partid (@{$parts}) {
                   4495: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4496: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4497: 		    $question++;
                   4498: 		}
1.585     bisitz   4499:             $studentTable.=&gradeBox_end();
1.196     albertel 4500: 		$prob++;
1.71      ng       4501: 	    }
                   4502: 	    $studentTable.='</td></tr>';
1.68      ng       4503: 
1.103     albertel 4504: 	}
1.68      ng       4505:         $curRes = $iterator->next();
                   4506:     }
                   4507: 
1.589     bisitz   4508:     $studentTable.=
                   4509:         '</table>'."\n".
                   4510:         '<input type="button" value="'.&mt('Save').'" '.
                   4511:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4512:         '</form>'."\n";
1.71      ng       4513:     $request->print($studentTable);
                   4514: 
                   4515:     return '';
1.119     ng       4516: }
                   4517: 
                   4518: sub displaySubByDates {
1.148     albertel 4519:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4520:     my $isCODE=0;
1.335     albertel 4521:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4522:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4523:     my $studentTable=&Apache::loncommon::start_data_table().
                   4524: 	&Apache::loncommon::start_data_table_header_row().
                   4525: 	'<th>'.&mt('Date/Time').'</th>'.
                   4526: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4527: 	'<th>'.&mt('Submission').'</th>'.
                   4528: 	'<th>'.&mt('Status').'</th>'.
                   4529: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4530:     my ($version);
                   4531:     my %mark;
1.148     albertel 4532:     my %orders;
1.119     ng       4533:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4534:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4535: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4536:     }
1.335     albertel 4537: 
                   4538:     my $interaction;
1.525     raeburn  4539:     my $no_increment = 1;
1.640     raeburn  4540:     my %lastrndseed;
1.119     ng       4541:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4542: 	my $timestamp = 
                   4543: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4544: 	if (exists($$record{$version.':resource.0.version'})) {
                   4545: 	    $interaction = $$record{$version.':resource.0.version'};
                   4546: 	}
                   4547: 
                   4548: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4549: 		             : "$version:resource");
1.467     albertel 4550: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4551: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4552: 	if ($isCODE) {
                   4553: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4554: 	}
1.119     ng       4555: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4556: 	my @displaySub = ();
                   4557: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4558:             my ($hidden,$type);
                   4559:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4560:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4561:                 $hidden = 1;
                   4562:             }
1.335     albertel 4563: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4564: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4565: 	    
1.122     ng       4566: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4567: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4568: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4569: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4570: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4571:                     
1.335     albertel 4572: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4573: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4574:                     $displaySub[0].='<span class="LC_nobreak"';
                   4575:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4576:                                    .' <span class="LC_internal_info">'
1.625     www      4577:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4578:                                    .'</span>'
                   4579:                                    .' <b>';
1.596     raeburn  4580:                     if ($hidden) {
                   4581:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4582:                     } else {
1.640     raeburn  4583:                         my ($trial,$rndseed,$newvariation);
                   4584:                         if ($type eq 'randomizetry') {
                   4585:                             $trial = $$record{"$where.$partid.tries"};
                   4586:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4587:                         }
1.596     raeburn  4588: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4589: 			    $displaySub[0].=&mt('Trial not counted');
                   4590: 		        } else {
                   4591: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4592: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4593:                             if ($rndseed || $lastrndseed{$partid}) {
                   4594:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4595:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4596:                                 }
                   4597:                             }
                   4598:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4599: 		        }
                   4600: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4601:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4602: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4603: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4604: 			    $orders{$partid}->{$responseId}=
                   4605: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4606:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4607: 		        }
1.640     raeburn  4608: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4609: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4610: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4611:                     }
1.147     albertel 4612: 		}
                   4613: 	    }
1.335     albertel 4614: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4615: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4616: 				    $$record{"$where.$partid.checkedin"},
                   4617: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4618: 					'<br />';
1.335     albertel 4619: 	    }
                   4620: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4621: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4622: 		    lc($$record{"$where.$partid.award"}).' '.
                   4623: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4624: 		    '<br />';
                   4625: 	    }
1.335     albertel 4626: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4627: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4628: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4629: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4630: 		$displaySub[2].=
                   4631: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4632: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4633: 	    }
                   4634: 	}
                   4635: 	# needed because old essay regrader has not parts info
                   4636: 	if (exists $$record{"$version:resource.regrader"}) {
                   4637: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4638: 	}
                   4639: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4640: 	if ($displaySub[2]) {
1.467     albertel 4641: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4642: 	}
1.467     albertel 4643: 	$studentTable.='&nbsp;</td>'.
                   4644: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4645:     }
1.467     albertel 4646:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4647:     return $studentTable;
1.71      ng       4648: }
                   4649: 
                   4650: sub updateGradeByPage {
1.608     www      4651:     my ($request,$symb) = @_;
1.71      ng       4652: 
1.257     albertel 4653:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4654:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4655:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4656:     my $pageTitle = $env{'form.page'};
1.103     albertel 4657:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4658:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4659:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4660:     if (!&canmodify($usec)) {
1.526     raeburn  4661: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4662: 	return;
                   4663:     }
1.398     albertel 4664:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4665:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4666: 	'</h3>'."\n";
1.70      ng       4667: 
1.68      ng       4668:     $request->print($result);
                   4669: 
1.582     raeburn  4670: 
1.132     bowersj2 4671:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4672:     unless (ref($navmap)) {
                   4673:         $request->print(&navmap_errormsg());
                   4674:         return;
                   4675:     }
1.257     albertel 4676:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4677:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4678:     if (!$map) {
1.527     raeburn  4679: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4680: 	return; 
                   4681:     }
1.71      ng       4682:     my $iterator = $navmap->getIterator($map->map_start(),
                   4683: 					$map->map_finish());
1.70      ng       4684: 
1.484     albertel 4685:     my $studentTable=
                   4686: 	&Apache::loncommon::start_data_table().
                   4687: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4688: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4689: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4690: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4691: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4692: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4693: 
                   4694:     $iterator->next(); # skip the first BEGIN_MAP
                   4695:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4696:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4697:     while ($depth > 0) {
1.71      ng       4698:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4699:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4700: 
1.385     albertel 4701:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4702: 	    my $parts = $curRes->parts();
1.71      ng       4703:             my $title = $curRes->compTitle();
                   4704: 	    my $symbx = $curRes->symb();
1.484     albertel 4705: 	    $studentTable.=
                   4706: 		&Apache::loncommon::start_data_table_row().
                   4707: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4708: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4709:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4710: 		.')').'</td>';
1.71      ng       4711: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4712: 
                   4713: 	    my %newrecord=();
                   4714: 	    my @displayPts=();
1.269     raeburn  4715:             my %aggregate = ();
                   4716:             my $aggregateflag = 0;
1.71      ng       4717: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4718: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4719: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4720: 
1.257     albertel 4721: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4722: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4723: 		my $partial = $newpts/$wgt;
                   4724: 		my $score;
                   4725: 		if ($partial > 0) {
                   4726: 		    $score = 'correct_by_override';
1.125     ng       4727: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4728: 		    $score = 'incorrect_by_override';
                   4729: 		}
1.257     albertel 4730: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4731: 		if ($dropMenu eq 'excused') {
1.71      ng       4732: 		    $partial = '';
                   4733: 		    $score = 'excused';
1.125     ng       4734: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4735: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4736: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4737: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4738: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4739: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4740: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4741: 		    $changeflag++;
                   4742: 		    $newpts = '';
1.269     raeburn  4743:                     
                   4744:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4745:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4746:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4747:                     if ($aggtries > 0) {
                   4748:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4749:                         $aggregateflag = 1;
                   4750:                     }
1.71      ng       4751: 		}
1.324     albertel 4752: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4753: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4754: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4755: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4756: 		    '&nbsp;<br />';
1.526     raeburn  4757: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4758: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4759: 		    '&nbsp;<br />';
1.71      ng       4760: 		$question++;
1.380     albertel 4761: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4762: 
1.71      ng       4763: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4764: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4765: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4766: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4767: 
                   4768: 		$changeflag++;
                   4769: 	    }
                   4770: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4771: 		my %record = 
                   4772: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4773: 					     $udom,$uname);
                   4774: 
                   4775: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4776: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4777: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4778: 		    $newrecord{'resource.CODE'} = '';
                   4779: 		}
1.257     albertel 4780: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4781: 					$udom,$uname);
1.382     albertel 4782: 		%record = &Apache::lonnet::restore($symbx,
                   4783: 						   $env{'request.course.id'},
                   4784: 						   $udom,$uname);
1.380     albertel 4785: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4786: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4787: 	    }
1.380     albertel 4788: 	    
1.269     raeburn  4789:             if ($aggregateflag) {
                   4790:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4791:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4792:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4793:             }
1.125     ng       4794: 
1.71      ng       4795: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4796: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4797: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4798: 
1.196     albertel 4799: 	    $prob++;
1.68      ng       4800: 	}
1.71      ng       4801:         $curRes = $iterator->next();
1.68      ng       4802:     }
1.98      albertel 4803: 
1.484     albertel 4804:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4805:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4806: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4807: 		  $changeflag));
1.76      ng       4808:     $request->print($grademsg.$studentTable);
1.68      ng       4809: 
1.70      ng       4810:     return '';
                   4811: }
                   4812: 
1.72      ng       4813: #-------- end of section for handling grading by page/sequence ---------
                   4814: #
                   4815: #-------------------------------------------------------------------
                   4816: 
1.581     www      4817: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4818: #
                   4819: #------ start of section for handling grading by page/sequence ---------
                   4820: 
1.423     albertel 4821: =pod
                   4822: 
                   4823: =head1 Bubble sheet grading routines
                   4824: 
1.424     albertel 4825:   For this documentation:
                   4826: 
                   4827:    'scanline' refers to the full line of characters
                   4828:    from the file that we are parsing that represents one entire sheet
                   4829: 
                   4830:    'bubble line' refers to the data
                   4831:    representing the line of bubbles that are on the physical bubble sheet
                   4832: 
                   4833: 
                   4834: The overall process is that a scanned in bubble sheet data is uploaded
                   4835: into a course. When a user wants to grade, they select a
                   4836: sequence/folder of resources, a file of bubble sheet info, and pick
                   4837: one of the predefined configurations for what each scanline looks
                   4838: like.
                   4839: 
                   4840: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4841: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4842: because too light bubbling), 'double bubble' (each bubble line should
                   4843: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4844: invalid student/employee ID
1.424     albertel 4845: 
                   4846: If the CODE option is used that determines the randomization of the
1.556     weissno  4847: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4848: username:domain.
                   4849: 
                   4850: During the validation phase the instructor can choose to skip scanlines. 
                   4851: 
1.435     foxr     4852: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4853: 
                   4854:   scantron_original_filename (unmodified original file)
                   4855:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4856:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4857: 
                   4858: Also there is a separate hash nohist_scantrondata that contains extra
                   4859: correction information that isn't representable in the bubble sheet
                   4860: file (see &scantron_getfile() for more information)
                   4861: 
                   4862: After all scanlines are either valid, marked as valid or skipped, then
                   4863: foreach line foreach problem in the picked sequence, an ssi request is
                   4864: made that simulates a user submitting their selected letter(s) against
                   4865: the homework problem.
1.423     albertel 4866: 
                   4867: =over 4
                   4868: 
                   4869: 
                   4870: 
                   4871: =item defaultFormData
                   4872: 
                   4873:   Returns html hidden inputs used to hold context/default values.
                   4874: 
                   4875:  Arguments:
                   4876:   $symb - $symb of the current resource 
                   4877: 
                   4878: =cut
1.422     foxr     4879: 
1.81      albertel 4880: sub defaultFormData {
1.324     albertel 4881:     my ($symb)=@_;
1.613     www      4882:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4883: }
                   4884: 
1.447     foxr     4885: 
1.423     albertel 4886: =pod 
                   4887: 
                   4888: =item getSequenceDropDown
                   4889: 
                   4890:    Return html dropdown of possible sequences to grade
                   4891:  
                   4892:  Arguments:
1.582     raeburn  4893:    $symb - $symb of the current resource
                   4894:    $map_error - ref to scalar which will container error if
                   4895:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4896: 
                   4897: =cut
1.422     foxr     4898: 
1.75      albertel 4899: sub getSequenceDropDown {
1.582     raeburn  4900:     my ($symb,$map_error)=@_;
1.75      albertel 4901:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4902:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4903:     if (ref($map_error)) {
                   4904:         return if ($$map_error);
                   4905:     }
1.137     albertel 4906:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4907:     my $ctr=0;
                   4908:     foreach (@$titles) {
                   4909: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4910: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4911: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4912: 	    '>'.$showtitle.'</option>'."\n";
                   4913: 	$ctr++;
                   4914:     }
                   4915:     $result.= '</select>';
                   4916:     return $result;
                   4917: }
                   4918: 
1.495     albertel 4919: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4920:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4921: 
                   4922: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4923: 
1.509     raeburn  4924: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4925:                                    # matchresponse or rankresponse, where 
                   4926:                                    # an individual response can have multiple 
                   4927:                                    # lines
1.503     raeburn  4928: 
                   4929: my %responsetype_per_response;     # responsetype for each response
                   4930: 
1.495     albertel 4931: # Save and restore the bubble lines array to the form env.
                   4932: 
                   4933: 
                   4934: sub save_bubble_lines {
                   4935:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4936: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4937: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4938: 	    $first_bubble_line{$line};
1.503     raeburn  4939:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4940:             $subdivided_bubble_lines{$line};
                   4941:         $env{"form.scantron.responsetype.$line"} =
                   4942:             $responsetype_per_response{$line};
1.495     albertel 4943:     }
                   4944: }
                   4945: 
                   4946: 
                   4947: sub restore_bubble_lines {
                   4948:     my $line = 0;
                   4949:     %bubble_lines_per_response = ();
                   4950:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4951: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4952: 	$bubble_lines_per_response{$line} = $value;
                   4953: 	$first_bubble_line{$line}  =
                   4954: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4955:         $subdivided_bubble_lines{$line} =
                   4956:             $env{"form.scantron.sub_bubblelines.$line"};
                   4957:         $responsetype_per_response{$line} =
                   4958:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4959: 	$line++;
                   4960:     }
                   4961: }
                   4962: 
                   4963: #  Given the parsed scanline, get the response for 
                   4964: #  'answer' number n:
                   4965: 
                   4966: sub get_response_bubbles {
                   4967:     my ($parsed_line, $response)  = @_;
                   4968: 
                   4969:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4970:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4971:     
                   4972:     my $selected = "";
                   4973: 
                   4974:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4975: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4976: 	$bubble_line++;
                   4977:     }
                   4978:     return $selected;
                   4979: }
1.423     albertel 4980: 
                   4981: =pod 
                   4982: 
                   4983: =item scantron_filenames
                   4984: 
                   4985:    Returns a list of the scantron files in the current course 
                   4986: 
                   4987: =cut
1.422     foxr     4988: 
1.202     albertel 4989: sub scantron_filenames {
1.257     albertel 4990:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4991:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4992:     my $getpropath = 1;
1.157     albertel 4993:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4994:                                        $getpropath);
1.202     albertel 4995:     my @possiblenames;
1.201     albertel 4996:     foreach my $filename (sort(@files)) {
1.157     albertel 4997: 	($filename)=split(/&/,$filename);
                   4998: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4999: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5000: 	push(@possiblenames,$filename);
                   5001:     }
                   5002:     return @possiblenames;
                   5003: }
                   5004: 
1.423     albertel 5005: =pod 
                   5006: 
                   5007: =item scantron_uploads
                   5008: 
                   5009:    Returns  html drop-down list of scantron files in current course.
                   5010: 
                   5011:  Arguments:
                   5012:    $file2grade - filename to set as selected in the dropdown
                   5013: 
                   5014: =cut
1.422     foxr     5015: 
1.202     albertel 5016: sub scantron_uploads {
1.209     ng       5017:     my ($file2grade) = @_;
1.202     albertel 5018:     my $result=	'<select name="scantron_selectfile">';
                   5019:     $result.="<option></option>";
                   5020:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5021: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5022:     }
                   5023:     $result.="</select>";
                   5024:     return $result;
                   5025: }
                   5026: 
1.423     albertel 5027: =pod 
                   5028: 
                   5029: =item scantron_scantab
                   5030: 
                   5031:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5032:   file.
                   5033: 
                   5034: =cut
1.422     foxr     5035: 
1.82      albertel 5036: sub scantron_scantab {
                   5037:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5038:     $result.='<option></option>'."\n";
1.518     raeburn  5039:     my @lines = &get_scantronformat_file();
                   5040:     if (@lines > 0) {
                   5041:         foreach my $line (@lines) {
                   5042:             next if (($line =~ /^\#/) || ($line eq ''));
                   5043: 	    my ($name,$descrip)=split(/:/,$line);
                   5044: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5045:         }
1.82      albertel 5046:     }
                   5047:     $result.='</select>'."\n";
1.518     raeburn  5048:     return $result;
                   5049: }
                   5050: 
                   5051: =pod
                   5052: 
                   5053: =item get_scantronformat_file
                   5054: 
                   5055:   Returns an array containing lines from the scantron format file for
                   5056:   the domain of the course.
                   5057: 
                   5058:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5059:   lines are from this file.
                   5060: 
                   5061:   Otherwise, if a default.tab has been published in RES space by the 
                   5062:   domainconfig user, lines are from this file.
                   5063: 
                   5064:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5065:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5066: 
1.518     raeburn  5067: =cut
                   5068: 
                   5069: sub get_scantronformat_file {
                   5070:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5071:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5072:     my $gottab = 0;
                   5073:     my @lines;
                   5074:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5075:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5076:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5077:             if ($formatfile ne '-1') {
                   5078:                 @lines = split("\n",$formatfile,-1);
                   5079:                 $gottab = 1;
                   5080:             }
                   5081:         }
                   5082:     }
                   5083:     if (!$gottab) {
                   5084:         my $confname = $cdom.'-domainconfig';
                   5085:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5086:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5087:         if ($formatfile ne '-1') {
                   5088:             @lines = split("\n",$formatfile,-1);
                   5089:             $gottab = 1;
                   5090:         }
                   5091:     }
                   5092:     if (!$gottab) {
1.519     raeburn  5093:         my @domains = &Apache::lonnet::current_machine_domains();
                   5094:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5095:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5096:             @lines = <$fh>;
                   5097:             close($fh);
                   5098:         } else {
                   5099:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5100:             @lines = <$fh>;
                   5101:             close($fh);
                   5102:         }
1.518     raeburn  5103:     }
                   5104:     return @lines;
1.82      albertel 5105: }
                   5106: 
1.423     albertel 5107: =pod 
                   5108: 
                   5109: =item scantron_CODElist
                   5110: 
                   5111:   Returns html drop down of the saved CODE lists from current course,
                   5112:   generated from earlier printings.
                   5113: 
                   5114: =cut
1.422     foxr     5115: 
1.186     albertel 5116: sub scantron_CODElist {
1.257     albertel 5117:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5118:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5119:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5120:     my $namechoice='<option></option>';
1.225     albertel 5121:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5122: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5123: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5124: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5125:     }
                   5126:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5127:     return $namechoice;
                   5128: }
                   5129: 
1.423     albertel 5130: =pod 
                   5131: 
                   5132: =item scantron_CODEunique
                   5133: 
                   5134:   Returns the html for "Each CODE to be used once" radio.
                   5135: 
                   5136: =cut
1.422     foxr     5137: 
1.186     albertel 5138: sub scantron_CODEunique {
1.532     bisitz   5139:     my $result='<span class="LC_nobreak">
1.272     albertel 5140:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5141:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5142:                 </span>
1.532     bisitz   5143:                 <span class="LC_nobreak">
1.272     albertel 5144:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5145:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5146:                 </span>';
1.186     albertel 5147:     return $result;
                   5148: }
1.423     albertel 5149: 
                   5150: =pod 
                   5151: 
                   5152: =item scantron_selectphase
                   5153: 
                   5154:   Generates the initial screen to start the bubble sheet process.
                   5155:   Allows for - starting a grading run.
1.424     albertel 5156:              - downloading existing scan data (original, corrected
1.423     albertel 5157:                                                 or skipped info)
                   5158: 
                   5159:              - uploading new scan data
                   5160: 
                   5161:  Arguments:
                   5162:   $r          - The Apache request object
                   5163:   $file2grade - name of the file that contain the scanned data to score
                   5164: 
                   5165: =cut
1.186     albertel 5166: 
1.75      albertel 5167: sub scantron_selectphase {
1.608     www      5168:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5169:     if (!$symb) {return '';}
1.582     raeburn  5170:     my $map_error;
                   5171:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5172:     if ($map_error) {
                   5173:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5174:         return;
                   5175:     }
1.324     albertel 5176:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5177:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5178:     my $format_selector=&scantron_scantab();
1.186     albertel 5179:     my $CODE_selector=&scantron_CODElist();
                   5180:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5181:     my $result;
1.422     foxr     5182: 
1.513     foxr     5183:     $ssi_error = 0;
                   5184: 
1.606     wenzelju 5185:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5186:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5187: 
                   5188: 	# Chunk of form to prompt for a scantron file upload.
                   5189: 
                   5190:         $r->print('
                   5191:     <br />
                   5192:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5193:        '.&Apache::loncommon::start_data_table_header_row().'
                   5194:             <th>
                   5195:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5196:             </th>
                   5197:        '.&Apache::loncommon::end_data_table_header_row().'
                   5198:        '.&Apache::loncommon::start_data_table_row().'
                   5199:             <td>
                   5200: ');
1.608     www      5201:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5202:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5203:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5204:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5205:     function checkUpload(formname) {
                   5206: 	if (formname.upfile.value == "") {
                   5207: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5208: 	    return false;
                   5209: 	}
                   5210: 	formname.submit();
                   5211:     }'));
                   5212:     $r->print('
                   5213:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5214:                 '.$default_form_data.'
                   5215:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5216:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5217:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5218:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5219:                 <br />
                   5220:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5221:               </form>
                   5222: ');
                   5223: 
                   5224:         $r->print('
                   5225:             </td>
                   5226:        '.&Apache::loncommon::end_data_table_row().'
                   5227:        '.&Apache::loncommon::end_data_table().'
                   5228: ');
                   5229:     }
                   5230: 
1.422     foxr     5231:     # Chunk of form to prompt for a file to grade and how:
                   5232: 
1.489     albertel 5233:     $result.= '
                   5234:     <br />
                   5235:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5236:     <input type="hidden" name="command" value="scantron_warning" />
                   5237:     '.$default_form_data.'
                   5238:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5239:        '.&Apache::loncommon::start_data_table_header_row().'
                   5240:             <th colspan="2">
1.492     albertel 5241:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5242:             </th>
                   5243:        '.&Apache::loncommon::end_data_table_header_row().'
                   5244:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5245:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5246:        '.&Apache::loncommon::end_data_table_row().'
                   5247:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5248:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5249:        '.&Apache::loncommon::end_data_table_row().'
                   5250:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5251:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5252:        '.&Apache::loncommon::end_data_table_row().'
                   5253:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5254:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5255:        '.&Apache::loncommon::end_data_table_row().'
                   5256:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5257:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5258:        '.&Apache::loncommon::end_data_table_row().'
                   5259:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5260: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5261:             <td>
1.492     albertel 5262: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5263:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5264:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5265: 	    </td>
1.489     albertel 5266:        '.&Apache::loncommon::end_data_table_row().'
                   5267:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5268:             <td colspan="2">
1.572     www      5269:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5270:             </td>
1.489     albertel 5271:        '.&Apache::loncommon::end_data_table_row().'
                   5272:     '.&Apache::loncommon::end_data_table().'
                   5273:     </form>
                   5274: ';
1.162     albertel 5275:    
                   5276:     $r->print($result);
                   5277: 
1.422     foxr     5278: 
                   5279: 
                   5280:     # Chunk of the form that prompts to view a scoring office file,
                   5281:     # corrected file, skipped records in a file.
                   5282: 
1.489     albertel 5283:     $r->print('
                   5284:    <br />
                   5285:    <form action="/adm/grades" name="scantron_download">
                   5286:      '.$default_form_data.'
                   5287:      <input type="hidden" name="command" value="scantron_download" />
                   5288:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5289:        '.&Apache::loncommon::start_data_table_header_row().'
                   5290:               <th>
1.492     albertel 5291:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5292:               </th>
                   5293:        '.&Apache::loncommon::end_data_table_header_row().'
                   5294:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5295:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5296:                 <br />
1.492     albertel 5297:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5298:        '.&Apache::loncommon::end_data_table_row().'
                   5299:      '.&Apache::loncommon::end_data_table().'
                   5300:    </form>
                   5301:    <br />
                   5302: ');
1.162     albertel 5303: 
1.457     banghart 5304:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5305: 
1.528     raeburn  5306:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5307:              $default_form_data."\n".
                   5308:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5309:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5310:              '<th colspan="2">
1.572     www      5311:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5312:              '</th>'."\n".
                   5313:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5314:               &Apache::loncommon::start_data_table_row()."\n".
                   5315:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5316:               '<td> '.$sequence_selector.' </td>'.
                   5317:               &Apache::loncommon::end_data_table_row()."\n".
                   5318:               &Apache::loncommon::start_data_table_row()."\n".
                   5319:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5320:               '<td> '.$file_selector.' </td>'."\n".
                   5321:               &Apache::loncommon::end_data_table_row()."\n".
                   5322:               &Apache::loncommon::start_data_table_row()."\n".
                   5323:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5324:               '<td> '.$format_selector.' </td>'."\n".
                   5325:               &Apache::loncommon::end_data_table_row()."\n".
                   5326:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5327:               '<td> '.&mt('Options').' </td>'."\n".
                   5328:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5329:               &Apache::loncommon::end_data_table_row()."\n".
                   5330:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5331:               '<td colspan="2">'."\n".
                   5332:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5333:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5334:               '</td>'."\n".
                   5335:               &Apache::loncommon::end_data_table_row()."\n".
                   5336:               &Apache::loncommon::end_data_table()."\n".
                   5337:               '</form><br />');
                   5338:     return;
1.75      albertel 5339: }
                   5340: 
1.423     albertel 5341: =pod
                   5342: 
                   5343: =item get_scantron_config
                   5344: 
                   5345:    Parse and return the scantron configuration line selected as a
                   5346:    hash of configuration file fields.
                   5347: 
                   5348:  Arguments:
                   5349:     which - the name of the configuration to parse from the file.
                   5350: 
                   5351: 
                   5352:  Returns:
                   5353:             If the named configuration is not in the file, an empty
                   5354:             hash is returned.
                   5355:     a hash with the fields
                   5356:       name         - internal name for the this configuration setup
                   5357:       description  - text to display to operator that describes this config
                   5358:       CODElocation - if 0 or the string 'none'
                   5359:                           - no CODE exists for this config
                   5360:                      if -1 || the string 'letter'
                   5361:                           - a CODE exists for this config and is
                   5362:                             a string of letters
                   5363:                      Unsupported value (but planned for future support)
                   5364:                           if a positive integer
                   5365:                                - The CODE exists as the first n items from
                   5366:                                  the question section of the form
                   5367:                           if the string 'number'
                   5368:                                - The CODE exists for this config and is
                   5369:                                  a string of numbers
                   5370:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5371:                      the CODE starts
                   5372:       CODElength  - length of the CODE
1.573     bisitz   5373:       IDstart     - column where the student/employee ID starts
1.556     weissno  5374:       IDlength    - length of the student/employee ID info
1.423     albertel 5375:       Qstart      - column where the information from the bubbled
                   5376:                     'questions' start
                   5377:       Qlength     - number of columns comprising a single bubble line from
                   5378:                     the sheet. (usually either 1 or 10)
1.424     albertel 5379:       Qon         - either a single character representing the character used
1.423     albertel 5380:                     to signal a bubble was chosen in the positional setup, or
                   5381:                     the string 'letter' if the letter of the chosen bubble is
                   5382:                     in the final, or 'number' if a number representing the
                   5383:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5384:       Qoff        - the character used to represent that a bubble was
                   5385:                     left blank
1.423     albertel 5386:       PaperID     - if the scanning process generates a unique number for each
                   5387:                     sheet scanned the column that this ID number starts in
                   5388:       PaperIDlength - number of columns that comprise the unique ID number
                   5389:                       for the sheet of paper
1.424     albertel 5390:       FirstName   - column that the first name starts in
1.423     albertel 5391:       FirstNameLength - number of columns that the first name spans
                   5392:  
                   5393:       LastName    - column that the last name starts in
                   5394:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5395:       BubblesPerRow - number of bubbles available in each row used to 
                   5396:                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5397: =cut
1.422     foxr     5398: 
1.82      albertel 5399: sub get_scantron_config {
                   5400:     my ($which) = @_;
1.518     raeburn  5401:     my @lines = &get_scantronformat_file();
1.82      albertel 5402:     my %config;
1.157     albertel 5403:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5404:     foreach my $line (@lines) {
1.82      albertel 5405: 	my ($name,$descrip)=split(/:/,$line);
                   5406: 	if ($name ne $which ) { next; }
                   5407: 	chomp($line);
                   5408: 	my @config=split(/:/,$line);
                   5409: 	$config{'name'}=$config[0];
                   5410: 	$config{'description'}=$config[1];
                   5411: 	$config{'CODElocation'}=$config[2];
                   5412: 	$config{'CODEstart'}=$config[3];
                   5413: 	$config{'CODElength'}=$config[4];
                   5414: 	$config{'IDstart'}=$config[5];
                   5415: 	$config{'IDlength'}=$config[6];
                   5416: 	$config{'Qstart'}=$config[7];
1.497     foxr     5417:  	$config{'Qlength'}=$config[8];
1.82      albertel 5418: 	$config{'Qoff'}=$config[9];
                   5419: 	$config{'Qon'}=$config[10];
1.157     albertel 5420: 	$config{'PaperID'}=$config[11];
                   5421: 	$config{'PaperIDlength'}=$config[12];
                   5422: 	$config{'FirstName'}=$config[13];
                   5423: 	$config{'FirstNamelength'}=$config[14];
                   5424: 	$config{'LastName'}=$config[15];
                   5425: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5426:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5427: 	last;
                   5428:     }
                   5429:     return %config;
                   5430: }
                   5431: 
1.423     albertel 5432: =pod 
                   5433: 
                   5434: =item username_to_idmap
                   5435: 
1.556     weissno  5436:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5437:     student username:domain.
                   5438: 
                   5439:   Arguments:
                   5440: 
                   5441:     $classlist - reference to the class list hash. This is a hash
                   5442:                  keyed by student name:domain  whose elements are references
1.424     albertel 5443:                  to arrays containing various chunks of information
1.423     albertel 5444:                  about the student. (See loncoursedata for more info).
                   5445: 
                   5446:   Returns
                   5447:     %idmap - the constructed hash
                   5448: 
                   5449: =cut
                   5450: 
1.82      albertel 5451: sub username_to_idmap {
                   5452:     my ($classlist)= @_;
                   5453:     my %idmap;
                   5454:     foreach my $student (keys(%$classlist)) {
                   5455: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5456: 	    $student;
                   5457:     }
                   5458:     return %idmap;
                   5459: }
1.423     albertel 5460: 
                   5461: =pod
                   5462: 
1.424     albertel 5463: =item scantron_fixup_scanline
1.423     albertel 5464: 
                   5465:    Process a requested correction to a scanline.
                   5466: 
                   5467:   Arguments:
                   5468:     $scantron_config   - hash from &get_scantron_config()
                   5469:     $scan_data         - hash of correction information 
                   5470:                           (see &scantron_getfile())
                   5471:     $line              - existing scanline
                   5472:     $whichline         - line number of the passed in scanline
                   5473:     $field             - type of change to process 
                   5474:                          (either 
1.573     bisitz   5475:                           'ID'     -> correct the student/employee ID
1.423     albertel 5476:                           'CODE'   -> correct the CODE
                   5477:                           'answer' -> fixup the submitted answers)
                   5478:     
                   5479:    $args               - hash of additional info,
                   5480:                           - 'ID' 
                   5481:                                'newid' -> studentID to use in replacement
1.424     albertel 5482:                                           of existing one
1.423     albertel 5483:                           - 'CODE' 
                   5484:                                'CODE_ignore_dup' - set to true if duplicates
                   5485:                                                    should be ignored.
                   5486: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5487:                                         if the existing unfound code should
1.423     albertel 5488:                                         be used as is
                   5489:                           - 'answer'
                   5490:                                'response' - new answer or 'none' if blank
                   5491:                                'question' - the bubble line to change
1.503     raeburn  5492:                                'questionnum' - the question identifier,
                   5493:                                                may include subquestion. 
1.423     albertel 5494: 
                   5495:   Returns:
                   5496:     $line - the modified scanline
                   5497: 
                   5498:   Side effects: 
                   5499:     $scan_data - may be updated
                   5500: 
                   5501: =cut
                   5502: 
1.82      albertel 5503: 
1.157     albertel 5504: sub scantron_fixup_scanline {
                   5505:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5506:     if ($field eq 'ID') {
                   5507: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5508: 	    return ($line,1,'New value too large');
1.157     albertel 5509: 	}
                   5510: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5511: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5512: 				     $args->{'newid'});
                   5513: 	}
                   5514: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5515: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5516: 	if ($args->{'newid'}=~/^\s*$/) {
                   5517: 	    &scan_data($scan_data,"$whichline.user",
                   5518: 		       $args->{'username'}.':'.$args->{'domain'});
                   5519: 	}
1.186     albertel 5520:     } elsif ($field eq 'CODE') {
1.192     albertel 5521: 	if ($args->{'CODE_ignore_dup'}) {
                   5522: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5523: 	}
                   5524: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5525: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5526: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5527: 		return ($line,1,'New CODE value too large');
                   5528: 	    }
                   5529: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5530: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5531: 	    }
                   5532: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5533: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5534: 	}
1.157     albertel 5535:     } elsif ($field eq 'answer') {
1.497     foxr     5536: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5537: 	my $off=$scantron_config->{'Qoff'};
                   5538: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5539: 	my $answer=${off}x$length;
                   5540: 	if ($args->{'response'} eq 'none') {
                   5541: 	    &scan_data($scan_data,
1.503     raeburn  5542: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5543: 	} else {
                   5544: 	    if ($on eq 'letter') {
                   5545: 		my @alphabet=('A'..'Z');
                   5546: 		$answer=$alphabet[$args->{'response'}];
                   5547: 	    } elsif ($on eq 'number') {
                   5548: 		$answer=$args->{'response'}+1;
                   5549: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5550: 	    } else {
1.497     foxr     5551: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5552: 	    }
1.497     foxr     5553: 	    &scan_data($scan_data,
1.503     raeburn  5554: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5555: 	}
1.497     foxr     5556: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5557: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5558:     }
                   5559:     return $line;
                   5560: }
1.423     albertel 5561: 
                   5562: =pod
                   5563: 
                   5564: =item scan_data
                   5565: 
                   5566:     Edit or look up  an item in the scan_data hash.
                   5567: 
                   5568:   Arguments:
                   5569:     $scan_data  - The hash (see scantron_getfile)
                   5570:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5571:                   scantronfilename_key).
1.423     albertel 5572:     $data        - New value of the hash entry.
                   5573:     $delete      - If true, the entry is removed from the hash.
                   5574: 
                   5575:   Returns:
                   5576:     The new value of the hash table field (undefined if deleted).
                   5577: 
                   5578: =cut
                   5579: 
                   5580: 
1.157     albertel 5581: sub scan_data {
                   5582:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5583:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5584:     if (defined($value)) {
                   5585: 	$scan_data->{$filename.'_'.$key} = $value;
                   5586:     }
                   5587:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5588:     return $scan_data->{$filename.'_'.$key};
                   5589: }
1.423     albertel 5590: 
1.495     albertel 5591: # ----- These first few routines are general use routines.----
                   5592: 
                   5593: # Return the number of occurences of a pattern in a string.
                   5594: 
                   5595: sub occurence_count {
                   5596:     my ($string, $pattern) = @_;
                   5597: 
                   5598:     my @matches = ($string =~ /$pattern/g);
                   5599: 
                   5600:     return scalar(@matches);
                   5601: }
                   5602: 
                   5603: 
                   5604: # Take a string known to have digits and convert all the
                   5605: # digits into letters in the range J,A..I.
                   5606: 
                   5607: sub digits_to_letters {
                   5608:     my ($input) = @_;
                   5609: 
                   5610:     my @alphabet = ('J', 'A'..'I');
                   5611: 
                   5612:     my @input    = split(//, $input);
                   5613:     my $output ='';
                   5614:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5615: 	if ($input[$i] =~ /\d/) {
                   5616: 	    $output .= $alphabet[$input[$i]];
                   5617: 	} else {
                   5618: 	    $output .= $input[$i];
                   5619: 	}
                   5620:     }
                   5621:     return $output;
                   5622: }
                   5623: 
1.423     albertel 5624: =pod 
                   5625: 
                   5626: =item scantron_parse_scanline
                   5627: 
                   5628:   Decodes a scanline from the selected scantron file
                   5629: 
                   5630:  Arguments:
                   5631:     line             - The text of the scantron file line to process
                   5632:     whichline        - Line number
                   5633:     scantron_config  - Hash describing the format of the scantron lines.
                   5634:     scan_data        - Hash of extra information about the scanline
                   5635:                        (see scantron_getfile for more information)
                   5636:     just_header      - True if should not process question answers but only
                   5637:                        the stuff to the left of the answers.
                   5638:  Returns:
                   5639:    Hash containing the result of parsing the scanline
                   5640: 
                   5641:    Keys are all proceeded by the string 'scantron.'
                   5642: 
                   5643:        CODE    - the CODE in use for this scanline
                   5644:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5645:                  by the operator
                   5646:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5647:                             CODEs were selected, but the usage has been
                   5648:                             forced by the operator
1.556     weissno  5649:        ID  - student/employee ID
1.423     albertel 5650:        PaperID - if used, the ID number printed on the sheet when the 
                   5651:                  paper was scanned
                   5652:        FirstName - first name from the sheet
                   5653:        LastName  - last name from the sheet
                   5654: 
                   5655:      if just_header was not true these key may also exist
                   5656: 
1.447     foxr     5657:        missingerror - a list of bubble ranges that are considered to be answers
                   5658:                       to a single question that don't have any bubbles filled in.
                   5659:                       Of the form questionnumber:firstbubblenumber:count.
                   5660:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5661:                       to a single question that have more than one bubble filled in.
                   5662:                       Of the form questionnumber::firstbubblenumber:count
                   5663:    
                   5664:                 In the above, count is the number of bubble responses in the
                   5665:                 input line needed to represent the possible answers to the question.
                   5666:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5667:                 per line would have count = 2.
                   5668: 
1.423     albertel 5669:        maxquest     - the number of the last bubble line that was parsed
                   5670: 
                   5671:        (<number> starts at 1)
                   5672:        <number>.answer - zero or more letters representing the selected
                   5673:                          letters from the scanline for the bubble line 
                   5674:                          <number>.
                   5675:                          if blank there was either no bubble or there where
                   5676:                          multiple bubbles, (consult the keys missingerror and
                   5677:                          doubleerror if this is an error condition)
                   5678: 
                   5679: =cut
                   5680: 
1.82      albertel 5681: sub scantron_parse_scanline {
1.423     albertel 5682:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5683: 
1.82      albertel 5684:     my %record;
1.550     raeburn  5685:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5686:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5687:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5688:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5689: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5690: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5691: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5692: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5693: 	    $record{'scantron.CODE'}=substr($data,
                   5694: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5695: 					    $$scantron_config{'CODElength'});
1.191     albertel 5696: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5697: 		$record{'scantron.useCODE'}=1;
                   5698: 	    }
1.192     albertel 5699: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5700: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5701: 	    }
1.82      albertel 5702: 	} else {
                   5703: 	    #FIXME interpret first N questions
                   5704: 	}
                   5705:     }
1.83      albertel 5706:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5707: 				  $$scantron_config{'IDlength'});
1.157     albertel 5708:     $record{'scantron.PaperID'}=
                   5709: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5710: 	       $$scantron_config{'PaperIDlength'});
                   5711:     $record{'scantron.FirstName'}=
                   5712: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5713: 	       $$scantron_config{'FirstNamelength'});
                   5714:     $record{'scantron.LastName'}=
                   5715: 	substr($data,$$scantron_config{'LastName'}-1,
                   5716: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5717:     if ($just_header) { return \%record; }
1.194     albertel 5718: 
1.82      albertel 5719:     my @alphabet=('A'..'Z');
                   5720:     my $questnum=0;
1.447     foxr     5721:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5722: 
1.470     foxr     5723:     chomp($questions);		# Get rid of any trailing \n.
                   5724:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5725:     while (length($questions)) {
1.447     foxr     5726: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5727:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5728:                              || 1;
                   5729:         $questnum++;
                   5730:         my $quest_id = $questnum;
                   5731:         my $currentquest = substr($questions,0,$answer_length);
                   5732:         $questions       = substr($questions,$answer_length);
                   5733:         if (length($currentquest) < $answer_length) { next; }
                   5734: 
                   5735:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5736:             my $subquestnum = 1;
                   5737:             my $subquestions = $currentquest;
                   5738:             my @subanswers_needed = 
                   5739:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5740:             foreach my $subans (@subanswers_needed) {
                   5741:                 my $subans_length =
                   5742:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5743:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5744:                 $subquestions   = substr($subquestions,$subans_length);
                   5745:                 $quest_id = "$questnum.$subquestnum";
                   5746:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5747:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5748:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5749:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5750:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5751:                 } else {
                   5752:                     $ansnum = &scantron_validator_positional($ansnum,
                   5753:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5754:                 }
                   5755:                 $subquestnum ++;
                   5756:             }
                   5757:         } else {
                   5758:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5759:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5760:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5761:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5762:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5763:             } else {
                   5764:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5765:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5766:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5767:             }
                   5768:         }
                   5769:     }
                   5770:     $record{'scantron.maxquest'}=$questnum;
                   5771:     return \%record;
                   5772: }
1.447     foxr     5773: 
1.503     raeburn  5774: sub scantron_validator_lettnum {
                   5775:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5776:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5777: 
                   5778:     # Qon 'letter' implies for each slot in currquest we have:
                   5779:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5780:     #    about anything else (esp. a value of Qoff) for missing
                   5781:     #    bubbles.
                   5782:     #
                   5783:     # Qon 'number' implies each slot gives a digit that indexes the
                   5784:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5785:     #    and * or ? for double bubbles on a single line.
                   5786:     #
1.447     foxr     5787: 
1.503     raeburn  5788:     my $matchon;
                   5789:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5790:         $matchon = '[A-Z]';
                   5791:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5792:         $matchon = '\d';
                   5793:     }
                   5794:     my $occurrences = 0;
                   5795:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5796:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5797:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5798:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5799:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5800:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5801:         my @singlelines = split('',$currquest);
                   5802:         foreach my $entry (@singlelines) {
                   5803:             $occurrences = &occurence_count($entry,$matchon);
                   5804:             if ($occurrences > 1) {
                   5805:                 last;
                   5806:             }
                   5807:         } 
                   5808:     } else {
                   5809:         $occurrences = &occurence_count($currquest,$matchon); 
                   5810:     }
                   5811:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5812:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5813:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5814:             my $bubble = substr($currquest,$ans,1);
                   5815:             if ($bubble =~ /$matchon/ ) {
                   5816:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5817:                     if ($bubble == 0) {
                   5818:                         $bubble = 10; 
                   5819:                     }
                   5820:                     $record->{"scantron.$ansnum.answer"} = 
                   5821:                         $alphabet->[$bubble-1];
                   5822:                 } else {
                   5823:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5824:                 }
                   5825:             } else {
                   5826:                 $record->{"scantron.$ansnum.answer"}='';
                   5827:             }
                   5828:             $ansnum++;
                   5829:         }
                   5830:     } elsif (!defined($currquest)
                   5831:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5832:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5833:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5834:             $record->{"scantron.$ansnum.answer"}='';
                   5835:             $ansnum++;
                   5836:         }
                   5837:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5838:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5839:         }
                   5840:     } else {
                   5841:         if ($$scantron_config{'Qon'} eq 'number') {
                   5842:             $currquest = &digits_to_letters($currquest);            
                   5843:         }
                   5844:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5845:             my $bubble = substr($currquest,$ans,1);
                   5846:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5847:             $ansnum++;
                   5848:         }
                   5849:     }
                   5850:     return $ansnum;
                   5851: }
1.447     foxr     5852: 
1.503     raeburn  5853: sub scantron_validator_positional {
                   5854:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5855:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5856: 
1.503     raeburn  5857:     # Otherwise there's a positional notation;
                   5858:     # each bubble line requires Qlength items, and there are filled in
                   5859:     # bubbles for each case where there 'Qon' characters.
                   5860:     #
1.447     foxr     5861: 
1.503     raeburn  5862:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5863: 
1.503     raeburn  5864:     # If the split only gives us one element.. the full length of the
                   5865:     # answer string, no bubbles are filled in:
1.447     foxr     5866: 
1.507     raeburn  5867:     if ($answers_needed eq '') {
                   5868:         return;
                   5869:     }
                   5870: 
1.503     raeburn  5871:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5872:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5873:             $record->{"scantron.$ansnum.answer"}='';
                   5874:             $ansnum++;
                   5875:         }
                   5876:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5877:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5878:         }
                   5879:     } elsif (scalar(@array) == 2) {
                   5880:         my $location = length($array[0]);
                   5881:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5882:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5883:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5884:             if ($ans eq $line_num) {
                   5885:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5886:             } else {
                   5887:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5888:             }
                   5889:             $ansnum++;
                   5890:          }
                   5891:     } else {
                   5892:         #  If there's more than one instance of a bubble character
                   5893:         #  That's a double bubble; with positional notation we can
                   5894:         #  record all the bubbles filled in as well as the
                   5895:         #  fact this response consists of multiple bubbles.
                   5896:         #
                   5897:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5898:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5899:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5900:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5901:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5902:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5903:             my $doubleerror = 0;
                   5904:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5905:                    (!$doubleerror)) {
                   5906:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5907:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5908:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5909:                if (length(@currarray) > 2) {
                   5910:                    $doubleerror = 1;
                   5911:                } 
                   5912:             }
                   5913:             if ($doubleerror) {
                   5914:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5915:             }
                   5916:         } else {
                   5917:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5918:         }
                   5919:         my $item = $ansnum;
                   5920:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5921:             $record->{"scantron.$item.answer"} = '';
                   5922:             $item ++;
                   5923:         }
1.447     foxr     5924: 
1.503     raeburn  5925:         my @ans=@array;
                   5926:         my $i=0;
                   5927:         my $increment = 0;
                   5928:         while ($#ans) {
                   5929:             $i+=length($ans[0]) + $increment;
                   5930:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5931:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5932:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5933:             shift(@ans);
                   5934:             $increment = 1;
                   5935:         }
                   5936:         $ansnum += $answers_needed;
1.82      albertel 5937:     }
1.503     raeburn  5938:     return $ansnum;
1.82      albertel 5939: }
                   5940: 
1.423     albertel 5941: =pod
                   5942: 
                   5943: =item scantron_add_delay
                   5944: 
                   5945:    Adds an error message that occurred during the grading phase to a
                   5946:    queue of messages to be shown after grading pass is complete
                   5947: 
                   5948:  Arguments:
1.424     albertel 5949:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5950:    $scanline    - the scanline that caused the error
                   5951:    $errormesage - the error message
                   5952:    $errorcode   - a numeric code for the error
                   5953: 
                   5954:  Side Effects:
1.424     albertel 5955:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5956: 
                   5957: =cut
                   5958: 
1.82      albertel 5959: sub scantron_add_delay {
1.140     albertel 5960:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5961:     push(@$delayqueue,
                   5962: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5963: 	  'ecode' => $errorcode }
                   5964: 	 );
1.82      albertel 5965: }
                   5966: 
1.423     albertel 5967: =pod
                   5968: 
                   5969: =item scantron_find_student
                   5970: 
1.424     albertel 5971:    Finds the username for the current scanline
                   5972: 
                   5973:   Arguments:
                   5974:    $scantron_record - hash result from scantron_parse_scanline
                   5975:    $scan_data       - hash of correction information 
                   5976:                       (see &scantron_getfile() form more information)
                   5977:    $idmap           - hash from &username_to_idmap()
                   5978:    $line            - number of current scanline
                   5979:  
                   5980:   Returns:
                   5981:    Either 'username:domain' or undef if unknown
                   5982: 
1.423     albertel 5983: =cut
                   5984: 
1.82      albertel 5985: sub scantron_find_student {
1.157     albertel 5986:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5987:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5988:     if ($scanID =~ /^\s*$/) {
                   5989:  	return &scan_data($scan_data,"$line.user");
                   5990:     }
1.83      albertel 5991:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5992:  	if (lc($id) eq lc($scanID)) {
                   5993:  	    return $$idmap{$id};
                   5994:  	}
1.83      albertel 5995:     }
                   5996:     return undef;
                   5997: }
                   5998: 
1.423     albertel 5999: =pod
                   6000: 
                   6001: =item scantron_filter
                   6002: 
1.424     albertel 6003:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6004:    hidden resources was selected
                   6005: 
1.423     albertel 6006: =cut
                   6007: 
1.83      albertel 6008: sub scantron_filter {
                   6009:     my ($curres)=@_;
1.331     albertel 6010: 
                   6011:     if (ref($curres) && $curres->is_problem()) {
                   6012: 	# if the user has asked to not have either hidden
                   6013: 	# or 'randomout' controlled resources to be graded
                   6014: 	# don't include them
                   6015: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6016: 	    && $curres->randomout) {
                   6017: 	    return 0;
                   6018: 	}
1.83      albertel 6019: 	return 1;
                   6020:     }
                   6021:     return 0;
1.82      albertel 6022: }
                   6023: 
1.423     albertel 6024: =pod
                   6025: 
                   6026: =item scantron_process_corrections
                   6027: 
1.424     albertel 6028:    Gets correction information out of submitted form data and corrects
                   6029:    the scanline
                   6030: 
1.423     albertel 6031: =cut
                   6032: 
1.157     albertel 6033: sub scantron_process_corrections {
                   6034:     my ($r) = @_;
1.257     albertel 6035:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6036:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6037:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6038:     my $which=$env{'form.scantron_line'};
1.200     albertel 6039:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6040:     my ($skip,$err,$errmsg);
1.257     albertel 6041:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6042: 	$skip=1;
1.257     albertel 6043:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6044: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6045: 	    $env{'form.scantron_domain'};
1.157     albertel 6046: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6047: 	($line,$err,$errmsg)=
                   6048: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6049: 				     'ID',{'newid'=>$newid,
1.257     albertel 6050: 				    'username'=>$env{'form.scantron_username'},
                   6051: 				    'domain'=>$env{'form.scantron_domain'}});
                   6052:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6053: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6054: 	my $newCODE;
1.192     albertel 6055: 	my %args;
1.190     albertel 6056: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6057: 	    $newCODE='use_unfound';
1.190     albertel 6058: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6059: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6060: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6061: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6062: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6063: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6064: 	}
1.257     albertel 6065: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6066: 	    $args{'CODE_ignore_dup'}=1;
                   6067: 	}
                   6068: 	$args{'CODE'}=$newCODE;
1.186     albertel 6069: 	($line,$err,$errmsg)=
                   6070: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6071: 				     'CODE',\%args);
1.257     albertel 6072:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6073: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6074: 	    ($line,$err,$errmsg)=
                   6075: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6076: 					 $which,'answer',
                   6077: 					 { 'question'=>$question,
1.503     raeburn  6078: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6079:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6080: 	    if ($err) { last; }
                   6081: 	}
                   6082:     }
                   6083:     if ($err) {
1.398     albertel 6084: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6085:     } else {
1.200     albertel 6086: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6087: 	&scantron_putfile($scanlines,$scan_data);
                   6088:     }
                   6089: }
                   6090: 
1.423     albertel 6091: =pod
                   6092: 
                   6093: =item reset_skipping_status
                   6094: 
1.424     albertel 6095:    Forgets the current set of remember skipped scanlines (and thus
                   6096:    reverts back to considering all lines in the
                   6097:    scantron_skipped_<filename> file)
                   6098: 
1.423     albertel 6099: =cut
                   6100: 
1.200     albertel 6101: sub reset_skipping_status {
                   6102:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6103:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6104:     &scantron_putfile(undef,$scan_data);
                   6105: }
                   6106: 
1.423     albertel 6107: =pod
                   6108: 
                   6109: =item start_skipping
                   6110: 
1.424     albertel 6111:    Marks a scanline to be skipped. 
                   6112: 
1.423     albertel 6113: =cut
                   6114: 
1.376     albertel 6115: sub start_skipping {
1.200     albertel 6116:     my ($scan_data,$i)=@_;
                   6117:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6118:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6119: 	$remembered{$i}=2;
                   6120:     } else {
                   6121: 	$remembered{$i}=1;
                   6122:     }
1.200     albertel 6123:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6124: }
                   6125: 
1.423     albertel 6126: =pod
                   6127: 
                   6128: =item should_be_skipped
                   6129: 
1.424     albertel 6130:    Checks whether a scanline should be skipped.
                   6131: 
1.423     albertel 6132: =cut
                   6133: 
1.200     albertel 6134: sub should_be_skipped {
1.376     albertel 6135:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6136:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6137: 	# not redoing old skips
1.376     albertel 6138: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6139: 	return 0;
                   6140:     }
                   6141:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6142: 
                   6143:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6144: 	return 0;
                   6145:     }
1.200     albertel 6146:     return 1;
                   6147: }
                   6148: 
1.423     albertel 6149: =pod
                   6150: 
                   6151: =item remember_current_skipped
                   6152: 
1.424     albertel 6153:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6154:    file and remembers them into scan_data for later use.
                   6155: 
1.423     albertel 6156: =cut
                   6157: 
1.200     albertel 6158: sub remember_current_skipped {
                   6159:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6160:     my %to_remember;
                   6161:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6162: 	if ($scanlines->{'skipped'}[$i]) {
                   6163: 	    $to_remember{$i}=1;
                   6164: 	}
                   6165:     }
1.376     albertel 6166: 
1.200     albertel 6167:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6168:     &scantron_putfile(undef,$scan_data);
                   6169: }
                   6170: 
1.423     albertel 6171: =pod
                   6172: 
                   6173: =item check_for_error
                   6174: 
1.424     albertel 6175:     Checks if there was an error when attempting to remove a specific
                   6176:     scantron_.. bubble sheet data file. Prints out an error if
                   6177:     something went wrong.
                   6178: 
1.423     albertel 6179: =cut
                   6180: 
1.200     albertel 6181: sub check_for_error {
                   6182:     my ($r,$result)=@_;
                   6183:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6184: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6185:     }
                   6186: }
1.157     albertel 6187: 
1.423     albertel 6188: =pod
                   6189: 
                   6190: =item scantron_warning_screen
                   6191: 
1.424     albertel 6192:    Interstitial screen to make sure the operator has selected the
                   6193:    correct options before we start the validation phase.
                   6194: 
1.423     albertel 6195: =cut
                   6196: 
1.203     albertel 6197: sub scantron_warning_screen {
1.650     raeburn  6198:     my ($button_text,$symb)=@_;
1.257     albertel 6199:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6200:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6201:     my $CODElist;
1.284     albertel 6202:     if ($scantron_config{'CODElocation'} &&
                   6203: 	$scantron_config{'CODEstart'} &&
                   6204: 	$scantron_config{'CODElength'}) {
                   6205: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6206: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6207: 	$CODElist=
1.492     albertel 6208: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6209: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6210:     }
1.492     albertel 6211:     return ('
1.203     albertel 6212: <p>
1.492     albertel 6213: <span class="LC_warning">
                   6214: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6215: </p>
                   6216: <table>
1.492     albertel 6217: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6218: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6219: '.$CODElist.'
1.203     albertel 6220: </table>
1.650     raeburn  6221: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6222: '.&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 6223: 
                   6224: <br />
1.492     albertel 6225: ');
1.203     albertel 6226: }
                   6227: 
1.423     albertel 6228: =pod
                   6229: 
                   6230: =item scantron_do_warning
                   6231: 
1.424     albertel 6232:    Check if the operator has picked something for all required
                   6233:    fields. Error out if something is missing.
                   6234: 
1.423     albertel 6235: =cut
                   6236: 
1.203     albertel 6237: sub scantron_do_warning {
1.608     www      6238:     my ($r,$symb)=@_;
1.203     albertel 6239:     if (!$symb) {return '';}
1.324     albertel 6240:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6241:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6242:     if ( $env{'form.selectpage'} eq '' ||
                   6243: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6244: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6245: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6246: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6247: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6248: 	} 
1.257     albertel 6249: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6250: 	    $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 6251: 	} 
1.257     albertel 6252: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6253: 	    $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 6254: 	} 
                   6255:     } else {
1.650     raeburn  6256: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.492     albertel 6257: 	$r->print('
                   6258: '.$warning.'
                   6259: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6260: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6261: ');
1.237     albertel 6262:     }
1.614     www      6263:     $r->print("</form><br />");
1.203     albertel 6264:     return '';
                   6265: }
                   6266: 
1.423     albertel 6267: =pod
                   6268: 
                   6269: =item scantron_form_start
                   6270: 
1.424     albertel 6271:     html hidden input for remembering all selected grading options
                   6272: 
1.423     albertel 6273: =cut
                   6274: 
1.203     albertel 6275: sub scantron_form_start {
                   6276:     my ($max_bubble)=@_;
                   6277:     my $result= <<SCANTRONFORM;
                   6278: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6279:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6280:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6281:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6282:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6283:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6284:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6285:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6286:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6287:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6288: SCANTRONFORM
1.447     foxr     6289: 
                   6290:   my $line = 0;
                   6291:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6292:        my $chunk =
                   6293: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6294:        $chunk .=
                   6295: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6296:        $chunk .= 
                   6297:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6298:        $chunk .=
                   6299:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6300:        $result .= $chunk;
                   6301:        $line++;
                   6302:    }
1.203     albertel 6303:     return $result;
                   6304: }
                   6305: 
1.423     albertel 6306: =pod
                   6307: 
                   6308: =item scantron_validate_file
                   6309: 
1.424     albertel 6310:     Dispatch routine for doing validation of a bubble sheet data file.
                   6311: 
                   6312:     Also processes any necessary information resets that need to
                   6313:     occur before validation begins (ignore previous corrections,
                   6314:     restarting the skipped records processing)
                   6315: 
1.423     albertel 6316: =cut
                   6317: 
1.157     albertel 6318: sub scantron_validate_file {
1.608     www      6319:     my ($r,$symb) = @_;
1.157     albertel 6320:     if (!$symb) {return '';}
1.324     albertel 6321:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6322:     
                   6323:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6324:     # them when doing the corrections reset
1.257     albertel 6325:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6326: 	&reset_skipping_status();
                   6327:     }
1.257     albertel 6328:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6329: 	&remember_current_skipped();
1.257     albertel 6330: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6331:     }
                   6332: 
1.257     albertel 6333:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6334: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6335: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6336: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6337: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6338:     }
1.200     albertel 6339: 
1.257     albertel 6340:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6341: 	&scantron_process_corrections($r);
                   6342:     }
1.503     raeburn  6343:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6344:     #get the student pick code ready
                   6345:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6346:     my $nav_error;
1.649     raeburn  6347:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6348:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6349:     if ($nav_error) {
                   6350:         $r->print(&navmap_errormsg());
                   6351:         return '';
                   6352:     }
1.203     albertel 6353:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6354:     $r->print($result);
                   6355:     
1.334     albertel 6356:     my @validate_phases=( 'sequence',
                   6357: 			  'ID',
1.157     albertel 6358: 			  'CODE',
                   6359: 			  'doublebubble',
                   6360: 			  'missingbubbles');
1.257     albertel 6361:     if (!$env{'form.validatepass'}) {
                   6362: 	$env{'form.validatepass'} = 0;
1.157     albertel 6363:     }
1.257     albertel 6364:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6365: 
1.448     foxr     6366: 
1.157     albertel 6367:     my $stop=0;
                   6368:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6369: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6370: 	$r->rflush();
                   6371: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6372: 	{
                   6373: 	    no strict 'refs';
                   6374: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6375: 	}
                   6376:     }
                   6377:     if (!$stop) {
1.650     raeburn  6378: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6379: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6380:                   $warning.
                   6381:                   &mt('Perform verification for each student after storage of submissions?').
                   6382:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6383:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6384:                   ('&nbsp;'x3).'<label>'.
                   6385:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6386:                   '</label></span><br />'.
                   6387:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6388:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6389:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6390:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6391:     } else {
                   6392: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6393: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6394:     }
                   6395:     if ($stop) {
1.334     albertel 6396: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6397: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6398: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6399: 
1.650     raeburn  6400: 	    $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 6401: 	} else {
1.503     raeburn  6402:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6403: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6404:             } else {
1.539     riegler  6405:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6406:             }
1.492     albertel 6407: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6408: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6409: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6410: 	}
1.157     albertel 6411:     }
1.614     www      6412:     $r->print(" </form><br />");
1.157     albertel 6413:     return '';
                   6414: }
                   6415: 
1.423     albertel 6416: 
                   6417: =pod
                   6418: 
                   6419: =item scantron_remove_file
                   6420: 
1.424     albertel 6421:    Removes the requested bubble sheet data file, makes sure that
                   6422:    scantron_original_<filename> is never removed
                   6423: 
                   6424: 
1.423     albertel 6425: =cut
                   6426: 
1.200     albertel 6427: sub scantron_remove_file {
1.192     albertel 6428:     my ($which)=@_;
1.257     albertel 6429:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6430:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6431:     my $file='scantron_';
1.200     albertel 6432:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6433: 	$file.=$which.'_';
1.192     albertel 6434:     } else {
                   6435: 	return 'refused';
                   6436:     }
1.257     albertel 6437:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6438:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6439: }
                   6440: 
1.423     albertel 6441: 
                   6442: =pod
                   6443: 
                   6444: =item scantron_remove_scan_data
                   6445: 
1.424     albertel 6446:    Removes all scan_data correction for the requested bubble sheet
                   6447:    data file.  (In the case that both the are doing skipped records we need
                   6448:    to remember the old skipped lines for the time being so that element
                   6449:    persists for a while.)
                   6450: 
1.423     albertel 6451: =cut
                   6452: 
1.200     albertel 6453: sub scantron_remove_scan_data {
1.257     albertel 6454:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6455:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6456:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6457:     my @todelete;
1.257     albertel 6458:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6459:     foreach my $key (@keys) {
                   6460: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6461: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6462: 		$key=~/remember_skipping/) {
                   6463: 		next;
                   6464: 	    }
1.192     albertel 6465: 	    push(@todelete,$key);
                   6466: 	}
                   6467:     }
1.200     albertel 6468:     my $result;
1.192     albertel 6469:     if (@todelete) {
1.491     albertel 6470: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6471: 				       \@todelete,$cdom,$cname);
                   6472:     } else {
                   6473: 	$result = 'ok';
1.192     albertel 6474:     }
                   6475:     return $result;
                   6476: }
                   6477: 
1.423     albertel 6478: 
                   6479: =pod
                   6480: 
                   6481: =item scantron_getfile
                   6482: 
1.424     albertel 6483:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6484:     the scan_data hash
                   6485:   
                   6486:   Arguments:
                   6487:     None
                   6488: 
                   6489:   Returns:
                   6490:     2 hash references
                   6491: 
                   6492:      - first one has 
                   6493:          orig      -
                   6494:          corrected -
                   6495:          skipped   -  each of which points to an array ref of the specified
                   6496:                       file broken up into individual lines
                   6497:          count     - number of scanlines
                   6498:  
                   6499:      - second is the scan_data hash possible keys are
1.425     albertel 6500:        ($number refers to scanline numbered $number and thus the key affects
                   6501:         only that scanline
                   6502:         $bubline refers to the specific bubble line element and the aspects
                   6503:         refers to that specific bubble line element)
                   6504: 
                   6505:        $number.user - username:domain to use
                   6506:        $number.CODE_ignore_dup 
                   6507:                     - ignore the duplicate CODE error 
                   6508:        $number.useCODE
                   6509:                     - use the CODE in the scanline as is
                   6510:        $number.no_bubble.$bubline
                   6511:                     - it is valid that there is no bubbled in bubble
                   6512:                       at $number $bubline
                   6513:        remember_skipping
                   6514:                     - a frozen hash containing keys of $number and values
                   6515:                       of either 
                   6516:                         1 - we are on a 'do skipped records pass' and plan
                   6517:                             on processing this line
                   6518:                         2 - we are on a 'do skipped records pass' and this
                   6519:                             scanline has been marked to skip yet again
1.424     albertel 6520: 
1.423     albertel 6521: =cut
                   6522: 
1.157     albertel 6523: sub scantron_getfile {
1.200     albertel 6524:     #FIXME really would prefer a scantron directory
1.257     albertel 6525:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6526:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6527:     my $lines;
                   6528:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6529: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6530:     my %scanlines;
                   6531:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6532:     my $temp=$scanlines{'orig'};
                   6533:     $scanlines{'count'}=$#$temp;
                   6534: 
                   6535:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6536: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6537:     if ($lines eq '-1') {
                   6538: 	$scanlines{'corrected'}=[];
                   6539:     } else {
                   6540: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6541:     }
                   6542:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6543: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6544:     if ($lines eq '-1') {
                   6545: 	$scanlines{'skipped'}=[];
                   6546:     } else {
                   6547: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6548:     }
1.175     albertel 6549:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6550:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6551:     my %scan_data = @tmp;
                   6552:     return (\%scanlines,\%scan_data);
                   6553: }
                   6554: 
1.423     albertel 6555: =pod
                   6556: 
                   6557: =item lonnet_putfile
                   6558: 
1.424     albertel 6559:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6560: 
                   6561:  Arguments:
                   6562:    $contents - data to store
                   6563:    $filename - filename to store $contents into
                   6564: 
                   6565:  Returns:
                   6566:    result value from &Apache::lonnet::finishuserfileupload
                   6567: 
1.423     albertel 6568: =cut
                   6569: 
1.157     albertel 6570: sub lonnet_putfile {
                   6571:     my ($contents,$filename)=@_;
1.257     albertel 6572:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6573:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6574:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6575:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6576: 
                   6577: }
                   6578: 
1.423     albertel 6579: =pod
                   6580: 
                   6581: =item scantron_putfile
                   6582: 
1.424     albertel 6583:     Stores the current version of the bubble sheet data files, and the
                   6584:     scan_data hash. (Does not modify the original version only the
                   6585:     corrected and skipped versions.
                   6586: 
                   6587:  Arguments:
                   6588:     $scanlines - hash ref that looks like the first return value from
                   6589:                  &scantron_getfile()
                   6590:     $scan_data - hash ref that looks like the second return value from
                   6591:                  &scantron_getfile()
                   6592: 
1.423     albertel 6593: =cut
                   6594: 
1.157     albertel 6595: sub scantron_putfile {
                   6596:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6597:     #FIXME really would prefer a scantron directory
1.257     albertel 6598:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6599:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6600:     if ($scanlines) {
                   6601: 	my $prefix='scantron_';
1.157     albertel 6602: # no need to update orig, shouldn't change
                   6603: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6604: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6605: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6606: 			$prefix.'corrected_'.
1.257     albertel 6607: 			$env{'form.scantron_selectfile'});
1.200     albertel 6608: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6609: 			$prefix.'skipped_'.
1.257     albertel 6610: 			$env{'form.scantron_selectfile'});
1.200     albertel 6611:     }
1.175     albertel 6612:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6613: }
                   6614: 
1.423     albertel 6615: =pod
                   6616: 
                   6617: =item scantron_get_line
                   6618: 
1.424     albertel 6619:    Returns the correct version of the scanline
                   6620: 
                   6621:  Arguments:
                   6622:     $scanlines - hash ref that looks like the first return value from
                   6623:                  &scantron_getfile()
                   6624:     $scan_data - hash ref that looks like the second return value from
                   6625:                  &scantron_getfile()
                   6626:     $i         - number of the requested line (starts at 0)
                   6627: 
                   6628:  Returns:
                   6629:    A scanline, (either the original or the corrected one if it
                   6630:    exists), or undef if the requested scanline should be
                   6631:    skipped. (Either because it's an skipped scanline, or it's an
                   6632:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6633:    pass.
                   6634: 
1.423     albertel 6635: =cut
                   6636: 
1.157     albertel 6637: sub scantron_get_line {
1.200     albertel 6638:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6639:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6640:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6641:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6642:     return $scanlines->{'orig'}[$i]; 
                   6643: }
                   6644: 
1.423     albertel 6645: =pod
                   6646: 
                   6647: =item scantron_todo_count
                   6648: 
1.424     albertel 6649:     Counts the number of scanlines that need processing.
                   6650: 
                   6651:  Arguments:
                   6652:     $scanlines - hash ref that looks like the first return value from
                   6653:                  &scantron_getfile()
                   6654:     $scan_data - hash ref that looks like the second return value from
                   6655:                  &scantron_getfile()
                   6656: 
                   6657:  Returns:
                   6658:     $count - number of scanlines to process
                   6659: 
1.423     albertel 6660: =cut
                   6661: 
1.200     albertel 6662: sub get_todo_count {
                   6663:     my ($scanlines,$scan_data)=@_;
                   6664:     my $count=0;
                   6665:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6666: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6667: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6668: 	$count++;
                   6669:     }
                   6670:     return $count;
                   6671: }
                   6672: 
1.423     albertel 6673: =pod
                   6674: 
                   6675: =item scantron_put_line
                   6676: 
1.424     albertel 6677:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6678:     data file.
                   6679: 
                   6680:  Arguments:
                   6681:     $scanlines - hash ref that looks like the first return value from
                   6682:                  &scantron_getfile()
                   6683:     $scan_data - hash ref that looks like the second return value from
                   6684:                  &scantron_getfile()
                   6685:     $i         - line number to update
                   6686:     $newline   - contents of the updated scanline
                   6687:     $skip      - if true make the line for skipping and update the
                   6688:                  'skipped' file
                   6689: 
1.423     albertel 6690: =cut
                   6691: 
1.157     albertel 6692: sub scantron_put_line {
1.200     albertel 6693:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6694:     if ($skip) {
                   6695: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6696: 	&start_skipping($scan_data,$i);
1.157     albertel 6697: 	return;
                   6698:     }
                   6699:     $scanlines->{'corrected'}[$i]=$newline;
                   6700: }
                   6701: 
1.423     albertel 6702: =pod
                   6703: 
                   6704: =item scantron_clear_skip
                   6705: 
1.424     albertel 6706:    Remove a line from the 'skipped' file
                   6707: 
                   6708:  Arguments:
                   6709:     $scanlines - hash ref that looks like the first return value from
                   6710:                  &scantron_getfile()
                   6711:     $scan_data - hash ref that looks like the second return value from
                   6712:                  &scantron_getfile()
                   6713:     $i         - line number to update
                   6714: 
1.423     albertel 6715: =cut
                   6716: 
1.376     albertel 6717: sub scantron_clear_skip {
                   6718:     my ($scanlines,$scan_data,$i)=@_;
                   6719:     if (exists($scanlines->{'skipped'}[$i])) {
                   6720: 	undef($scanlines->{'skipped'}[$i]);
                   6721: 	return 1;
                   6722:     }
                   6723:     return 0;
                   6724: }
                   6725: 
1.423     albertel 6726: =pod
                   6727: 
                   6728: =item scantron_filter_not_exam
                   6729: 
1.424     albertel 6730:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6731:    filter out resources that are not marked as 'exam' mode
                   6732: 
1.423     albertel 6733: =cut
                   6734: 
1.334     albertel 6735: sub scantron_filter_not_exam {
                   6736:     my ($curres)=@_;
                   6737:     
                   6738:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6739: 	# if the user has asked to not have either hidden
                   6740: 	# or 'randomout' controlled resources to be graded
                   6741: 	# don't include them
                   6742: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6743: 	    && $curres->randomout) {
                   6744: 	    return 0;
                   6745: 	}
                   6746: 	return 1;
                   6747:     }
                   6748:     return 0;
                   6749: }
                   6750: 
1.423     albertel 6751: =pod
                   6752: 
                   6753: =item scantron_validate_sequence
                   6754: 
1.424     albertel 6755:     Validates the selected sequence, checking for resource that are
                   6756:     not set to exam mode.
                   6757: 
1.423     albertel 6758: =cut
                   6759: 
1.334     albertel 6760: sub scantron_validate_sequence {
                   6761:     my ($r,$currentphase) = @_;
                   6762: 
                   6763:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6764:     unless (ref($navmap)) {
                   6765:         $r->print(&navmap_errormsg());
                   6766:         return (1,$currentphase);
                   6767:     }
1.334     albertel 6768:     my (undef,undef,$sequence)=
                   6769: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6770: 
                   6771:     my $map=$navmap->getResourceByUrl($sequence);
                   6772: 
                   6773:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6774:                                     value="ignore" />');
                   6775:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6776: 	my @resources=
                   6777: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6778: 	if (@resources) {
1.357     banghart 6779: 	    $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 6780: 	    return (1,$currentphase);
                   6781: 	}
                   6782:     }
                   6783: 
                   6784:     return (0,$currentphase+1);
                   6785: }
                   6786: 
1.423     albertel 6787: 
                   6788: 
1.157     albertel 6789: sub scantron_validate_ID {
                   6790:     my ($r,$currentphase) = @_;
                   6791:     
                   6792:     #get student info
                   6793:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6794:     my %idmap=&username_to_idmap($classlist);
                   6795: 
                   6796:     #get scantron line setup
1.257     albertel 6797:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6798:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6799: 
                   6800:     my $nav_error;
1.649     raeburn  6801:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6802:     if ($nav_error) {
                   6803:         $r->print(&navmap_errormsg());
                   6804:         return(1,$currentphase);
                   6805:     }
1.157     albertel 6806: 
                   6807:     my %found=('ids'=>{},'usernames'=>{});
                   6808:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6809: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6810: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6811: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6812: 						 $scan_data);
                   6813: 	my $id=$$scan_record{'scantron.ID'};
                   6814: 	my $found;
                   6815: 	foreach my $checkid (keys(%idmap)) {
                   6816: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6817: 	}
                   6818: 	if ($found) {
                   6819: 	    my $username=$idmap{$found};
                   6820: 	    if ($found{'ids'}{$found}) {
                   6821: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6822: 					 $line,'duplicateID',$found);
1.194     albertel 6823: 		return(1,$currentphase);
1.157     albertel 6824: 	    } elsif ($found{'usernames'}{$username}) {
                   6825: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6826: 					 $line,'duplicateID',$username);
1.194     albertel 6827: 		return(1,$currentphase);
1.157     albertel 6828: 	    }
1.186     albertel 6829: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6830: 	    $found{'ids'}{$found}++;
                   6831: 	    $found{'usernames'}{$username}++;
                   6832: 	} else {
                   6833: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6834: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6835: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6836: 		    &scantron_get_correction($r,$i,$scan_record,
                   6837: 					     \%scantron_config,
                   6838: 					     $line,'duplicateID',$username);
1.194     albertel 6839: 		    return(1,$currentphase);
1.157     albertel 6840: 		} elsif (!defined($username)) {
                   6841: 		    &scantron_get_correction($r,$i,$scan_record,
                   6842: 					     \%scantron_config,
                   6843: 					     $line,'incorrectID');
1.194     albertel 6844: 		    return(1,$currentphase);
1.157     albertel 6845: 		}
                   6846: 		$found{'usernames'}{$username}++;
                   6847: 	    } else {
                   6848: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6849: 					 $line,'incorrectID');
1.194     albertel 6850: 		return(1,$currentphase);
1.157     albertel 6851: 	    }
                   6852: 	}
                   6853:     }
                   6854: 
                   6855:     return (0,$currentphase+1);
                   6856: }
                   6857: 
1.423     albertel 6858: 
1.157     albertel 6859: sub scantron_get_correction {
                   6860:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6861: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6862: #to show both the current line and the previous one and allow skipping
                   6863: #the previous one or the current one
                   6864: 
1.333     albertel 6865:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6866: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6867: 			    " for PaperID <tt>[_1]</tt>",
                   6868: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6869:     } else {
1.492     albertel 6870: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6871: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6872: 			    $i,$line)."</p> \n");
                   6873:     }
                   6874:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6875: 			  "The name on the paper is [_2],[_3]",
                   6876: 			  $$scan_record{'scantron.ID'},
                   6877: 			  $$scan_record{'scantron.LastName'},
                   6878: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6879: 
1.157     albertel 6880:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6881:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6882:                            # Array populated for doublebubble or
                   6883:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6884:                            # to validate radio button checking   
                   6885: 
1.157     albertel 6886:     if ($error =~ /ID$/) {
1.186     albertel 6887: 	if ($error eq 'incorrectID') {
1.492     albertel 6888: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6889: 		      "</p>\n");
1.157     albertel 6890: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6891: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6892: 	}
1.242     albertel 6893: 	$r->print($message);
1.492     albertel 6894: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6895: 	$r->print("\n<ul><li> ");
                   6896: 	#FIXME it would be nice if this sent back the user ID and
                   6897: 	#could do partial userID matches
                   6898: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6899: 				       'scantron_username','scantron_domain'));
                   6900: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6901: 	$r->print("\n@".
1.257     albertel 6902: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6903: 
                   6904: 	$r->print('</li>');
1.186     albertel 6905:     } elsif ($error =~ /CODE$/) {
                   6906: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6907: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6908: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6909: 	    $r->print("<p>".&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 6910: 	}
1.492     albertel 6911: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6912: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6913: 	$r->print($message);
1.492     albertel 6914: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6915: 	$r->print("\n<br /> ");
1.194     albertel 6916: 	my $i=0;
1.273     albertel 6917: 	if ($error eq 'incorrectCODE' 
                   6918: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6919: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6920: 	    if ($closest > 0) {
                   6921: 		foreach my $testcode (@{$closest}) {
                   6922: 		    my $checked='';
1.569     bisitz   6923: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6924: 		    $r->print("
                   6925:    <label>
1.569     bisitz   6926:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6927:        ".&mt("Use the similar CODE [_1] instead.",
                   6928: 	    "<b><tt>".$testcode."</tt></b>")."
                   6929:     </label>
                   6930:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6931: 		    $r->print("\n<br />");
                   6932: 		    $i++;
                   6933: 		}
1.194     albertel 6934: 	    }
                   6935: 	}
1.273     albertel 6936: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6937: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6938: 	    $r->print("
                   6939:     <label>
1.569     bisitz   6940:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6941:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6942: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6943:     </label>");
1.273     albertel 6944: 	    $r->print("\n<br />");
                   6945: 	}
1.194     albertel 6946: 
1.597     wenzelju 6947: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6948: function change_radio(field) {
1.190     albertel 6949:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6950:     var i;
                   6951:     for (i=0;i<slct.length;i++) {
                   6952:         if (slct[i].value==field) { slct[i].checked=true; }
                   6953:     }
                   6954: }
                   6955: ENDSCRIPT
1.187     albertel 6956: 	my $href="/adm/pickcode?".
1.359     www      6957: 	   "form=".&escape("scantronupload").
                   6958: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6959: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6960: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6961: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6962: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6963: 	    $r->print("
                   6964:     <label>
                   6965:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6966:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6967: 	     "<a target='_blank' href='$href'>","</a>")."
                   6968:     </label> 
1.558     bisitz   6969:     ".&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 6970: 	    $r->print("\n<br />");
                   6971: 	}
1.492     albertel 6972: 	$r->print("
                   6973:     <label>
                   6974:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6975:        ".&mt("Use [_1] as the CODE.",
                   6976: 	     "</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 6977: 	$r->print("\n<br /><br />");
1.157     albertel 6978:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6979: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6980: 
                   6981: 	# The form field scantron_questions is acutally a list of line numbers.
                   6982: 	# represented by this form so:
                   6983: 
                   6984: 	my $line_list = &questions_to_line_list($arg);
                   6985: 
1.157     albertel 6986: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6987: 		  $line_list.'" />');
1.242     albertel 6988: 	$r->print($message);
1.492     albertel 6989: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6990: 	foreach my $question (@{$arg}) {
1.503     raeburn  6991: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6992:                                                    $scan_record, $error);
1.524     raeburn  6993:             push(@lines_to_correct,@linenums);
1.157     albertel 6994: 	}
1.503     raeburn  6995:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6996:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6997: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6998: 	$r->print($message);
1.492     albertel 6999: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7000: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7001: 
1.503     raeburn  7002: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7003: 	# a list of question numbers. Therefore:
                   7004: 	#
                   7005: 	
                   7006: 	my $line_list = &questions_to_line_list($arg);
                   7007: 
1.157     albertel 7008: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7009: 		  $line_list.'" />');
1.157     albertel 7010: 	foreach my $question (@{$arg}) {
1.503     raeburn  7011: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7012:                                                    $scan_record, $error);
1.524     raeburn  7013:             push(@lines_to_correct,@linenums);
1.157     albertel 7014: 	}
1.503     raeburn  7015:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7016:     } else {
                   7017: 	$r->print("\n<ul>");
                   7018:     }
                   7019:     $r->print("\n</li></ul>");
1.497     foxr     7020: }
                   7021: 
1.503     raeburn  7022: sub verify_bubbles_checked {
                   7023:     my (@ansnums) = @_;
                   7024:     my $ansnumstr = join('","',@ansnums);
                   7025:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7026:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7027: function verify_bubble_radio(form) {
                   7028:     var ansnumArray = new Array ("$ansnumstr");
                   7029:     var need_bubble_count = 0;
                   7030:     for (var i=0; i<ansnumArray.length; i++) {
                   7031:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7032:             var bubble_picked = 0; 
                   7033:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7034:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7035:                     bubble_picked = 1;
                   7036:                 }
                   7037:             }
                   7038:             if (bubble_picked == 0) {
                   7039:                 need_bubble_count ++;
                   7040:             }
                   7041:         }
                   7042:     }
                   7043:     if (need_bubble_count) {
                   7044:         alert("$warning");
                   7045:         return;
                   7046:     }
                   7047:     form.submit(); 
                   7048: }
                   7049: ENDSCRIPT
                   7050:     return $output;
                   7051: }
                   7052: 
1.497     foxr     7053: =pod
                   7054: 
                   7055: =item  questions_to_line_list
1.157     albertel 7056: 
1.497     foxr     7057: Converts a list of questions into a string of comma separated
                   7058: line numbers in the answer sheet used by the questions.  This is
                   7059: used to fill in the scantron_questions form field.
                   7060: 
                   7061:   Arguments:
                   7062:      questions    - Reference to an array of questions.
                   7063: 
                   7064: =cut
                   7065: 
                   7066: 
                   7067: sub questions_to_line_list {
                   7068:     my ($questions) = @_;
                   7069:     my @lines;
                   7070: 
1.503     raeburn  7071:     foreach my $item (@{$questions}) {
                   7072:         my $question = $item;
                   7073:         my ($first,$count,$last);
                   7074:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7075:             $question = $1;
                   7076:             my $subquestion = $2;
                   7077:             $first = $first_bubble_line{$question-1} + 1;
                   7078:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7079:             my $subcount = 1;
                   7080:             while ($subcount<$subquestion) {
                   7081:                 $first += $subans[$subcount-1];
                   7082:                 $subcount ++;
                   7083:             }
                   7084:             $count = $subans[$subquestion-1];
                   7085:         } else {
                   7086: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7087: 	    $count   = $bubble_lines_per_response{$question-1};
                   7088:         }
1.506     raeburn  7089:         $last = $first+$count-1;
1.503     raeburn  7090:         push(@lines, ($first..$last));
1.497     foxr     7091:     }
                   7092:     return join(',', @lines);
                   7093: }
                   7094: 
                   7095: =pod 
                   7096: 
                   7097: =item prompt_for_corrections
                   7098: 
                   7099: Prompts for a potentially multiline correction to the
                   7100: user's bubbling (factors out common code from scantron_get_correction
                   7101: for multi and missing bubble cases).
                   7102: 
                   7103:  Arguments:
                   7104:    $r           - Apache request object.
                   7105:    $question    - The question number to prompt for.
                   7106:    $scan_config - The scantron file configuration hash.
                   7107:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7108:    $error       - Type of error
1.497     foxr     7109: 
                   7110:  Implicit inputs:
                   7111:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7112:                                   Numbered from 0 (but question numbers are from
                   7113:                                   1.
                   7114:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7115:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7116:                                   type problems render as separate sub-questions, 
1.503     raeburn  7117:                                   in exam mode. This hash contains a 
                   7118:                                   comma-separated list of the lines per 
                   7119:                                   sub-question.
1.510     raeburn  7120:    %responsetype_per_response   - essayresponse, formularesponse,
                   7121:                                   stringresponse, imageresponse, reactionresponse,
                   7122:                                   and organicresponse type problem parts can have
1.503     raeburn  7123:                                   multiple lines per response if the weight
                   7124:                                   assigned exceeds 10.  In this case, only
                   7125:                                   one bubble per line is permitted, but more 
                   7126:                                   than one line might contain bubbles, e.g.
                   7127:                                   bubbling of: line 1 - J, line 2 - J, 
                   7128:                                   line 3 - B would assign 22 points.  
1.497     foxr     7129: 
                   7130: =cut
                   7131: 
                   7132: sub prompt_for_corrections {
1.503     raeburn  7133:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7134:     my ($current_line,$lines);
                   7135:     my @linenums;
                   7136:     my $questionnum = $question;
                   7137:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7138:         $question = $1;
                   7139:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7140:         my $subquestion = $2;
                   7141:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7142:         my $subcount = 1;
                   7143:         while ($subcount<$subquestion) {
                   7144:             $current_line += $subans[$subcount-1];
                   7145:             $subcount ++;
                   7146:         }
                   7147:         $lines = $subans[$subquestion-1];
                   7148:     } else {
                   7149:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7150:         $lines        = $bubble_lines_per_response{$question-1};
                   7151:     }
1.497     foxr     7152:     if ($lines > 1) {
1.503     raeburn  7153:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7154:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7155:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7156:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7157:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7158:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7159:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7160:             $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  7161:         } else {
                   7162:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7163:         }
1.497     foxr     7164:     }
                   7165:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7166:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7167: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7168: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7169:         push(@linenums,$current_line);
1.497     foxr     7170: 	$current_line++;
                   7171:     }
                   7172:     if ($lines > 1) {
                   7173: 	$r->print("<hr /><br />");
                   7174:     }
1.503     raeburn  7175:     return @linenums;
1.157     albertel 7176: }
1.423     albertel 7177: 
                   7178: =pod
                   7179: 
                   7180: =item scantron_bubble_selector
                   7181:   
                   7182:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7183:    possibly showing the existing the selected bubbles if known
1.423     albertel 7184: 
                   7185:  Arguments:
                   7186:     $r           - Apache request object
                   7187:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7188:     $line        - Number of the line being displayed.
1.503     raeburn  7189:     $questionnum - Question number (may include subquestion)
                   7190:     $error       - Type of error.
1.497     foxr     7191:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7192: 
                   7193: =cut
                   7194: 
1.157     albertel 7195: sub scantron_bubble_selector {
1.503     raeburn  7196:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7197:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7198: 
                   7199:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7200:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7201:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7202:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7203:             $max=$$scan_config{'BubblesPerRow'};
                   7204:             if (($scmode eq 'number') && ($max > 10)) {
                   7205:                 $max = 10;
                   7206:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7207:                 $max = 26;
                   7208:             }
                   7209:         } else {
                   7210:             $max = 10;
                   7211:         }
                   7212:     }
1.274     albertel 7213: 
1.157     albertel 7214:     my @alphabet=('A'..'Z');
1.503     raeburn  7215:     $r->print(&Apache::loncommon::start_data_table().
                   7216:               &Apache::loncommon::start_data_table_row());
                   7217:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7218:     for (my $i=0;$i<$max+1;$i++) {
                   7219: 	$r->print("\n".'<td align="center">');
                   7220: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7221: 	else { $r->print('&nbsp;'); }
                   7222: 	$r->print('</td>');
                   7223:     }
1.503     raeburn  7224:     $r->print(&Apache::loncommon::end_data_table_row().
                   7225:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7226:     for (my $i=0;$i<$max;$i++) {
                   7227: 	$r->print("\n".
                   7228: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7229: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7230:     }
1.503     raeburn  7231:     my $nobub_checked = ' ';
                   7232:     if ($error eq 'missingbubble') {
                   7233:         $nobub_checked = ' checked = "checked" ';
                   7234:     }
                   7235:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7236: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7237:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7238:               $line.'" value="'.$questionnum.'" /></td>');
                   7239:     $r->print(&Apache::loncommon::end_data_table_row().
                   7240:               &Apache::loncommon::end_data_table());
1.157     albertel 7241: }
                   7242: 
1.423     albertel 7243: =pod
                   7244: 
                   7245: =item num_matches
                   7246: 
1.424     albertel 7247:    Counts the number of characters that are the same between the two arguments.
                   7248: 
                   7249:  Arguments:
                   7250:    $orig - CODE from the scanline
                   7251:    $code - CODE to match against
                   7252: 
                   7253:  Returns:
                   7254:    $count - integer count of the number of same characters between the
                   7255:             two arguments
                   7256: 
1.423     albertel 7257: =cut
                   7258: 
1.194     albertel 7259: sub num_matches {
                   7260:     my ($orig,$code) = @_;
                   7261:     my @code=split(//,$code);
                   7262:     my @orig=split(//,$orig);
                   7263:     my $same=0;
                   7264:     for (my $i=0;$i<scalar(@code);$i++) {
                   7265: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7266:     }
                   7267:     return $same;
                   7268: }
                   7269: 
1.423     albertel 7270: =pod
                   7271: 
                   7272: =item scantron_get_closely_matching_CODEs
                   7273: 
1.424     albertel 7274:    Cycles through all CODEs and finds the set that has the greatest
                   7275:    number of same characters as the provided CODE
                   7276: 
                   7277:  Arguments:
                   7278:    $allcodes - hash ref returned by &get_codes()
                   7279:    $CODE     - CODE from the current scanline
                   7280: 
                   7281:  Returns:
                   7282:    2 element list
                   7283:     - first elements is number of how closely matching the best fit is 
                   7284:       (5 means best set has 5 matching characters)
                   7285:     - second element is an arrary ref containing the set of valid CODEs
                   7286:       that best fit the passed in CODE
                   7287: 
1.423     albertel 7288: =cut
                   7289: 
1.194     albertel 7290: sub scantron_get_closely_matching_CODEs {
                   7291:     my ($allcodes,$CODE)=@_;
                   7292:     my @CODEs;
                   7293:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7294: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7295:     }
                   7296: 
                   7297:     return ($#CODEs,$CODEs[-1]);
                   7298: }
                   7299: 
1.423     albertel 7300: =pod
                   7301: 
                   7302: =item get_codes
                   7303: 
1.424     albertel 7304:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7305:    set of remembered CODEs.
                   7306: 
                   7307:  Arguments:
                   7308:   $old_name - name of the set of remembered CODEs
                   7309:   $cdom     - domain of the course
                   7310:   $cnum     - internal course name
                   7311: 
                   7312:  Returns:
                   7313:   %allcodes - keys are the valid CODEs, values are all 1
                   7314: 
1.423     albertel 7315: =cut
                   7316: 
1.194     albertel 7317: sub get_codes {
1.280     foxr     7318:     my ($old_name, $cdom, $cnum) = @_;
                   7319:     if (!$old_name) {
                   7320: 	$old_name=$env{'form.scantron_CODElist'};
                   7321:     }
                   7322:     if (!$cdom) {
                   7323: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7324:     }
                   7325:     if (!$cnum) {
                   7326: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7327:     }
1.278     albertel 7328:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7329: 				    $cdom,$cnum);
                   7330:     my %allcodes;
                   7331:     if ($result{"type\0$old_name"} eq 'number') {
                   7332: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7333:     } else {
                   7334: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7335:     }
1.194     albertel 7336:     return %allcodes;
                   7337: }
                   7338: 
1.423     albertel 7339: =pod
                   7340: 
                   7341: =item scantron_validate_CODE
                   7342: 
1.424     albertel 7343:    Validates all scanlines in the selected file to not have any
                   7344:    invalid or underspecified CODEs and that none of the codes are
                   7345:    duplicated if this was requested.
                   7346: 
1.423     albertel 7347: =cut
                   7348: 
1.157     albertel 7349: sub scantron_validate_CODE {
                   7350:     my ($r,$currentphase) = @_;
1.257     albertel 7351:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7352:     if ($scantron_config{'CODElocation'} &&
                   7353: 	$scantron_config{'CODEstart'} &&
                   7354: 	$scantron_config{'CODElength'}) {
1.257     albertel 7355: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7356: 	    &FIXME_blow_up()
                   7357: 	}
                   7358:     } else {
                   7359: 	return (0,$currentphase+1);
                   7360:     }
                   7361:     
                   7362:     my %usedCODEs;
                   7363: 
1.194     albertel 7364:     my %allcodes=&get_codes();
1.186     albertel 7365: 
1.582     raeburn  7366:     my $nav_error;
1.649     raeburn  7367:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7368:     if ($nav_error) {
                   7369:         $r->print(&navmap_errormsg());
                   7370:         return(1,$currentphase);
                   7371:     }
1.447     foxr     7372: 
1.186     albertel 7373:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7374:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7375: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7376: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7377: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7378: 						 $scan_data);
                   7379: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7380: 	my $error=0;
1.224     albertel 7381: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7382: 	    &scantron_get_correction($r,$i,$scan_record,
                   7383: 				     \%scantron_config,
                   7384: 				     $line,'incorrectCODE',\%allcodes);
                   7385: 	    return(1,$currentphase);
                   7386: 	}
1.221     albertel 7387: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7388: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7389: 	    &scantron_get_correction($r,$i,$scan_record,
                   7390: 				     \%scantron_config,
1.194     albertel 7391: 				     $line,'incorrectCODE',\%allcodes);
                   7392: 	    return(1,$currentphase);
1.186     albertel 7393: 	}
1.214     albertel 7394: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7395: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7396: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7397: 	    &scantron_get_correction($r,$i,$scan_record,
                   7398: 				     \%scantron_config,
1.194     albertel 7399: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7400: 	    return(1,$currentphase);
1.186     albertel 7401: 	}
1.524     raeburn  7402: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7403:     }
1.157     albertel 7404:     return (0,$currentphase+1);
                   7405: }
                   7406: 
1.423     albertel 7407: =pod
                   7408: 
                   7409: =item scantron_validate_doublebubble
                   7410: 
1.424     albertel 7411:    Validates all scanlines in the selected file to not have any
                   7412:    bubble lines with multiple bubbles marked.
                   7413: 
1.423     albertel 7414: =cut
                   7415: 
1.157     albertel 7416: sub scantron_validate_doublebubble {
                   7417:     my ($r,$currentphase) = @_;
                   7418:     #get student info
                   7419:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7420:     my %idmap=&username_to_idmap($classlist);
                   7421: 
                   7422:     #get scantron line setup
1.257     albertel 7423:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7424:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7425:     my $nav_error;
1.649     raeburn  7426:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7427:     if ($nav_error) {
                   7428:         $r->print(&navmap_errormsg());
                   7429:         return(1,$currentphase);
                   7430:     }
1.447     foxr     7431: 
1.157     albertel 7432:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7433: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7434: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7435: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7436: 						 $scan_data);
                   7437: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7438: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7439: 				 'doublebubble',
                   7440: 				 $$scan_record{'scantron.doubleerror'});
                   7441:     	return (1,$currentphase);
                   7442:     }
                   7443:     return (0,$currentphase+1);
                   7444: }
                   7445: 
1.423     albertel 7446: 
1.503     raeburn  7447: sub scantron_get_maxbubble {
1.649     raeburn  7448:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7449:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7450: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7451: 	&restore_bubble_lines();
1.257     albertel 7452: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7453:     }
1.330     albertel 7454: 
1.447     foxr     7455:     my (undef, undef, $sequence) =
1.257     albertel 7456: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7457: 
1.447     foxr     7458:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7459:     unless (ref($navmap)) {
                   7460:         if (ref($nav_error)) {
                   7461:             $$nav_error = 1;
                   7462:         }
1.591     raeburn  7463:         return;
1.582     raeburn  7464:     }
1.191     albertel 7465:     my $map=$navmap->getResourceByUrl($sequence);
                   7466:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7467:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7468: 
                   7469:     &Apache::lonxml::clear_problem_counter();
                   7470: 
1.557     raeburn  7471:     my $uname       = $env{'user.name'};
                   7472:     my $udom        = $env{'user.domain'};
1.435     foxr     7473:     my $cid         = $env{'request.course.id'};
                   7474:     my $total_lines = 0;
                   7475:     %bubble_lines_per_response = ();
1.447     foxr     7476:     %first_bubble_line         = ();
1.503     raeburn  7477:     %subdivided_bubble_lines   = ();
                   7478:     %responsetype_per_response = ();
1.554     raeburn  7479: 
1.447     foxr     7480:     my $response_number = 0;
                   7481:     my $bubble_line     = 0;
1.191     albertel 7482:     foreach my $resource (@resources) {
1.649     raeburn  7483:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
1.542     raeburn  7484:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7485: 	    foreach my $part_id (@{$parts}) {
                   7486:                 my $lines;
                   7487: 
                   7488: 	        # TODO - make this a persistent hash not an array.
                   7489: 
                   7490:                 # optionresponse, matchresponse and rankresponse type items 
                   7491:                 # render as separate sub-questions in exam mode.
                   7492:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7493:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7494:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7495:                     my ($numbub,$numshown);
                   7496:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7497:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7498:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7499:                         }
                   7500:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7501:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7502:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7503:                         }
                   7504:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7505:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7506:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7507:                         }
                   7508:                     }
                   7509:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7510:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7511:                     }
1.649     raeburn  7512:                     my $bubbles_per_row =
                   7513:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7514:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7515:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7516:                         $inner_bubble_lines++;
                   7517:                     }
                   7518:                     for (my $i=0; $i<$numshown; $i++) {
                   7519:                         $subdivided_bubble_lines{$response_number} .= 
                   7520:                             $inner_bubble_lines.',';
                   7521:                     }
                   7522:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7523:                     $lines = $numshown * $inner_bubble_lines;
                   7524:                 } else {
                   7525:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7526:                 }
1.542     raeburn  7527: 
                   7528:                 $first_bubble_line{$response_number} = $bubble_line;
                   7529: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7530:                 $responsetype_per_response{$response_number} = 
                   7531:                     $analysis->{$part_id.'.type'};
                   7532: 	        $response_number++;
                   7533: 
                   7534: 	        $bubble_line +=  $lines;
                   7535: 	        $total_lines +=  $lines;
                   7536: 	    }
                   7537:         }
                   7538:     }
1.552     raeburn  7539:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7540: 
                   7541:     &save_bubble_lines();
                   7542:     $env{'form.scantron_maxbubble'} =
                   7543: 	$total_lines;
                   7544:     return $env{'form.scantron_maxbubble'};
                   7545: }
1.523     raeburn  7546: 
1.649     raeburn  7547: sub bubblesheet_bubbles_per_row {
                   7548:     my ($scantron_config) = @_;
                   7549:     my $bubbles_per_row;
                   7550:     if (ref($scantron_config) eq 'HASH') {
                   7551:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7552:     }
                   7553:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7554:         $bubbles_per_row = 10;
                   7555:     }
                   7556:     return $bubbles_per_row;
                   7557: }
                   7558: 
1.157     albertel 7559: sub scantron_validate_missingbubbles {
                   7560:     my ($r,$currentphase) = @_;
                   7561:     #get student info
                   7562:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7563:     my %idmap=&username_to_idmap($classlist);
                   7564: 
                   7565:     #get scantron line setup
1.257     albertel 7566:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7567:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7568:     my $nav_error;
1.649     raeburn  7569:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7570:     if ($nav_error) {
                   7571:         return(1,$currentphase);
                   7572:     }
1.157     albertel 7573:     if (!$max_bubble) { $max_bubble=2**31; }
                   7574:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7575: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7576: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7577: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7578: 						 $scan_data);
                   7579: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7580: 	my @to_correct;
1.470     foxr     7581: 	
                   7582: 	# Probably here's where the error is...
                   7583: 
1.157     albertel 7584: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7585:             my $lastbubble;
                   7586:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7587:                my $question = $1;
                   7588:                my $subquestion = $2;
                   7589:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7590:                my $first = $first_bubble_line{$question-1};
                   7591:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7592:                my $subcount = 1;
                   7593:                while ($subcount<$subquestion) {
                   7594:                    $first += $subans[$subcount-1];
                   7595:                    $subcount ++;
                   7596:                }
                   7597:                my $count = $subans[$subquestion-1];
                   7598:                $lastbubble = $first + $count;
                   7599:             } else {
                   7600:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7601:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7602:             }
                   7603:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7604: 	    push(@to_correct,$missing);
                   7605: 	}
                   7606: 	if (@to_correct) {
                   7607: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7608: 				     $line,'missingbubble',\@to_correct);
                   7609: 	    return (1,$currentphase);
                   7610: 	}
                   7611: 
                   7612:     }
                   7613:     return (0,$currentphase+1);
                   7614: }
                   7615: 
1.423     albertel 7616: 
1.82      albertel 7617: sub scantron_process_students {
1.608     www      7618:     my ($r,$symb) = @_;
1.513     foxr     7619: 
1.257     albertel 7620:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7621:     if (!$symb) {
                   7622: 	return '';
                   7623:     }
1.324     albertel 7624:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7625: 
1.257     albertel 7626:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7627:     my $bubbles_per_row =
                   7628:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7629:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7630:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7631:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7632:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7633:     unless (ref($navmap)) {
                   7634:         $r->print(&navmap_errormsg());
                   7635:         return '';
                   7636:     }  
1.83      albertel 7637:     my $map=$navmap->getResourceByUrl($sequence);
                   7638:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7639:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7640:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7641:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7642:     my $resource_error;
1.557     raeburn  7643:     foreach my $resource (@resources) {
1.586     raeburn  7644:         my $ressymb;
                   7645:         if (ref($resource)) {
                   7646:             $ressymb = $resource->symb();
                   7647:         } else {
                   7648:             $resource_error = 1;
                   7649:             last;
                   7650:         }
1.557     raeburn  7651:         my ($analysis,$parts) =
                   7652:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7653:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7654:         $grader_partids_by_symb{$ressymb} = $parts;
                   7655:         if (ref($analysis) eq 'HASH') {
                   7656:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7657:                 $grader_randomlists_by_symb{$ressymb} = 
                   7658:                     $analysis->{'parts_withrandomlist'};
                   7659:             }
                   7660:         }
                   7661:     }
1.586     raeburn  7662:     if ($resource_error) {
                   7663:         $r->print(&navmap_errormsg());
                   7664:         return '';
                   7665:     }
1.557     raeburn  7666: 
1.554     raeburn  7667:     my ($uname,$udom);
1.82      albertel 7668:     my $result= <<SCANTRONFORM;
1.81      albertel 7669: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7670:   <input type="hidden" name="command" value="scantron_configphase" />
                   7671:   $default_form_data
                   7672: SCANTRONFORM
1.82      albertel 7673:     $r->print($result);
                   7674: 
                   7675:     my @delayqueue;
1.542     raeburn  7676:     my (%completedstudents,%scandata);
1.140     albertel 7677:     
1.520     www      7678:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7679:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7680:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7681:  				    'Bubblesheet Progress',$count,
1.195     albertel 7682: 				    'inline',undef,'scantronupload');
1.140     albertel 7683:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7684: 					  'Processing first student');
1.542     raeburn  7685:     $r->print('<br />');
1.140     albertel 7686:     my $start=&Time::HiRes::time();
1.158     albertel 7687:     my $i=-1;
1.542     raeburn  7688:     my $started;
1.447     foxr     7689: 
1.582     raeburn  7690:     my $nav_error;
1.649     raeburn  7691:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7692:     if ($nav_error) {
                   7693:         $r->print(&navmap_errormsg());
                   7694:         return '';
                   7695:     }
                   7696: 
1.513     foxr     7697:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7698:     # the user and return.
                   7699: 
                   7700:     if ($ssi_error) {
                   7701: 	$r->print("</form>");
                   7702: 	&ssi_print_error($r);
1.520     www      7703:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7704: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7705:     }
1.447     foxr     7706: 
1.542     raeburn  7707:     my %lettdig = &letter_to_digits();
                   7708:     my $numletts = scalar(keys(%lettdig));
                   7709: 
1.157     albertel 7710:     while ($i<$scanlines->{'count'}) {
                   7711:  	($uname,$udom)=('','');
                   7712:  	$i++;
1.200     albertel 7713:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7714:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7715: 	if ($started) {
                   7716: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7717: 						     'last student');
                   7718: 	}
                   7719: 	$started=1;
1.157     albertel 7720:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7721:  						 $scan_data);
                   7722:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7723:  					      \%idmap,$i)) {
                   7724:   	    &scantron_add_delay(\@delayqueue,$line,
                   7725:  				'Unable to find a student that matches',1);
                   7726:  	    next;
                   7727:   	}
                   7728:  	if (exists $completedstudents{$uname}) {
                   7729:  	    &scantron_add_delay(\@delayqueue,$line,
                   7730:  				'Student '.$uname.' has multiple sheets',2);
                   7731:  	    next;
                   7732:  	}
                   7733:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7734: 
1.586     raeburn  7735:         my (%partids_by_symb,$res_error);
1.554     raeburn  7736:         foreach my $resource (@resources) {
1.586     raeburn  7737:             my $ressymb;
                   7738:             if (ref($resource)) {
                   7739:                 $ressymb = $resource->symb();
                   7740:             } else {
                   7741:                 $res_error = 1;
                   7742:                 last;
                   7743:             }
1.557     raeburn  7744:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7745:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7746:                 my ($analysis,$parts) =
1.649     raeburn  7747:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7748:                 $partids_by_symb{$ressymb} = $parts;
                   7749:             } else {
                   7750:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7751:             }
1.554     raeburn  7752:         }
                   7753: 
1.586     raeburn  7754:         if ($res_error) {
                   7755:             &scantron_add_delay(\@delayqueue,$line,
                   7756:                                 'An error occurred while grading student '.$uname,2);
                   7757:             next;
                   7758:         }
                   7759: 
1.330     albertel 7760: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7761:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7762: 
                   7763: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7764: 	    &scantron_putfile($scanlines,$scan_data);
                   7765: 	}
1.161     albertel 7766: 	
1.542     raeburn  7767:         my $scancode;
                   7768:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7769:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7770:             $scancode = $scan_record->{'scantron.CODE'};
                   7771:         } else {
                   7772:             $scancode = '';
                   7773:         }
                   7774: 
                   7775:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7776:                                    \@resources,\%partids_by_symb,
                   7777:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  7778:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7779:             $r->print("</form>");
                   7780:             &ssi_print_error($r);
                   7781:             &Apache::lonnet::remove_lock($lock);
                   7782:             return '';      # Why return ''?  Beats me.
                   7783:         }
1.513     foxr     7784: 
1.140     albertel 7785: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7786:         if ($env{'form.verifyrecord'}) {
                   7787:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7788:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7789:             chomp($studentdata);
                   7790:             $studentdata =~ s/\r$//;
                   7791:             my $studentrecord = '';
                   7792:             my $counter = -1;
                   7793:             foreach my $resource (@resources) {
1.554     raeburn  7794:                 my $ressymb = $resource->symb();
1.542     raeburn  7795:                 ($counter,my $recording) =
                   7796:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7797:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7798:                                              \%scantron_config,\%lettdig,$numletts);
                   7799:                 $studentrecord .= $recording;
                   7800:             }
                   7801:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7802:                 &Apache::lonxml::clear_problem_counter();
                   7803:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7804:                                            \@resources,\%partids_by_symb,
                   7805:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  7806:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7807:                     $r->print("</form>");
                   7808:                     &ssi_print_error($r);
                   7809:                     &Apache::lonnet::remove_lock($lock);
                   7810:                     delete($completedstudents{$uname});
                   7811:                     return '';
                   7812:                 }
1.542     raeburn  7813:                 $counter = -1;
                   7814:                 $studentrecord = '';
                   7815:                 foreach my $resource (@resources) {
1.554     raeburn  7816:                     my $ressymb = $resource->symb();
1.542     raeburn  7817:                     ($counter,my $recording) =
                   7818:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7819:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7820:                                                  \%scantron_config,\%lettdig,$numletts);
                   7821:                     $studentrecord .= $recording;
                   7822:                 }
                   7823:                 if ($studentrecord ne $studentdata) {
                   7824:                     $r->print('<p><span class="LC_error">');
                   7825:                     if ($scancode eq '') {
                   7826:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7827:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7828:                     } else {
                   7829:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7830:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7831:                     }
                   7832:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7833:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7834:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7835:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7836:                               &Apache::loncommon::start_data_table_row().
                   7837:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7838:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7839:                               &Apache::loncommon::end_data_table_row().
                   7840:                               &Apache::loncommon::start_data_table_row().
                   7841:                               '<td>Stored submissions</td>'.
                   7842:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7843:                               &Apache::loncommon::end_data_table_row().
                   7844:                               &Apache::loncommon::end_data_table().'</p>');
                   7845:                 } else {
                   7846:                     $r->print('<br /><span class="LC_warning">'.
                   7847:                              &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 />'.
                   7848:                              &mt("As a consequence, this user's submission history records two tries.").
                   7849:                                  '</span><br />');
                   7850:                 }
                   7851:             }
                   7852:         }
1.543     raeburn  7853:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7854:     } continue {
1.330     albertel 7855: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7856: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7857:     }
1.140     albertel 7858:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7859:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7860: #    my $lasttime = &Time::HiRes::time()-$start;
                   7861: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7862: 
1.200     albertel 7863:     $r->print("</form>");
1.157     albertel 7864:     return '';
1.75      albertel 7865: }
1.157     albertel 7866: 
1.557     raeburn  7867: sub graders_resources_pass {
1.649     raeburn  7868:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   7869:         $bubbles_per_row) = @_;
1.557     raeburn  7870:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7871:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7872:         foreach my $resource (@{$resources}) {
                   7873:             my $ressymb = $resource->symb();
                   7874:             my ($analysis,$parts) =
                   7875:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7876:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7877:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7878:             if (ref($analysis) eq 'HASH') {
                   7879:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7880:                     $grader_randomlists_by_symb->{$ressymb} =
                   7881:                         $analysis->{'parts_withrandomlist'};
                   7882:                 }
                   7883:             }
                   7884:         }
                   7885:     }
                   7886:     return;
                   7887: }
                   7888: 
1.542     raeburn  7889: sub grade_student_bubbles {
1.649     raeburn  7890:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   7891: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  7892:     if (ref($resources) eq 'ARRAY') {
                   7893:         my $count = 0;
                   7894:         foreach my $resource (@{$resources}) {
                   7895:             my $ressymb = $resource->symb();
                   7896:             my %form = ('submitted'      => 'scantron',
                   7897:                         'grade_target'   => 'grade',
                   7898:                         'grade_username' => $uname,
                   7899:                         'grade_domain'   => $udom,
                   7900:                         'grade_courseid' => $env{'request.course.id'},
                   7901:                         'grade_symb'     => $ressymb,
                   7902:                         'CODE'           => $scancode
                   7903:                        );
1.649     raeburn  7904:             if ($bubbles_per_row ne '') {
                   7905:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   7906:             }
1.554     raeburn  7907:             if (ref($parts) eq 'HASH') {
                   7908:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7909:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7910:                         $form{'scantron_questnum_start.'.$part} =
                   7911:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7912:                         $count++;
                   7913:                     }
                   7914:                 }
                   7915:             }
                   7916:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7917:             return 'ssi_error' if ($ssi_error);
                   7918:             last if (&Apache::loncommon::connection_aborted($r));
                   7919:         }
1.542     raeburn  7920:     }
                   7921:     return;
                   7922: }
                   7923: 
1.157     albertel 7924: sub scantron_upload_scantron_data {
1.608     www      7925:     my ($r,$symb)=@_;
1.565     raeburn  7926:     my $dom = $env{'request.role.domain'};
                   7927:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7928:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7929:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7930: 							  'domainid',
1.565     raeburn  7931: 							  'coursename',$dom);
                   7932:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7933:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7934:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7935:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7936:     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 7937:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7938:     function checkUpload(formname) {
                   7939: 	if (formname.upfile.value == "") {
1.579     raeburn  7940: 	    alert("'.$nofile_alert.'");
1.157     albertel 7941: 	    return false;
                   7942: 	}
1.565     raeburn  7943:         if (formname.courseid.value == "") {
1.579     raeburn  7944:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7945:             return false;
                   7946:         }
1.157     albertel 7947: 	formname.submit();
                   7948:     }
1.565     raeburn  7949: 
                   7950:     function ToSyllabus() {
                   7951:         var cdom = '."'$dom'".';
                   7952:         var cnum = document.rules.courseid.value;
                   7953:         if (cdom == "" || cdom == null) {
                   7954:             return;
                   7955:         }
                   7956:         if (cnum == "" || cnum == null) {
                   7957:            return;
                   7958:         }
                   7959:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7960:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7961:         return;
                   7962:     }
                   7963: 
1.597     wenzelju 7964: '));
                   7965:     $r->print('
1.648     bisitz   7966: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  7967: 
1.492     albertel 7968: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7969: '.$default_form_data.
                   7970:   &Apache::lonhtmlcommon::start_pick_box().
                   7971:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7972:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7973:   &Apache::lonhtmlcommon::row_closure().
                   7974:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7975:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7976:   &Apache::lonhtmlcommon::row_closure().
                   7977:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7978:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7979:   &Apache::lonhtmlcommon::row_closure().
                   7980:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7981:   '<input type="file" name="upfile" size="50" />'.
                   7982:   &Apache::lonhtmlcommon::row_closure(1).
                   7983:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7984: 
1.492     albertel 7985: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7986: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7987: </form>
1.492     albertel 7988: ');
1.157     albertel 7989:     return '';
                   7990: }
                   7991: 
1.423     albertel 7992: 
1.157     albertel 7993: sub scantron_upload_scantron_data_save {
1.608     www      7994:     my($r,$symb)=@_;
1.182     albertel 7995:     my $doanotherupload=
                   7996: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7997: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7998: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7999: 	'</form>'."\n";
1.257     albertel 8000:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8001: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8002: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8003: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8004: 	unless ($symb) {
1.182     albertel 8005: 	    $r->print($doanotherupload);
                   8006: 	}
1.162     albertel 8007: 	return '';
                   8008:     }
1.257     albertel 8009:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8010:     my $uploadedfile;
1.567     raeburn  8011:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8012:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8013:         $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 8014:     } else {
1.568     raeburn  8015:         my $result = 
                   8016:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8017:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8018: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8019: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8020:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8021: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8022:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8023:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8024:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8025: 	} else {
1.567     raeburn  8026: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8027:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8028: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8029: 	}
                   8030:     }
1.174     albertel 8031:     if ($symb) {
1.612     www      8032: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8033:     } else {
1.182     albertel 8034: 	$r->print($doanotherupload);
1.174     albertel 8035:     }
1.157     albertel 8036:     return '';
                   8037: }
                   8038: 
1.567     raeburn  8039: sub validate_uploaded_scantron_file {
                   8040:     my ($cdom,$cname,$fname) = @_;
                   8041:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8042:     my @lines;
                   8043:     if ($scanlines ne '-1') {
                   8044:         @lines=split("\n",$scanlines,-1);
                   8045:     }
                   8046:     my $output;
                   8047:     if (@lines) {
                   8048:         my (%counts,$max_match_format);
                   8049:         my ($max_match_count,$max_match_pct) = (0,0);
                   8050:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8051:         my %idmap = &username_to_idmap($classlist);
                   8052:         foreach my $key (keys(%idmap)) {
                   8053:             my $lckey = lc($key);
                   8054:             $idmap{$lckey} = $idmap{$key};
                   8055:         }
                   8056:         my %unique_formats;
                   8057:         my @formatlines = &get_scantronformat_file();
                   8058:         foreach my $line (@formatlines) {
                   8059:             chomp($line);
                   8060:             my @config = split(/:/,$line);
                   8061:             my $idstart = $config[5];
                   8062:             my $idlength = $config[6];
                   8063:             if (($idstart ne '') && ($idlength > 0)) {
                   8064:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8065:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8066:                 } else {
                   8067:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8068:                 }
                   8069:             }
                   8070:         }
                   8071:         foreach my $key (keys(%unique_formats)) {
                   8072:             my ($idstart,$idlength) = split(':',$key);
                   8073:             %{$counts{$key}} = (
                   8074:                                'found'   => 0,
                   8075:                                'total'   => 0,
                   8076:                               );
                   8077:             foreach my $line (@lines) {
                   8078:                 next if ($line =~ /^#/);
                   8079:                 next if ($line =~ /^[\s\cz]*$/);
                   8080:                 my $id = substr($line,$idstart-1,$idlength);
                   8081:                 $id = lc($id);
                   8082:                 if (exists($idmap{$id})) {
                   8083:                     $counts{$key}{'found'} ++;
                   8084:                 }
                   8085:                 $counts{$key}{'total'} ++;
                   8086:             }
                   8087:             if ($counts{$key}{'total'}) {
                   8088:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8089:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8090:                     $max_match_pct = $percent_match;
                   8091:                     $max_match_format = $key;
                   8092:                     $max_match_count = $counts{$key}{'total'};
                   8093:                 }
                   8094:             }
                   8095:         }
                   8096:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8097:             my $format_descs;
                   8098:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8099:             for (my $i=0; $i<$numwithformat; $i++) {
                   8100:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8101:                 if ($i<$numwithformat-2) {
                   8102:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8103:                 } elsif ($i==$numwithformat-2) {
                   8104:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8105:                 } elsif ($i==$numwithformat-1) {
                   8106:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8107:                 }
                   8108:             }
                   8109:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8110:             $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).
                   8111:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8112:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8113:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8114:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8115:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8116:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8117:                        '</ul>';
                   8118:         }
                   8119:     } else {
                   8120:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8121:     }
                   8122:     return $output;
                   8123: }
                   8124: 
1.202     albertel 8125: sub valid_file {
                   8126:     my ($requested_file)=@_;
                   8127:     foreach my $filename (sort(&scantron_filenames())) {
                   8128: 	if ($requested_file eq $filename) { return 1; }
                   8129:     }
                   8130:     return 0;
                   8131: }
                   8132: 
                   8133: sub scantron_download_scantron_data {
1.608     www      8134:     my ($r,$symb)=@_;
                   8135:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8136:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8137:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8138:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8139:     if (! &valid_file($file)) {
1.492     albertel 8140: 	$r->print('
1.202     albertel 8141: 	<p>
1.492     albertel 8142: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8143:         </p>
1.492     albertel 8144: ');
1.202     albertel 8145: 	return;
                   8146:     }
                   8147:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8148:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8149:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8150:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8151:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8152:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8153:     $r->print('
1.202     albertel 8154:     <p>
1.492     albertel 8155: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8156: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8157:     </p>
                   8158:     <p>
1.492     albertel 8159: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8160: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8161:     </p>
                   8162:     <p>
1.492     albertel 8163: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8164: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8165:     </p>
1.492     albertel 8166: ');
1.202     albertel 8167:     return '';
                   8168: }
1.157     albertel 8169: 
1.523     raeburn  8170: sub checkscantron_results {
1.608     www      8171:     my ($r,$symb) = @_;
1.523     raeburn  8172:     if (!$symb) {return '';}
                   8173:     my $cid = $env{'request.course.id'};
1.542     raeburn  8174:     my %lettdig = &letter_to_digits();
1.523     raeburn  8175:     my $numletts = scalar(keys(%lettdig));
                   8176:     my $cnum = $env{'course.'.$cid.'.num'};
                   8177:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8178:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8179:     my %record;
                   8180:     my %scantron_config =
                   8181:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8182:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8183:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8184:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8185:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8186:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8187:     unless (ref($navmap)) {
                   8188:         $r->print(&navmap_errormsg());
                   8189:         return '';
                   8190:     }
1.523     raeburn  8191:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8192:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8193:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8194:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8195: 
1.554     raeburn  8196:     my ($uname,$udom);
1.523     raeburn  8197:     my (%scandata,%lastname,%bylast);
                   8198:     $r->print('
                   8199: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8200: 
                   8201:     my @delayqueue;
                   8202:     my %completedstudents;
                   8203: 
                   8204:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8205:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8206:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8207:                                     'inline',undef,'checkscantron');
1.546     raeburn  8208:     my ($username,$domain,$started);
1.582     raeburn  8209:     my $nav_error;
1.649     raeburn  8210:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8211:     if ($nav_error) {
                   8212:         $r->print(&navmap_errormsg());
                   8213:         return '';
                   8214:     }
1.523     raeburn  8215: 
                   8216:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8217:                                           'Processing first student');
                   8218:     my $start=&Time::HiRes::time();
                   8219:     my $i=-1;
                   8220: 
                   8221:     while ($i<$scanlines->{'count'}) {
                   8222:         ($username,$domain,$uname)=('','','');
                   8223:         $i++;
                   8224:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8225:         if ($line=~/^[\s\cz]*$/) { next; }
                   8226:         if ($started) {
                   8227:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8228:                                                      'last student');
                   8229:         }
                   8230:         $started=1;
                   8231:         my $scan_record=
                   8232:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8233:                                                      $scan_data);
                   8234:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8235:                                                               \%idmap,$i)) {
                   8236:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8237:                                 'Unable to find a student that matches',1);
                   8238:             next;
                   8239:         }
                   8240:         if (exists $completedstudents{$uname}) {
                   8241:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8242:                                 'Student '.$uname.' has multiple sheets',2);
                   8243:             next;
                   8244:         }
                   8245:         my $pid = $scan_record->{'scantron.ID'};
                   8246:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8247:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8248:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8249:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8250:         chomp($scandata{$pid});
                   8251:         $scandata{$pid} =~ s/\r$//;
                   8252:         ($username,$domain)=split(/:/,$uname);
                   8253:         my $counter = -1;
                   8254:         foreach my $resource (@resources) {
1.557     raeburn  8255:             my $parts;
1.554     raeburn  8256:             my $ressymb = $resource->symb();
1.557     raeburn  8257:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8258:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8259:                 (my $analysis,$parts) =
1.649     raeburn  8260:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
1.557     raeburn  8261:             } else {
                   8262:                 $parts = $grader_partids_by_symb{$ressymb};
                   8263:             }
1.542     raeburn  8264:             ($counter,my $recording) =
                   8265:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8266:                                          $scandata{$pid},$parts,
1.542     raeburn  8267:                                          \%scantron_config,\%lettdig,$numletts);
                   8268:             $record{$pid} .= $recording;
1.523     raeburn  8269:         }
                   8270:     }
                   8271:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8272:     $r->print('<br />');
                   8273:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8274:     $passed = 0;
                   8275:     $failed = 0;
                   8276:     $numstudents = 0;
                   8277:     foreach my $last (sort(keys(%bylast))) {
                   8278:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8279:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8280:                 my $showscandata = $scandata{$pid};
                   8281:                 my $showrecord = $record{$pid};
                   8282:                 $showscandata =~ s/\s/&nbsp;/g;
                   8283:                 $showrecord =~ s/\s/&nbsp;/g;
                   8284:                 if ($scandata{$pid} eq $record{$pid}) {
                   8285:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8286:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8287: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8288: '</tr>'."\n".
                   8289: '<tr class="'.$css_class.'">'."\n".
                   8290: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8291:                     $passed ++;
                   8292:                 } else {
                   8293:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8294:                     $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  8295: '</tr>'."\n".
                   8296: '<tr class="'.$css_class.'">'."\n".
                   8297: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8298: '</tr>'."\n";
                   8299:                     $failed ++;
                   8300:                 }
                   8301:                 $numstudents ++;
                   8302:             }
                   8303:         }
                   8304:     }
1.648     bisitz   8305:     $r->print(
                   8306:         '<p>'
                   8307:        .&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).',
                   8308:             '<b>',
                   8309:             $numstudents,
                   8310:             '</b>',
                   8311:             $env{'form.scantron_maxbubble'})
                   8312:        .'</p>'
                   8313:     );
1.523     raeburn  8314:     $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>');
                   8315:     if ($passed) {
1.572     www      8316:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8317:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8318:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8319:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8320:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8321:                  $okstudents."\n".
                   8322:                  &Apache::loncommon::end_data_table().'<br />');
                   8323:     }
                   8324:     if ($failed) {
1.572     www      8325:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8326:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8327:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8328:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8329:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8330:                  $badstudents."\n".
                   8331:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8332:                  &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  8333:     }
1.614     www      8334:     $r->print('</form><br />');
1.523     raeburn  8335:     return;
                   8336: }
                   8337: 
1.542     raeburn  8338: sub verify_scantron_grading {
1.554     raeburn  8339:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8340:         $scantron_config,$lettdig,$numletts) = @_;
                   8341:     my ($record,%expected,%startpos);
                   8342:     return ($counter,$record) if (!ref($resource));
                   8343:     return ($counter,$record) if (!$resource->is_problem());
                   8344:     my $symb = $resource->symb();
1.554     raeburn  8345:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8346:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8347:         $counter ++;
                   8348:         $expected{$part_id} = 0;
                   8349:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8350:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8351:             foreach my $item (@sub_lines) {
                   8352:                 $expected{$part_id} += $item;
                   8353:             }
                   8354:         } else {
                   8355:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8356:         }
                   8357:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8358:     }
                   8359:     if ($symb) {
                   8360:         my %recorded;
                   8361:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8362:         if ($returnhash{'version'}) {
                   8363:             my %lasthash=();
                   8364:             my $version;
                   8365:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8366:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8367:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8368:                 }
                   8369:             }
                   8370:             foreach my $key (keys(%lasthash)) {
                   8371:                 if ($key =~ /\.scantron$/) {
                   8372:                     my $value = &unescape($lasthash{$key});
                   8373:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8374:                     if ($value eq '') {
                   8375:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8376:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8377:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8378:                             }
                   8379:                         }
                   8380:                     } else {
                   8381:                         my @tocheck;
                   8382:                         my @items = split(//,$value);
                   8383:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8384:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8385:                             if (@items < $expected{$part_id}) {
                   8386:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8387:                                 my @singles = split(//,$fragment);
                   8388:                                 foreach my $pos (@singles) {
                   8389:                                     if ($pos eq ' ') {
                   8390:                                         push(@tocheck,$pos);
                   8391:                                     } else {
                   8392:                                         my $next = shift(@items);
                   8393:                                         push(@tocheck,$next);
                   8394:                                     }
                   8395:                                 }
                   8396:                             } else {
                   8397:                                 @tocheck = @items;
                   8398:                             }
                   8399:                             foreach my $letter (@tocheck) {
                   8400:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8401:                                     if ($letter !~ /^[A-J]$/) {
                   8402:                                         $letter = $scantron_config->{'Qoff'};
                   8403:                                     }
                   8404:                                     $recorded{$part_id} .= $letter;
                   8405:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8406:                                     my $digit;
                   8407:                                     if ($letter !~ /^[A-J]$/) {
                   8408:                                         $digit = $scantron_config->{'Qoff'};
                   8409:                                     } else {
                   8410:                                         $digit = $lettdig->{$letter};
                   8411:                                     }
                   8412:                                     $recorded{$part_id} .= $digit;
                   8413:                                 }
                   8414:                             }
                   8415:                         } else {
                   8416:                             @tocheck = @items;
                   8417:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8418:                                 my $curr_sub = shift(@tocheck);
                   8419:                                 my $digit;
                   8420:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8421:                                     $digit = $lettdig->{$curr_sub}-1;
                   8422:                                 }
                   8423:                                 if ($curr_sub eq 'J') {
                   8424:                                     $digit += scalar($numletts);
                   8425:                                 }
                   8426:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8427:                                     if ($j == $digit) {
                   8428:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8429:                                     } else {
                   8430:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8431:                                     }
                   8432:                                 }
                   8433:                             }
                   8434:                         }
                   8435:                     }
                   8436:                 }
                   8437:             }
                   8438:         }
1.554     raeburn  8439:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8440:             if ($recorded{$part_id} eq '') {
                   8441:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8442:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8443:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8444:                     }
                   8445:                 }
                   8446:             }
                   8447:             $record .= $recorded{$part_id};
                   8448:         }
                   8449:     }
                   8450:     return ($counter,$record);
                   8451: }
                   8452: 
                   8453: sub letter_to_digits { 
                   8454:     my %lettdig = (
                   8455:                     A => 1,
                   8456:                     B => 2,
                   8457:                     C => 3,
                   8458:                     D => 4,
                   8459:                     E => 5,
                   8460:                     F => 6,
                   8461:                     G => 7,
                   8462:                     H => 8,
                   8463:                     I => 9,
                   8464:                     J => 0,
                   8465:                   );
                   8466:     return %lettdig;
                   8467: }
                   8468: 
1.423     albertel 8469: 
1.75      albertel 8470: #-------- end of section for handling grading scantron forms -------
                   8471: #
                   8472: #-------------------------------------------------------------------
                   8473: 
1.72      ng       8474: #-------------------------- Menu interface -------------------------
                   8475: #
1.614     www      8476: #--- Href with symb and command ---
                   8477: 
                   8478: sub href_symb_cmd {
                   8479:     my ($symb,$cmd)=@_;
                   8480:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8481: }
                   8482: 
1.443     banghart 8483: sub grading_menu {
1.608     www      8484:     my ($request,$symb) = @_;
1.443     banghart 8485:     if (!$symb) {return '';}
                   8486: 
                   8487:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8488:                   'command'=>'individual');
1.538     schulted 8489:     
1.598     www      8490:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8491: 
                   8492:     $fields{'command'}='ungraded';
                   8493:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8494: 
                   8495:     $fields{'command'}='table';
                   8496:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8497: 
                   8498:     $fields{'command'}='all_for_one';
                   8499:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8500: 
1.621     www      8501:     $fields{'command'}='downloadfilesselect';
                   8502:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8503: 
1.443     banghart 8504:     $fields{'command'} = 'csvform';
1.538     schulted 8505:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8506:     
1.443     banghart 8507:     $fields{'command'} = 'processclicker';
1.538     schulted 8508:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8509:     
1.443     banghart 8510:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8511:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8512: 
                   8513:     $fields{'command'} = 'initialverifyreceipt';
                   8514:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8515:     
1.598     www      8516:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8517:             items =>[
1.598     www      8518:                         {	linktext => 'Select individual students to grade',
                   8519:                     		url => $url1a,
1.538     schulted 8520:                     		permission => 'F',
1.636     wenzelju 8521:                     		icon => 'grade_students.png',
1.598     www      8522:                     		linktitle => 'Grade current resource for a selection of students.'
                   8523:                         }, 
                   8524:                         {       linktext => 'Grade ungraded submissions.',
                   8525:                                 url => $url1b,
                   8526:                                 permission => 'F',
1.636     wenzelju 8527:                                 icon => 'ungrade_sub.png',
1.598     www      8528:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8529:                         },
1.598     www      8530: 
                   8531:                         {       linktext => 'Grading table',
                   8532:                                 url => $url1c,
                   8533:                                 permission => 'F',
1.636     wenzelju 8534:                                 icon => 'grading_table.png',
1.598     www      8535:                                 linktitle => 'Grade current resource for all students.'
                   8536:                         },
1.615     www      8537:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8538:                                 url => $url1d,
                   8539:                                 permission => 'F',
1.636     wenzelju 8540:                                 icon => 'grade_PageFolder.png',
1.598     www      8541:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8542:                         },
                   8543:                         {       linktext => 'Download submissions',
                   8544:                                 url => $url1e,
                   8545:                                 permission => 'F',
1.636     wenzelju 8546:                                 icon => 'download_sub.png',
1.621     www      8547:                                 linktitle => 'Download all students submissions.'
1.598     www      8548:                         }]},
                   8549:                          { categorytitle=>'Automated Grading',
                   8550:                items =>[
                   8551: 
1.538     schulted 8552:                 	    {	linktext => 'Upload Scores',
                   8553:                     		url => $url2,
                   8554:                     		permission => 'F',
                   8555:                     		icon => 'uploadscores.png',
                   8556:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8557:                 	    },
                   8558:                 	    {	linktext => 'Process Clicker',
                   8559:                     		url => $url3,
                   8560:                     		permission => 'F',
                   8561:                     		icon => 'addClickerInfoFile.png',
                   8562:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8563:                 	    },
1.587     raeburn  8564:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8565:                     		url => $url4,
                   8566:                     		permission => 'F',
1.636     wenzelju 8567:                     		icon => 'bubblesheet.png',
1.648     bisitz   8568:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8569:                 	    },
1.616     www      8570:                             {   linktext => 'Verify Receipt Number',
1.602     www      8571:                                 url => $url5,
                   8572:                                 permission => 'F',
1.636     wenzelju 8573:                                 icon => 'receipt_number.png',
1.602     www      8574:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8575:                             }
                   8576: 
1.538     schulted 8577:                     ]
                   8578:             });
                   8579: 
1.443     banghart 8580:     # Create the menu
                   8581:     my $Str;
1.445     banghart 8582:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8583:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8584:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8585: 
1.602     www      8586:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8587:     return $Str;    
                   8588: }
                   8589: 
1.598     www      8590: 
                   8591: sub ungraded {
                   8592:     my ($request)=@_;
                   8593:     &submit_options($request);
                   8594: }
                   8595: 
1.599     www      8596: sub submit_options_sequence {
1.608     www      8597:     my ($request,$symb) = @_;
1.599     www      8598:     if (!$symb) {return '';}
1.600     www      8599:     &commonJSfunctions($request);
                   8600:     my $result;
1.599     www      8601: 
1.600     www      8602:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8603:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8604:     $result.=&selectfield(0).
1.601     www      8605:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8606:             <div>
                   8607:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8608:             </div>
                   8609:         </div>
                   8610:   </form>';
                   8611:     return $result;
                   8612: }
                   8613: 
                   8614: sub submit_options_table {
1.608     www      8615:     my ($request,$symb) = @_;
1.600     www      8616:     if (!$symb) {return '';}
1.599     www      8617:     &commonJSfunctions($request);
                   8618:     my $result;
                   8619: 
                   8620:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8621:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8622: 
1.632     www      8623:     $result.=&selectfield(0).
1.601     www      8624:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8625:             <div>
                   8626:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8627:             </div>
                   8628:         </div>
                   8629:   </form>';
                   8630:     return $result;
                   8631: }
1.443     banghart 8632: 
1.621     www      8633: sub submit_options_download {
                   8634:     my ($request,$symb) = @_;
                   8635:     if (!$symb) {return '';}
                   8636: 
                   8637:     &commonJSfunctions($request);
                   8638: 
                   8639:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8640:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8641:     $result.='
                   8642: <h2>
                   8643:   '.&mt('Select Students for Which to Download Submissions').'
                   8644: </h2>'.&selectfield(1).'
                   8645:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8646:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8647:             </div>
                   8648:           </div>
1.600     www      8649: 
                   8650: 
1.621     www      8651:   </form>';
                   8652:     return $result;
                   8653: }
                   8654: 
1.443     banghart 8655: #--- Displays the submissions first page -------
                   8656: sub submit_options {
1.608     www      8657:     my ($request,$symb) = @_;
1.72      ng       8658:     if (!$symb) {return '';}
                   8659: 
1.118     ng       8660:     &commonJSfunctions($request);
1.473     albertel 8661:     my $result;
1.533     bisitz   8662: 
1.72      ng       8663:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8664: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8665:     $result.=&selectfield(1).'
1.601     www      8666:                 <input type="hidden" name="command" value="submission" /> 
                   8667: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8668:             </div>
                   8669:           </div>
                   8670: 
                   8671: 
                   8672:   </form>';
                   8673:     return $result;
                   8674: }
1.533     bisitz   8675: 
1.601     www      8676: sub selectfield {
                   8677:    my ($full)=@_;
1.635     raeburn  8678:    my %options = 
                   8679:           (&Apache::lonlocal::texthash(
                   8680:              'yes'       => 'with submissions',
                   8681:              'queued'    => 'in grading queue',
                   8682:              'graded'    => 'with ungraded submissions',
                   8683:              'incorrect' => 'with incorrect submissions',
                   8684:              'all'       => 'with any status'),
                   8685:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8686:    my $result='<div class="LC_columnSection">
1.537     harmsja  8687:   
1.533     bisitz   8688:     <fieldset>
                   8689:       <legend>
                   8690:        '.&mt('Sections').'
                   8691:       </legend>
1.601     www      8692:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8693:     </fieldset>
1.537     harmsja  8694:   
1.533     bisitz   8695:     <fieldset>
                   8696:       <legend>
                   8697:         '.&mt('Groups').'
                   8698:       </legend>
                   8699:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8700:     </fieldset>
1.537     harmsja  8701:   
1.533     bisitz   8702:     <fieldset>
                   8703:       <legend>
                   8704:         '.&mt('Access Status').'
                   8705:       </legend>
1.601     www      8706:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8707:     </fieldset>';
                   8708:     if ($full) {
                   8709:        $result.='
1.533     bisitz   8710:     <fieldset>
                   8711:       <legend>
                   8712:         '.&mt('Submission Status').'
1.601     www      8713:       </legend>'.
1.635     raeburn  8714:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8715:    '</fieldset>';
                   8716:     }
                   8717:     $result.='</div><br />';
1.44      ng       8718:     return $result;
1.2       albertel 8719: }
                   8720: 
1.285     albertel 8721: sub reset_perm {
                   8722:     undef(%perm);
                   8723: }
                   8724: 
                   8725: sub init_perm {
                   8726:     &reset_perm();
1.300     albertel 8727:     foreach my $test_perm ('vgr','mgr','opa') {
                   8728: 
                   8729: 	my $scope = $env{'request.course.id'};
                   8730: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8731: 
                   8732: 	    $scope .= '/'.$env{'request.course.sec'};
                   8733: 	    if ( $perm{$test_perm}=
                   8734: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8735: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8736: 	    } else {
                   8737: 		delete($perm{$test_perm});
                   8738: 	    }
1.285     albertel 8739: 	}
                   8740:     }
                   8741: }
                   8742: 
1.400     www      8743: sub gather_clicker_ids {
1.408     albertel 8744:     my %clicker_ids;
1.400     www      8745: 
                   8746:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8747: 
                   8748:     # Set up a couple variables.
1.407     albertel 8749:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8750:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8751:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8752: 
1.407     albertel 8753:     foreach my $student (keys(%$classlist)) {
1.438     www      8754:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8755:         my $username = $classlist->{$student}->[$username_idx];
                   8756:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8757:         my $clickers =
1.408     albertel 8758: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8759:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8760:             $id=~s/^[\#0]+//;
1.421     www      8761:             $id=~s/[\-\:]//g;
1.407     albertel 8762:             if (exists($clicker_ids{$id})) {
1.408     albertel 8763: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8764:             } else {
1.408     albertel 8765: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8766:             }
                   8767:         }
                   8768:     }
1.407     albertel 8769:     return %clicker_ids;
1.400     www      8770: }
                   8771: 
1.402     www      8772: sub gather_adv_clicker_ids {
1.408     albertel 8773:     my %clicker_ids;
1.402     www      8774:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8775:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8776:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8777:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8778:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8779:             my ($puname,$pudom)=split(/\:/,$person);
                   8780:             my $clickers =
1.408     albertel 8781: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8782:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8783: 		$id=~s/^[\#0]+//;
1.421     www      8784:                 $id=~s/[\-\:]//g;
1.408     albertel 8785: 		if (exists($clicker_ids{$id})) {
                   8786: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8787: 		} else {
                   8788: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8789: 		}
1.405     www      8790:             }
1.402     www      8791:         }
                   8792:     }
1.407     albertel 8793:     return %clicker_ids;
1.402     www      8794: }
                   8795: 
1.413     www      8796: sub clicker_grading_parameters {
                   8797:     return ('gradingmechanism' => 'scalar',
                   8798:             'upfiletype' => 'scalar',
                   8799:             'specificid' => 'scalar',
                   8800:             'pcorrect' => 'scalar',
                   8801:             'pincorrect' => 'scalar');
                   8802: }
                   8803: 
1.400     www      8804: sub process_clicker {
1.608     www      8805:     my ($r,$symb)=@_;
1.400     www      8806:     if (!$symb) {return '';}
                   8807:     my $result=&checkforfile_js();
1.632     www      8808:     $result.=&Apache::loncommon::start_data_table().
                   8809:              &Apache::loncommon::start_data_table_header_row().
                   8810:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8811:              &Apache::loncommon::end_data_table_header_row().
                   8812:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8813: # Attempt to restore parameters from last session, set defaults if not present
                   8814:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8815:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8816:                                                  \%Saveable_Parameters);
                   8817:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8818:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8819:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8820:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8821: 
                   8822:     my %checked;
1.521     www      8823:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8824:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8825:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8826:        }
                   8827:     }
                   8828: 
1.632     www      8829:     my $upload=&mt("Evaluate File");
1.400     www      8830:     my $type=&mt("Type");
1.402     www      8831:     my $attendance=&mt("Award points just for participation");
                   8832:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8833:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8834:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8835:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8836:     my $pcorrect=&mt("Percentage points for correct solution");
                   8837:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8838:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8839: 						   {'iclicker' => 'i>clicker',
                   8840:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8841:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8842:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8843: function sanitycheck() {
                   8844: // Accept only integer percentages
                   8845:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8846:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8847: // Find out grading choice
                   8848:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8849:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8850:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8851:       }
                   8852:    }
                   8853: // By default, new choice equals user selection
                   8854:    newgradingchoice=gradingchoice;
                   8855: // Not good to give more points for false answers than correct ones
                   8856:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8857:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8858:    }
                   8859: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8860:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8861:       document.forms.gradesupload.pcorrect.value=100;
                   8862:       document.forms.gradesupload.pincorrect.value=100;
                   8863:    }
                   8864: // If the values are different, cannot be attendance only
                   8865:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8866:        (gradingchoice=='attendance')) {
                   8867:        newgradingchoice='personnel';
                   8868:    }
                   8869: // Change grading choice to new one
                   8870:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8871:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8872:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8873:       } else {
                   8874:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8875:       }
                   8876:    }
                   8877: // Remember the old state
                   8878:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8879: }
1.597     wenzelju 8880: ENDUPFORM
                   8881:     $result.= <<ENDUPFORM;
1.400     www      8882: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8883: <input type="hidden" name="symb" value="$symb" />
                   8884: <input type="hidden" name="command" value="processclickerfile" />
                   8885: <input type="file" name="upfile" size="50" />
                   8886: <br /><label>$type: $selectform</label>
1.632     www      8887: ENDUPFORM
                   8888:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8889:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8890:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8891: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8892: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8893: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8894: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8895: <br />&nbsp;&nbsp;&nbsp;
                   8896: <input type="text" name="givenanswer" size="50" />
1.413     www      8897: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8898: ENDGRADINGFORM
                   8899:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8900:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8901:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8902: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8903: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8904: </form>'
1.632     www      8905: ENDPERCFORM
                   8906:     $result.='</td>'.
                   8907:              &Apache::loncommon::end_data_table_row().
                   8908:              &Apache::loncommon::end_data_table();
1.400     www      8909:     return $result;
                   8910: }
                   8911: 
                   8912: sub process_clicker_file {
1.608     www      8913:     my ($r,$symb)=@_;
1.400     www      8914:     if (!$symb) {return '';}
1.413     www      8915: 
                   8916:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8917:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8918:                                               \%Saveable_Parameters);
1.598     www      8919:     my $result='';
1.404     www      8920:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8921: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8922: 	return $result;
1.404     www      8923:     }
1.522     www      8924:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8925:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8926:         return $result;
1.521     www      8927:     }
1.522     www      8928:     my $foundgiven=0;
1.521     www      8929:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8930:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8931:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      8932:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      8933:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8934:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8935:         $foundgiven=$#answers+1;
1.521     www      8936:     }
1.407     albertel 8937:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8938:     my %correct_ids;
1.404     www      8939:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8940: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8941:     }
                   8942:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8943: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8944: 	   $correct_id=~tr/a-z/A-Z/;
                   8945: 	   $correct_id=~s/\s//gs;
                   8946: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8947:            $correct_id=~s/[\-\:]//g;
1.414     www      8948:            if ($correct_id) {
                   8949: 	      $correct_ids{$correct_id}='specified';
                   8950:            }
                   8951:         }
1.400     www      8952:     }
1.404     www      8953:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8954: 	$result.=&mt('Score based on attendance only');
1.521     www      8955:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8956:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8957:     } else {
1.408     albertel 8958: 	my $number=0;
1.411     www      8959: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8960: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8961: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8962: 	    if ($correct_ids{$id} eq 'specified') {
                   8963: 		$result.=&mt('specified');
                   8964: 	    } else {
                   8965: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8966: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8967: 	    }
                   8968: 	    $number++;
                   8969: 	}
1.411     www      8970:         $result.="</p>\n";
1.408     albertel 8971: 	if ($number==0) {
                   8972: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8973: 	    return $result;
1.408     albertel 8974: 	}
1.404     www      8975:     }
1.405     www      8976:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8977:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8978: 		     '<span class="LC_error">',
                   8979: 		     '</span>',
                   8980: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8981:         return $result;
1.405     www      8982:     }
1.410     www      8983: 
                   8984: # Were able to get all the info needed, now analyze the file
                   8985: 
1.411     www      8986:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8987:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8988:     $result.=&Apache::loncommon::start_data_table().
                   8989:              &Apache::loncommon::start_data_table_header_row().
                   8990:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8991:              &Apache::loncommon::end_data_table_header_row().
                   8992:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8993: <td>
1.410     www      8994: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8995: <input type="hidden" name="symb" value="$symb" />
                   8996: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8997: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8998: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8999: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9000: ENDHEADER
1.522     www      9001:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9002:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9003:     } 
1.408     albertel 9004:     my %responses;
                   9005:     my @questiontitles;
1.405     www      9006:     my $errormsg='';
                   9007:     my $number=0;
                   9008:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9009: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9010:     }
1.419     www      9011:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9012:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9013:     }
1.411     www      9014:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9015:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9016:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9017:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9018:              '<br />';
1.522     www      9019:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9020:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9021:        return $result;
1.522     www      9022:     } 
1.414     www      9023: # Remember Question Titles
                   9024: # FIXME: Possibly need delimiter other than ":"
                   9025:     for (my $i=0;$i<$number;$i++) {
                   9026:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9027:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9028:     }
1.411     www      9029:     my $correct_count=0;
                   9030:     my $student_count=0;
                   9031:     my $unknown_count=0;
1.414     www      9032: # Match answers with usernames
                   9033: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9034:     foreach my $id (keys(%responses)) {
1.410     www      9035:        if ($correct_ids{$id}) {
1.414     www      9036:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9037:           $correct_count++;
1.410     www      9038:        } elsif ($clicker_ids{$id}) {
1.437     www      9039:           if ($clicker_ids{$id}=~/\,/) {
                   9040: # More than one user with the same clicker!
1.632     www      9041:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9042:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9043:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9044:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9045:                            "<select name='multi".$id."'>";
                   9046:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9047:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9048:              }
                   9049:              $result.='</select>';
                   9050:              $unknown_count++;
                   9051:           } else {
                   9052: # Good: found one and only one user with the right clicker
                   9053:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9054:              $student_count++;
                   9055:           }
1.410     www      9056:        } else {
1.632     www      9057:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9058:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9059:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9060:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9061:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9062:                    "\n".&mt("Domain").": ".
                   9063:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9064:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9065:           $unknown_count++;
1.410     www      9066:        }
1.405     www      9067:     }
1.412     www      9068:     $result.='<hr />'.
                   9069:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9070:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9071:        if ($correct_count==0) {
                   9072:           $errormsg.="Found no correct answers answers for grading!";
                   9073:        } elsif ($correct_count>1) {
1.414     www      9074:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9075:        }
                   9076:     }
1.428     www      9077:     if ($number<1) {
                   9078:        $errormsg.="Found no questions.";
                   9079:     }
1.412     www      9080:     if ($errormsg) {
                   9081:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9082:     } else {
                   9083:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9084:     }
1.632     www      9085:     $result.='</form></td>'.
                   9086:              &Apache::loncommon::end_data_table_row().
                   9087:              &Apache::loncommon::end_data_table();
1.614     www      9088:     return $result;
1.400     www      9089: }
                   9090: 
1.405     www      9091: sub iclicker_eval {
1.406     www      9092:     my ($questiontitles,$responses)=@_;
1.405     www      9093:     my $number=0;
                   9094:     my $errormsg='';
                   9095:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9096:         my %components=&Apache::loncommon::record_sep($line);
                   9097:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9098: 	if ($entries[0] eq 'Question') {
                   9099: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9100: 		$$questiontitles[$number]=$entries[$i];
                   9101: 		$number++;
                   9102: 	    }
                   9103: 	}
                   9104: 	if ($entries[0]=~/^\#/) {
                   9105: 	    my $id=$entries[0];
                   9106: 	    my @idresponses;
                   9107: 	    $id=~s/^[\#0]+//;
                   9108: 	    for (my $i=0;$i<$number;$i++) {
                   9109: 		my $idx=3+$i*6;
1.644     www      9110:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9111: 		push(@idresponses,$entries[$idx]);
                   9112: 	    }
                   9113: 	    $$responses{$id}=join(',',@idresponses);
                   9114: 	}
1.405     www      9115:     }
                   9116:     return ($errormsg,$number);
                   9117: }
                   9118: 
1.419     www      9119: sub interwrite_eval {
                   9120:     my ($questiontitles,$responses)=@_;
                   9121:     my $number=0;
                   9122:     my $errormsg='';
1.420     www      9123:     my $skipline=1;
                   9124:     my $questionnumber=0;
                   9125:     my %idresponses=();
1.419     www      9126:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9127:         my %components=&Apache::loncommon::record_sep($line);
                   9128:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9129:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9130:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9131:         next if $skipline;
                   9132:         if ($entries[0]!=$questionnumber) {
                   9133:            $questionnumber=$entries[0];
                   9134:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9135:            $number++;
1.419     www      9136:         }
1.420     www      9137:         my $id=$entries[4];
                   9138:         $id=~s/^[\#0]+//;
1.421     www      9139:         $id=~s/^v\d*\://i;
                   9140:         $id=~s/[\-\:]//g;
1.420     www      9141:         $idresponses{$id}[$number]=$entries[6];
                   9142:     }
1.524     raeburn  9143:     foreach my $id (keys(%idresponses)) {
1.420     www      9144:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9145:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9146:     }
                   9147:     return ($errormsg,$number);
                   9148: }
                   9149: 
1.414     www      9150: sub assign_clicker_grades {
1.608     www      9151:     my ($r,$symb)=@_;
1.414     www      9152:     if (!$symb) {return '';}
1.416     www      9153: # See which part we are saving to
1.582     raeburn  9154:     my $res_error;
                   9155:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9156:     if ($res_error) {
                   9157:         return &navmap_errormsg();
                   9158:     }
1.416     www      9159: # FIXME: This should probably look for the first handgradeable part
                   9160:     my $part=$$partlist[0];
                   9161: # Start screen output
1.632     www      9162:     my $result=&Apache::loncommon::start_data_table().
                   9163:              &Apache::loncommon::start_data_table_header_row().
                   9164:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9165:              &Apache::loncommon::end_data_table_header_row().
                   9166:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9167: # Get correct result
                   9168: # FIXME: Possibly need delimiter other than ":"
                   9169:     my @correct=();
1.415     www      9170:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9171:     my $number=$env{'form.number'};
                   9172:     if ($gradingmechanism ne 'attendance') {
1.414     www      9173:        foreach my $key (keys(%env)) {
                   9174:           if ($key=~/^form\.correct\:/) {
                   9175:              my @input=split(/\,/,$env{$key});
                   9176:              for (my $i=0;$i<=$#input;$i++) {
                   9177:                  if (($correct[$i]) && ($input[$i]) &&
                   9178:                      ($correct[$i] ne $input[$i])) {
                   9179:                     $result.='<br /><span class="LC_warning">'.
                   9180:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9181:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9182:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9183:                     $correct[$i]=$input[$i];
                   9184:                  }
                   9185:              }
                   9186:           }
                   9187:        }
1.415     www      9188:        for (my $i=0;$i<$number;$i++) {
1.644     www      9189:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9190:              $result.='<br /><span class="LC_error">'.
                   9191:                       &mt('No correct result given for question "[_1]"!',
                   9192:                           $env{'form.question:'.$i}).'</span>';
                   9193:           }
                   9194:        }
1.644     www      9195:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9196:     }
                   9197: # Start grading
1.415     www      9198:     my $pcorrect=$env{'form.pcorrect'};
                   9199:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9200:     my $storecount=0;
1.632     www      9201:     my %users=();
1.415     www      9202:     foreach my $key (keys(%env)) {
1.420     www      9203:        my $user='';
1.415     www      9204:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9205:           $user=$1;
                   9206:        }
                   9207:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9208:           my $id=$1;
                   9209:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9210:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9211:           } elsif ($env{'form.multi'.$id}) {
                   9212:              $user=$env{'form.multi'.$id};
1.420     www      9213:           }
                   9214:        }
1.632     www      9215:        if ($user) {
                   9216:           if ($users{$user}) {
                   9217:              $result.='<br /><span class="LC_warning">'.
                   9218:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9219:                       '</span><br />';
                   9220:           }
                   9221:           $users{$user}=1; 
1.415     www      9222:           my @answer=split(/\,/,$env{$key});
                   9223:           my $sum=0;
1.522     www      9224:           my $realnumber=$number;
1.415     www      9225:           for (my $i=0;$i<$number;$i++) {
1.576     www      9226:              if  ($correct[$i] eq '-') {
                   9227:                 $realnumber--;
1.644     www      9228:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9229:                 if ($gradingmechanism eq 'attendance') {
                   9230:                    $sum+=$pcorrect;
1.576     www      9231:                 } elsif ($correct[$i] eq '*') {
1.522     www      9232:                    $sum+=$pcorrect;
1.415     www      9233:                 } else {
1.644     www      9234: # We actually grade if correct or not
                   9235:                    my $increment=$pincorrect;
                   9236: # Special case: numerical answer "0"
                   9237:                    if ($correct[$i] eq '0') {
                   9238:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9239:                          $increment=$pcorrect;
                   9240:                       }
                   9241: # General numerical answer, both evaluate to something non-zero
                   9242:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9243:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9244:                          $increment=$pcorrect;
                   9245:                       }
                   9246: # Must be just alphanumeric
                   9247:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9248:                       $increment=$pcorrect;
1.415     www      9249:                    }
1.644     www      9250:                    $sum+=$increment;
1.415     www      9251:                 }
                   9252:              }
                   9253:           }
1.522     www      9254:           my $ave=$sum/(100*$realnumber);
1.416     www      9255: # Store
                   9256:           my ($username,$domain)=split(/\:/,$user);
                   9257:           my %grades=();
                   9258:           $grades{"resource.$part.solved"}='correct_by_override';
                   9259:           $grades{"resource.$part.awarded"}=$ave;
                   9260:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9261:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9262:                                                  $env{'request.course.id'},
                   9263:                                                  $domain,$username);
                   9264:           if ($returncode ne 'ok') {
                   9265:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9266:           } else {
                   9267:              $storecount++;
                   9268:           }
1.415     www      9269:        }
                   9270:     }
                   9271: # We are done
1.549     hauer    9272:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9273:              '</td>'.
                   9274:              &Apache::loncommon::end_data_table_row().
                   9275:              &Apache::loncommon::end_data_table();
1.614     www      9276:     return $result;
1.414     www      9277: }
                   9278: 
1.582     raeburn  9279: sub navmap_errormsg {
                   9280:     return '<div class="LC_error">'.
                   9281:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9282:            &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  9283:            '</div>';
                   9284: }
1.607     droeschl 9285: 
1.609     www      9286: sub startpage {
1.613     www      9287:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9288:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9289:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9290:                                           {'bread_crumbs' => $crumbs}));
1.645     www      9291:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
1.613     www      9292:     unless ($nodisplayflag) {
                   9293:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9294:     }
1.607     droeschl 9295: }
1.582     raeburn  9296: 
1.622     www      9297: sub select_problem {
                   9298:     my ($r)=@_;
1.632     www      9299:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9300:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9301:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9302:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9303: }
                   9304: 
1.1       albertel 9305: sub handler {
1.41      ng       9306:     my $request=$_[0];
1.434     albertel 9307:     &reset_caches();
1.646     raeburn  9308:     if ($request->header_only) {
                   9309:         &Apache::loncommon::content_type($request,'text/html');
                   9310:         $request->send_http_header;
                   9311:         return OK;
                   9312:     }
                   9313:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9314: 
                   9315:     &init_perm();
                   9316:     if (!$env{'request.course.id'}) {
                   9317:         # Not in a course.
                   9318:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9319:         return HTTP_NOT_ACCEPTABLE;
                   9320:     } elsif (!%perm) {
                   9321:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9322:     }
1.646     raeburn  9323:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9324:     $request->send_http_header;
1.646     raeburn  9325: 
1.608     www      9326: 
                   9327: # see what command we need to execute
                   9328: 
1.160     albertel 9329:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9330:     my $command=$commands[0];
1.447     foxr     9331: 
1.160     albertel 9332:     if ($#commands > 0) {
                   9333: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9334:     }
1.608     www      9335: 
                   9336: # see what the symb is
                   9337: 
                   9338:     my $symb=$env{'form.symb'};
                   9339:     unless ($symb) {
                   9340:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9341:        $symb=&Apache::lonnet::symbread($url);
                   9342:     }
1.646     raeburn  9343:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9344: 
1.513     foxr     9345:     $ssi_error = 0;
1.637     www      9346:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9347: #
1.637     www      9348: # Not called from a resource, but inside a course
1.601     www      9349: #    
1.622     www      9350:         &startpage($request,undef,[],1,1);
                   9351:         &select_problem($request);
1.41      ng       9352:     } else {
1.104     albertel 9353: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9354:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9355: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9356: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9357:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9358:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9359: 	    &pickStudentPage($request,$symb);
1.103     albertel 9360: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9361:             &startpage($request,$symb,
                   9362:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9363:                                        {href=>'',text=>'Select student'},
                   9364:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9365: 	    &displayPage($request,$symb);
1.104     albertel 9366: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9367:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9368:                                        {href=>'',text=>'Select student'},
                   9369:                                        {href=>'',text=>'Grade student'},
                   9370:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9371: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9372: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9373:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9374:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9375: 	    &processGroup($request,$symb);
1.104     albertel 9376: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9377:             &startpage($request,$symb);
                   9378: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9379: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9380:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9381: 	    $request->print(&submit_options($request,$symb));
1.598     www      9382:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9383:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9384:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9385:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9386:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9387:             $request->print(&submit_options_table($request,$symb));
1.598     www      9388:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9389:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9390:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9391: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9392:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9393: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9394: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9395:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9396:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9397: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9398: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9399:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9400:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9401:                                                                              text=>"Modify grades"},
                   9402:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9403: 	    $request->print(&editgrades($request,$symb));
1.602     www      9404:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9405:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9406:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9407: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9408:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9409:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9410: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9411:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9412:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9413:             $request->print(&process_clicker($request,$symb));
1.400     www      9414:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9415:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9416:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9417:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9418:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9419:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9420:                                        {href=>'', text=>'Process clicker file'},
                   9421:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9422:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9423: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9424:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9425: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9426: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9427:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9428: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9429: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9430:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9431: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9432: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9433: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9434:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9435: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9436: 	    } else {
1.257     albertel 9437: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9438: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9439: 		} else {
1.257     albertel 9440: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9441: 		}
1.627     www      9442:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9443: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9444: 	    }
1.246     albertel 9445: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9446:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9447: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9448: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9449:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9450: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9451:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9452:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9453:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9454: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9455:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9456: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9457: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9458:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9459: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9460:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9461:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9462: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9463:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9464:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9465:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9466:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9467: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9468:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9469:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9470:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9471: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9472:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9473:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9474:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9475:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9476:             $request->print(&checkscantron_results($request,$symb));
                   9477:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9478:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9479:             $request->print(&submit_options_download($request,$symb));
                   9480:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9481:             &startpage($request,$symb,
                   9482:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9483:     {href=>'', text=>'Download submissions'}]);
                   9484:             &submit_download_link($request,$symb);
1.106     albertel 9485: 	} elsif ($command) {
1.620     www      9486:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9487: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9488: 	}
1.2       albertel 9489:     }
1.513     foxr     9490:     if ($ssi_error) {
                   9491: 	&ssi_print_error($request);
                   9492:     }
1.639     www      9493:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9494:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9495:     &reset_caches();
1.646     raeburn  9496:     return OK;
1.44      ng       9497: }
                   9498: 
1.1       albertel 9499: 1;
                   9500: 
1.13      albertel 9501: __END__;
1.531     jms      9502: 
                   9503: 
                   9504: =head1 NAME
                   9505: 
                   9506: Apache::grades
                   9507: 
                   9508: =head1 SYNOPSIS
                   9509: 
                   9510: Handles the viewing of grades.
                   9511: 
                   9512: This is part of the LearningOnline Network with CAPA project
                   9513: described at http://www.lon-capa.org.
                   9514: 
                   9515: =head1 OVERVIEW
                   9516: 
                   9517: Do an ssi with retries:
                   9518: While I'd love to factor out this with the vesrion in lonprintout,
                   9519: 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
                   9520: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9521: 
                   9522: At least the logic that drives this has been pulled out into loncommon.
                   9523: 
                   9524: 
                   9525: 
                   9526: ssi_with_retries - Does the server side include of a resource.
                   9527:                      if the ssi call returns an error we'll retry it up to
                   9528:                      the number of times requested by the caller.
                   9529:                      If we still have a proble, no text is appended to the
                   9530:                      output and we set some global variables.
                   9531:                      to indicate to the caller an SSI error occurred.  
                   9532:                      All of this is supposed to deal with the issues described
                   9533:                      in LonCAPA BZ 5631 see:
                   9534:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9535:                      by informing the user that this happened.
                   9536: 
                   9537: Parameters:
                   9538:   resource   - The resource to include.  This is passed directly, without
                   9539:                interpretation to lonnet::ssi.
                   9540:   form       - The form hash parameters that guide the interpretation of the resource
                   9541:                
                   9542:   retries    - Number of retries allowed before giving up completely.
                   9543: Returns:
                   9544:   On success, returns the rendered resource identified by the resource parameter.
                   9545: Side Effects:
                   9546:   The following global variables can be set:
                   9547:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9548:                               It is up to the caller to initialize this to false
                   9549:                               if desired.
                   9550:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9551:                               of the resource that could not be rendered by the ssi
                   9552:                               call.
                   9553:    ssi_error_message   - The error string fetched from the ssi response
                   9554:                               in the event of an error.
                   9555: 
                   9556: 
                   9557: =head1 HANDLER SUBROUTINE
                   9558: 
                   9559: ssi_with_retries()
                   9560: 
                   9561: =head1 SUBROUTINES
                   9562: 
                   9563: =over
                   9564: 
                   9565: =item scantron_get_correction() : 
                   9566: 
                   9567:    Builds the interface screen to interact with the operator to fix a
                   9568:    specific error condition in a specific scanline
                   9569: 
                   9570:  Arguments:
                   9571:     $r           - Apache request object
                   9572:     $i           - number of the current scanline
                   9573:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9574:     $scan_config - hash ref as returned from &get_scantron_config()
                   9575:     $line        - full contents of the current scanline
                   9576:     $error       - error condition, valid values are
                   9577:                    'incorrectCODE', 'duplicateCODE',
                   9578:                    'doublebubble', 'missingbubble',
                   9579:                    'duplicateID', 'incorrectID'
                   9580:     $arg         - extra information needed
                   9581:        For errors:
                   9582:          - duplicateID   - paper number that this studentID was seen before on
                   9583:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9584:                            seen on before
                   9585:          - incorrectCODE - current incorrect CODE 
                   9586:          - doublebubble  - array ref of the bubble lines that have double
                   9587:                            bubble errors
                   9588:          - missingbubble - array ref of the bubble lines that have missing
                   9589:                            bubble errors
                   9590: 
                   9591: =item  scantron_get_maxbubble() : 
                   9592: 
1.582     raeburn  9593:    Arguments:
                   9594:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9595:                       failure to retrieve a navmap object.
                   9596:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9597:        calling routine should trap the error condition and display the warning
                   9598:        found in &navmap_errormsg().
                   9599: 
1.649     raeburn  9600:        $scantron_config - Reference to bubblesheet format configuration hash.
                   9601: 
1.531     jms      9602:    Returns the maximum number of bubble lines that are expected to
                   9603:    occur. Does this by walking the selected sequence rendering the
                   9604:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9605:    for what the current value of the problem counter is.
                   9606: 
                   9607:    Caches the results to $env{'form.scantron_maxbubble'},
                   9608:    $env{'form.scantron.bubble_lines.n'}, 
                   9609:    $env{'form.scantron.first_bubble_line.n'} and
                   9610:    $env{"form.scantron.sub_bubblelines.n"}
                   9611:    which are the total number of bubble, lines, the number of bubble
                   9612:    lines for response n and number of the first bubble line for response n,
                   9613:    and a comma separated list of numbers of bubble lines for sub-questions
                   9614:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9615: 
                   9616: 
                   9617: =item  scantron_validate_missingbubbles() : 
                   9618: 
                   9619:    Validates all scanlines in the selected file to not have any
                   9620:     answers that don't have bubbles that have not been verified
                   9621:     to be bubble free.
                   9622: 
                   9623: =item  scantron_process_students() : 
                   9624: 
                   9625:    Routine that does the actual grading of the bubble sheet information.
                   9626: 
                   9627:    The parsed scanline hash is added to %env 
                   9628: 
                   9629:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9630:    foreach resource , with the form data of
                   9631: 
                   9632: 	'submitted'     =>'scantron' 
                   9633: 	'grade_target'  =>'grade',
                   9634: 	'grade_username'=> username of student
                   9635: 	'grade_domain'  => domain of student
                   9636: 	'grade_courseid'=> of course
                   9637: 	'grade_symb'    => symb of resource to grade
                   9638: 
                   9639:     This triggers a grading pass. The problem grading code takes care
                   9640:     of converting the bubbled letter information (now in %env) into a
                   9641:     valid submission.
                   9642: 
                   9643: =item  scantron_upload_scantron_data() :
                   9644: 
                   9645:     Creates the screen for adding a new bubble sheet data file to a course.
                   9646: 
                   9647: =item  scantron_upload_scantron_data_save() : 
                   9648: 
                   9649:    Adds a provided bubble information data file to the course if user
                   9650:    has the correct privileges to do so. 
                   9651: 
                   9652: =item  valid_file() :
                   9653: 
                   9654:    Validates that the requested bubble data file exists in the course.
                   9655: 
                   9656: =item  scantron_download_scantron_data() : 
                   9657: 
                   9658:    Shows a list of the three internal files (original, corrected,
                   9659:    skipped) for a specific bubble sheet data file that exists in the
                   9660:    course.
                   9661: 
                   9662: =item  scantron_validate_ID() : 
                   9663: 
                   9664:    Validates all scanlines in the selected file to not have any
1.556     weissno  9665:    invalid or underspecified student/employee IDs
1.531     jms      9666: 
1.582     raeburn  9667: =item navmap_errormsg() :
                   9668: 
                   9669:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9670:    Should be called whenever the request to instantiate a navmap object fails.  
                   9671: 
1.531     jms      9672: =back
                   9673: 
                   9674: =cut

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