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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.655   ! raeburn     4: # $Id: grades.pm,v 1.654 2011/10/01 15:55:51 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',
1.655   ! raeburn  2025:                           list => 'List',
1.652     raeburn  2026:                           past => 'Paste Selection to List',
                   2027:                           high => 'Hightlight Attribute',
                   2028:                      );    
1.88      www      2029: #
                   2030: # Print out the keyword options line
                   2031: #
1.41      ng       2032: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2033: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655   ! raeburn  2034: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2035: <a href="#" onmousedown="javascript:getSel(); return false"
1.652     raeburn  2036:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2037: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2038: KEYWORDS
1.88      www      2039: #
                   2040: # Load the other essays for similarity check
                   2041: #
1.324     albertel 2042:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2043: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2044: 	    $apath=&escape($apath);
1.88      www      2045: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2046: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2047:         }
                   2048:     }
1.44      ng       2049: 
1.441     www      2050: # This is where output for one specific student would start
1.592     bisitz   2051:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2052:     $request->print(
                   2053:         "\n\n"
                   2054:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2055:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2056:        ."\n"
                   2057:     );
1.441     www      2058: 
1.592     bisitz   2059:     # Show additional functions if allowed
                   2060:     if ($perm{'vgr'}) {
                   2061:         $request->print(
                   2062:             &Apache::loncommon::track_student_link(
                   2063:                 &mt('View recent activity'),
                   2064:                 $uname,$udom,'check')
                   2065:            .' '
                   2066:         );
                   2067:     }
                   2068:     if ($perm{'opa'}) {
                   2069:         $request->print(
                   2070:             &Apache::loncommon::pprmlink(
                   2071:                 &mt('Set/Change parameters'),
                   2072:                 $uname,$udom,$symb,'check'));
                   2073:     }
                   2074: 
                   2075:     # Show Problem
1.257     albertel 2076:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2077: 	my $mode;
1.257     albertel 2078: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2079: 	    $mode='both';
1.257     albertel 2080: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2081: 	    $mode='text';
1.257     albertel 2082: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2083: 	    $mode='answer';
                   2084: 	}
1.329     albertel 2085: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2086: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2087:     }
1.144     albertel 2088: 
1.257     albertel 2089:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2090:     my $res_error;
                   2091:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2092:     if ($res_error) {
                   2093:         $request->print(&navmap_errormsg());
                   2094:         return;
                   2095:     }
1.41      ng       2096: 
1.44      ng       2097:     # Display student info
1.41      ng       2098:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2099: 
                   2100:     my $result='<div class="LC_Box">'
                   2101:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2102:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2103:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2104: #    if ($env{'form.handgrade'} eq 'no') {
                   2105:     if (1) {
1.588     bisitz   2106:         $result.='<p class="LC_info">'
                   2107:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2108:                 ."</p>\n";
1.469     albertel 2109:     }
                   2110: 
1.118     ng       2111:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2112:     my $fullname;
                   2113:     my $col_fullnames = [];
1.624     www      2114: #    if ($env{'form.handgrade'} eq 'yes') {
                   2115:     if (1) {
1.464     albertel 2116: 	(my $sub_result,$fullname,$col_fullnames)=
                   2117: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2118: 				 $counter);
                   2119: 	$result.=$sub_result;
1.41      ng       2120:     }
1.44      ng       2121:     $request->print($result."\n");
1.588     bisitz   2122: 
1.44      ng       2123:     # print student answer/submission
1.588     bisitz   2124:     # Options are (1) Handgraded submission only
1.44      ng       2125:     #             (2) Last submission, includes submission that is not handgraded 
                   2126:     #                  (for multi-response type part)
                   2127:     #             (3) Last submission plus the parts info
                   2128:     #             (4) The whole record for this student
1.257     albertel 2129:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2130: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2131: 	
                   2132: 	my $lastsubonly;
                   2133: 
1.588     bisitz   2134:         if ($$timestamp eq '') {
                   2135:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2136:         } else {
1.592     bisitz   2137:             $lastsubonly =
                   2138:                 '<div class="LC_grade_submissions_body">'
                   2139:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2140: 
1.151     albertel 2141: 	    my %seenparts;
1.375     albertel 2142: 	    my @part_response_id = &flatten_responseType($responseType);
                   2143: 	    foreach my $part (@part_response_id) {
1.393     albertel 2144: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2145: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2146: 
1.375     albertel 2147: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2148: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2149: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2150: 		    if (exists($seenparts{$partid})) { next; }
                   2151: 		    $seenparts{$partid}=1;
1.207     albertel 2152: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2153: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2154: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2155: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2156: 			'\');" target="_self">'.
1.257     albertel 2157: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2158: 		    $request->print($submitby);
                   2159: 		    next;
                   2160: 		}
                   2161: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2162: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2163:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2164:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2165:                         ' <span class="LC_internal_info">'.
1.623     www      2166:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2167:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2168: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2169: 		    next;
                   2170: 		}
1.468     albertel 2171: 		foreach my $submission (@$string) {
                   2172: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2173: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2174: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2175: 		    # Similarity check
                   2176: 		    my $similar='';
1.640     raeburn  2177:                     my ($type,$trial,$rndseed);
                   2178:                     if ($hide eq 'rand') {
                   2179:                         $type = 'randomizetry';
                   2180:                         $trial = $record{"resource.$partid.tries"};
                   2181:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2182:                     }
1.257     albertel 2183: 		    if($env{'form.checkPlag'}){
1.151     albertel 2184: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2185: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2186: 			if ($osim) {
                   2187: 			    $osim=int($osim*100.0);
1.426     albertel 2188: 			    my %old_course_desc = 
                   2189: 				&Apache::lonnet::coursedescription($ocrsid,
                   2190: 								   {'one_time' => 1});
                   2191: 
1.640     raeburn  2192:                             if ($hide eq 'anon') {
1.596     raeburn  2193:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2194:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2195:                             } else {
                   2196: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2197: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2198: 				        $osim,
                   2199: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2200: 				        $old_course_desc{'description'},
                   2201: 				        $old_course_desc{'num'},
                   2202: 				        $old_course_desc{'domain'}).
                   2203: 				    '</span></h3><blockquote><i>'.
                   2204: 				    &keywords_highlight($oessay).
                   2205: 				    '</i></blockquote><hr />';
                   2206:                             }
1.151     albertel 2207: 			}
1.150     albertel 2208: 		    }
1.640     raeburn  2209: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2210:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2211: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2212: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2213: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2214: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2215:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2216:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2217:                             ' <span class="LC_internal_info">'.
1.623     www      2218:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2219:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2220: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2221: 			if (@$files) {
1.640     raeburn  2222:                             if ($hide eq 'anon') {
1.596     raeburn  2223:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2224:                             } else {
                   2225:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2226:                                 foreach my $file (@$files) {
                   2227:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2228:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2229:                                 }
                   2230:                             }
1.236     albertel 2231: 			    $lastsubonly.='<br />';
1.41      ng       2232: 			}
1.640     raeburn  2233:                         if ($hide eq 'anon') {
1.596     raeburn  2234:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2235:                         } else {
                   2236: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2237: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2238: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2239:                         }
1.151     albertel 2240: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2241: 			$lastsubonly.='</div>';
1.41      ng       2242: 		    }
                   2243: 		}
                   2244: 	    }
1.588     bisitz   2245: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2246: 	}
                   2247: 	$request->print($lastsubonly);
1.468     albertel 2248:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2249:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2250: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2251:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2252: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2253: 								 $env{'request.course.id'},
1.44      ng       2254: 								 $last,'.submission',
                   2255: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2256:     }
1.121     ng       2257:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2258: 	.$udom.'" />'."\n");
1.44      ng       2259:     # return if view submission with no grading option
1.618     www      2260:     if (!&canmodify($usec)) {
1.633     www      2261: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2262: 	return;
1.180     albertel 2263:     } else {
1.468     albertel 2264: 	$request->print('</div>'."\n");
1.41      ng       2265:     }
1.33      ng       2266: 
1.121     ng       2267:     # essay grading message center
1.624     www      2268: #    if ($env{'form.handgrade'} eq 'yes') {
                   2269:     if (1) {
1.468     albertel 2270: 	my $result='<div class="LC_grade_message_center">';
                   2271:     
                   2272: 	$result.='<div class="LC_grade_message_center_header">'.
                   2273: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2274: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2275: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2276: 	if (scalar(@$col_fullnames) > 0) {
                   2277: 	    my $lastone = pop(@$col_fullnames);
                   2278: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2279: 	}
                   2280: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2281: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2282: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2283: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2284: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2285: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2286: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2287: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2288: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2289: 	    '<br />&nbsp;('.
1.468     albertel 2290: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2291: 	$result.='</div></div>';
1.121     ng       2292: 	$request->print($result);
1.118     ng       2293:     }
1.41      ng       2294: 
                   2295:     my %seen = ();
                   2296:     my @partlist;
1.129     ng       2297:     my @gradePartRespid;
1.375     albertel 2298:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2299:     $request->print(
1.588     bisitz   2300:         '<div class="LC_Box">'
                   2301:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2302:     );
1.592     bisitz   2303:     $request->print(&gradeBox_start());
1.375     albertel 2304:     foreach my $part_response_id (@part_response_id) {
                   2305:     	my ($partid,$respid) = @{ $part_response_id };
                   2306: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2307: 	next if ($seen{$partid} > 0);
1.41      ng       2308: 	$seen{$partid}++;
1.393     albertel 2309: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2310: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2311: 	push(@partlist,$partid);
                   2312: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2313: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2314:     }
1.585     bisitz   2315:     $request->print(&gradeBox_end()); # </div>
                   2316:     $request->print('</div>');
1.468     albertel 2317: 
                   2318:     $request->print('<div class="LC_grade_info_links">');
                   2319:     $request->print('</div>');
                   2320: 
1.45      ng       2321:     $result='<input type="hidden" name="partlist'.$counter.
                   2322: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2323:     $result.='<input type="hidden" name="gradePartRespid'.
                   2324: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2325:     my $ctr = 0;
                   2326:     while ($ctr < scalar(@partlist)) {
                   2327: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2328: 	    $partlist[$ctr].'" />'."\n";
                   2329: 	$ctr++;
                   2330:     }
1.468     albertel 2331:     $request->print($result.''."\n");
1.41      ng       2332: 
1.441     www      2333: # Done with printing info for one student
                   2334: 
1.468     albertel 2335:     $request->print('</div>');#LC_grade_show_user
1.441     www      2336: 
                   2337: 
1.41      ng       2338:     # print end of form
                   2339:     if ($counter == $total) {
1.592     bisitz   2340:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2341: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2342: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2343: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2344: 	my $ntstu ='<select name="NTSTU">'.
                   2345: 	    '<option>1</option><option>2</option>'.
                   2346: 	    '<option>3</option><option>5</option>'.
                   2347: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2348: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2349: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2350:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2351: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2352: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2353: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2354: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2355:         $endform.='<span class="LC_warning">'.
                   2356:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2357:                   '</span>'."\n" ;
1.349     albertel 2358:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2359:             "' name='increment' />";
1.485     albertel 2360: 	$endform.='</td></tr></table></form>';
1.41      ng       2361: 	$request->print($endform);
                   2362:     }
                   2363:     return '';
1.38      ng       2364: }
                   2365: 
1.464     albertel 2366: sub check_collaborators {
                   2367:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2368:     my ($result,@col_fullnames);
                   2369:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2370:     foreach my $part (keys(%$handgrade)) {
                   2371: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2372: 					'.maxcollaborators',
                   2373: 					$symb,$udom,$uname);
                   2374: 	next if ($ncol <= 0);
                   2375: 	$part =~ s/\_/\./g;
                   2376: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2377: 	my (@good_collaborators, @bad_collaborators);
                   2378: 	foreach my $possible_collaborator
1.630     www      2379: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2380: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2381: 	    next if ($possible_collaborator eq '');
1.631     www      2382: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2383: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2384: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2385: 	    # Doing this grep allows 'fuzzy' specification
                   2386: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2387: 			       keys(%$classlist));
                   2388: 	    if (! scalar(@matches)) {
                   2389: 		push(@bad_collaborators, $possible_collaborator);
                   2390: 	    } else {
                   2391: 		push(@good_collaborators, @matches);
                   2392: 	    }
                   2393: 	}
                   2394: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2395: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2396: 	    foreach my $name (@good_collaborators) {
                   2397: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2398: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2399: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2400: 	    }
1.630     www      2401: 	    $result.='</ol><br />'."\n";
1.466     albertel 2402: 	    my ($part)=split(/\./,$part);
1.464     albertel 2403: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2404: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2405: 		"\n";
                   2406: 	}
                   2407: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2408: 	    $result.='<div class="LC_warning">';
1.464     albertel 2409: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2410: 	    $result .= '</div>';
                   2411: 	}         
                   2412: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2413: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2414: 	    $result .= &mt('This student has submitted too many '.
                   2415: 		'collaborators.  Maximum is [_1].',$ncol);
                   2416: 	    $result .= '</div>';
                   2417: 	}
                   2418:     }
                   2419:     return ($result,$fullname,\@col_fullnames);
                   2420: }
                   2421: 
1.44      ng       2422: #--- Retrieve the last submission for all the parts
1.38      ng       2423: sub get_last_submission {
1.119     ng       2424:     my ($returnhash)=@_;
1.596     raeburn  2425:     my (@string,$timestamp,%lasthidden);
1.119     ng       2426:     if ($$returnhash{'version'}) {
1.46      ng       2427: 	my %lasthash=();
                   2428: 	my ($version);
1.119     ng       2429: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2430: 	    foreach my $key (sort(split(/\:/,
                   2431: 					$$returnhash{$version.':keys'}))) {
                   2432: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2433: 		$timestamp = 
1.545     raeburn  2434: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2435: 	    }
                   2436: 	}
1.640     raeburn  2437:         my (%typeparts,%randombytry);
1.596     raeburn  2438:         my $showsurv = 
                   2439:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2440:         foreach my $key (sort(keys(%lasthash))) {
                   2441:             if ($key =~ /\.type$/) {
                   2442:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2443:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2444:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2445:                     my ($ign,@parts) = split(/\./,$key);
                   2446:                     pop(@parts);
1.641     raeburn  2447:                     my $id = join('.',@parts);
1.640     raeburn  2448:                     if ($lasthash{$key} eq 'randomizetry') {
                   2449:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2450:                     } else {
                   2451:                         unless ($showsurv) {
                   2452:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2453:                         }
1.596     raeburn  2454:                     }
                   2455:                     delete($lasthash{$key});
                   2456:                 }
                   2457:             }
                   2458:         }
                   2459:         my @hidden = keys(%typeparts);
1.640     raeburn  2460:         my @randomize = keys(%randombytry);
1.397     albertel 2461: 	foreach my $key (keys(%lasthash)) {
                   2462: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2463:             my $hide;
                   2464:             if (@hidden) {
                   2465:                 foreach my $id (@hidden) {
                   2466:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2467:                         $hide = 'anon';
1.596     raeburn  2468:                         last;
                   2469:                     }
                   2470:                 }
                   2471:             }
1.640     raeburn  2472:             unless ($hide) {
                   2473:                 if (@randomize) {
                   2474:                     foreach my $id (@hidden) {
                   2475:                         if ($key =~ /^\Q$id\E/) {
                   2476:                             $hide = 'rand';
                   2477:                             last;
                   2478:                         }
                   2479:                     }
                   2480:                 }
                   2481:             }
1.397     albertel 2482: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2483: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2484: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2485: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2486: 	}
                   2487:     }
1.397     albertel 2488:     if (!@string) {
                   2489: 	$string[0] =
1.539     riegler  2490: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2491:     }
                   2492:     return (\@string,\$timestamp);
1.38      ng       2493: }
1.35      ng       2494: 
1.44      ng       2495: #--- High light keywords, with style choosen by user.
1.38      ng       2496: sub keywords_highlight {
1.44      ng       2497:     my $string    = shift;
1.257     albertel 2498:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2499:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2500:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2501:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2502:     foreach my $keyword (@keylist) {
                   2503: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2504:     }
                   2505:     return $string;
1.38      ng       2506: }
1.36      ng       2507: 
1.44      ng       2508: #--- Called from submission routine
1.38      ng       2509: sub processHandGrade {
1.608     www      2510:     my ($request,$symb) = @_;
1.324     albertel 2511:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2512:     my $button = $env{'form.gradeOpt'};
                   2513:     my $ngrade = $env{'form.NCT'};
                   2514:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2515:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2516:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2517: 
1.44      ng       2518:     if ($button eq 'Save & Next') {
                   2519: 	my $ctr = 0;
                   2520: 	while ($ctr < $ngrade) {
1.257     albertel 2521: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2522: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2523: 	    if ($errorflag eq 'no_score') {
                   2524: 		$ctr++;
                   2525: 		next;
                   2526: 	    }
1.104     albertel 2527: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2528: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2529: 		$ctr++;
                   2530: 		next;
                   2531: 	    }
1.257     albertel 2532: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2533: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2534: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2535:             my ($feedurl,$showsymb) =
                   2536: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2537: 	    my $messagetail;
1.62      albertel 2538: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2539: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2540: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2541: 		$subject.=' ['.$restitle.']';
1.44      ng       2542: 		my (@msgnum) = split(/,/,$includemsg);
                   2543: 		foreach (@msgnum) {
1.257     albertel 2544: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2545: 		}
1.80      ng       2546: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2547: 		if ($env{'form.withgrades'.$ctr}) {
                   2548: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2549: 		    $messagetail = " for <a href=\"".
1.605     www      2550: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2551: 		}
                   2552: 		$msgstatus = 
                   2553:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2554: 						     $message.$messagetail,
1.418     albertel 2555:                                                      undef,$feedurl,undef,
1.386     raeburn  2556:                                                      undef,undef,$showsymb,
                   2557:                                                      $restitle);
1.574     bisitz   2558: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2559: 				$msgstatus.'<br />');
1.44      ng       2560: 	    }
1.257     albertel 2561: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2562: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2563: 		foreach my $collabstr (@collabstrs) {
                   2564: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2565: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2566: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2567: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2568: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2569: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2570: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2571: 			    next;
1.418     albertel 2572: 			} elsif ($message ne '') {
                   2573: 			    my ($baseurl,$showsymb) = 
                   2574: 				&get_feedurl_and_symb($symb,$collaborator,
                   2575: 						      $udom);
                   2576: 			    if ($env{'form.withgrades'.$ctr}) {
                   2577: 				$messagetail = " for <a href=\"".
1.605     www      2578:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2579: 			    }
1.418     albertel 2580: 			    $msgstatus = 
                   2581: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2582: 			}
1.44      ng       2583: 		    }
                   2584: 		}
                   2585: 	    }
                   2586: 	    $ctr++;
                   2587: 	}
                   2588:     }
                   2589: 
1.624     www      2590: #    if ($env{'form.handgrade'} eq 'yes') {
                   2591:     if (1) {
1.119     ng       2592: 	# Keywords sorted in alphabatical order
1.257     albertel 2593: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2594: 	my %keyhash = ();
1.257     albertel 2595: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2596: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2597: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2598: 	$env{'form.keywords'} = join(' ',@keywords);
                   2599: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2600: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2601: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2602: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2603: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2604: 
                   2605: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2606: 	# New messages are saved in env for the next student.
1.119     ng       2607: 	# All messages are saved in nohist_handgrade.db
                   2608: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2609: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2610: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2611: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2612: 		$idx++;
                   2613: 	    }
                   2614: 	    $ctr++;
1.41      ng       2615: 	}
1.119     ng       2616: 	$ctr = 0;
                   2617: 	while ($ctr < $ngrade) {
1.257     albertel 2618: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2619: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2620: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2621: 		$idx++;
                   2622: 	    }
                   2623: 	    $ctr++;
1.41      ng       2624: 	}
1.257     albertel 2625: 	$env{'form.savemsgN'} = --$idx;
                   2626: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2627: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2628: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2629:     }
1.44      ng       2630:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2631:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2632:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2633: 	my ($ctr,$total) = (0,0);
                   2634: 	while ($ctr < $ngrade) {
1.257     albertel 2635: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2636: 	    $ctr++;
                   2637: 	}
1.257     albertel 2638: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2639: 	$ctr = 0;
                   2640: 	while ($ctr < $total) {
1.257     albertel 2641: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2642: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2643: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2644: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2645: 	    $ctr++;
                   2646: 	}
                   2647: 	return '';
                   2648:     }
1.36      ng       2649: 
1.44      ng       2650:     # Get the next/previous one or group of students
1.257     albertel 2651:     my $firststu = $env{'form.unamedom0'};
                   2652:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2653:     my $ctr = 2;
1.41      ng       2654:     while ($laststu eq '') {
1.257     albertel 2655: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2656: 	$ctr++;
                   2657: 	$laststu = $firststu if ($ctr > $ngrade);
                   2658:     }
1.44      ng       2659: 
1.41      ng       2660:     my (@parsedlist,@nextlist);
                   2661:     my ($nextflg) = 0;
1.524     raeburn  2662:     foreach my $item (sort 
1.294     albertel 2663: 	     {
                   2664: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2665: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2666: 		 }
                   2667: 		 return $a cmp $b;
                   2668: 	     } (keys(%$fullname))) {
1.605     www      2669: # FIXME: this is fishy, looks like the button label
1.41      ng       2670: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2671: 	    push(@parsedlist,$item);
1.41      ng       2672: 	}
1.524     raeburn  2673: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2674: 	if ($button eq 'Previous') {
1.524     raeburn  2675: 	    last if ($item eq $firststu);
                   2676: 	    push(@parsedlist,$item);
1.41      ng       2677: 	}
                   2678:     }
                   2679:     $ctr = 0;
1.605     www      2680: # FIXME: this is fishy, looks like the button label
1.41      ng       2681:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2682:     my $res_error;
                   2683:     my ($partlist) = &response_type($symb,\$res_error);
                   2684:     if ($res_error) {
                   2685:         $request->print(&navmap_errormsg());
                   2686:         return;
                   2687:     }
1.41      ng       2688:     foreach my $student (@parsedlist) {
1.257     albertel 2689: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2690: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2691: 	
                   2692: 	if ($submitonly eq 'queued') {
                   2693: 	    my %queue_status = 
                   2694: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2695: 							$udom,$uname);
                   2696: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2697: 	}
                   2698: 
1.156     albertel 2699: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2700: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2701: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2702: 	    my $submitted = 0;
1.248     albertel 2703: 	    my $ungraded = 0;
                   2704: 	    my $incorrect = 0;
1.524     raeburn  2705: 	    foreach my $item (keys(%status)) {
                   2706: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2707: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2708: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2709: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2710: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2711: 		    $submitted = 0;
                   2712: 		}
1.41      ng       2713: 	    }
1.156     albertel 2714: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2715: 				     $submitonly eq 'incorrect' ||
                   2716: 				     $submitonly eq 'graded'));
1.248     albertel 2717: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2718: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2719: 	}
1.524     raeburn  2720: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2721: 	last if ($ctr == $ntstu);
1.41      ng       2722: 	$ctr++;
                   2723:     }
1.36      ng       2724: 
1.41      ng       2725:     $ctr = 0;
                   2726:     my $total = scalar(@nextlist)-1;
1.39      ng       2727: 
1.524     raeburn  2728:     foreach (sort(@nextlist)) {
1.41      ng       2729: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2730: 	$env{'form.student'}  = $uname;
                   2731: 	$env{'form.userdom'}  = $udom;
                   2732: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2733: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2734: 	$ctr++;
                   2735:     }
                   2736:     if ($total < 0) {
1.653     raeburn  2737: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2738: 	$request->print($the_end);
                   2739:     }
                   2740:     return '';
1.38      ng       2741: }
1.36      ng       2742: 
1.44      ng       2743: #---- Save the score and award for each student, if changed
1.38      ng       2744: sub saveHandGrade {
1.324     albertel 2745:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2746:     my @version_parts;
1.104     albertel 2747:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2748: 					   $env{'request.course.id'});
1.104     albertel 2749:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2750:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2751:     my @parts_graded;
1.77      ng       2752:     my %newrecord  = ();
                   2753:     my ($pts,$wgt) = ('','');
1.269     raeburn  2754:     my %aggregate = ();
                   2755:     my $aggregateflag = 0;
1.301     albertel 2756:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2757:     foreach my $new_part (@parts) {
1.337     banghart 2758: 	#collaborator ($submi may vary for different parts
1.259     banghart 2759: 	if ($submitter && $new_part ne $part) { next; }
                   2760: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2761: 	if ($dropMenu eq 'excused') {
1.259     banghart 2762: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2763: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2764: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2765: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2766: 		}
1.364     banghart 2767: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2768: 	    }
1.125     ng       2769: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2770: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2771: 	    foreach my $key (keys(%record)) {
1.259     banghart 2772: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2773: 	    }
1.259     banghart 2774: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2775: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2776:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2777: 
                   2778:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2779: 					       [$new_part]);
                   2780:             my $aggtries =$totaltries;
1.269     raeburn  2781:             if ($last_resets{$new_part}) {
1.270     albertel 2782:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2783: 					   $new_part);
1.269     raeburn  2784:             }
1.270     albertel 2785: 
                   2786:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2787:             if ($aggtries > 0) {
1.327     albertel 2788:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2789:                 $aggregateflag = 1;
                   2790:             }
1.125     ng       2791: 	} elsif ($dropMenu eq '') {
1.259     banghart 2792: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2793: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2794: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2795: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2796: 		next;
                   2797: 	    }
1.259     banghart 2798: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2799: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2800: 	    my $partial= $pts/$wgt;
1.259     banghart 2801: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2802: 		#do not update score for part if not changed.
1.346     banghart 2803:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2804: 		next;
1.251     banghart 2805: 	    } else {
1.524     raeburn  2806: 	        push(@parts_graded,$new_part);
1.153     albertel 2807: 	    }
1.259     banghart 2808: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2809: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2810: 	    }
1.259     banghart 2811: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2812: 	    if ($partial == 0) {
1.153     albertel 2813: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2814: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2815: 		}
1.41      ng       2816: 	    } else {
1.153     albertel 2817: 		if ($record{$reckey} ne 'correct_by_override') {
                   2818: 		    $newrecord{$reckey} = 'correct_by_override';
                   2819: 		}
                   2820: 	    }	    
                   2821: 	    if ($submitter && 
1.259     banghart 2822: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2823: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2824: 	    }
1.259     banghart 2825: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2826: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2827: 	}
1.259     banghart 2828: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2829: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2830: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2831: 	        $dropMenu eq 'reset status')
                   2832: 	   {
1.524     raeburn  2833: 	    push(@version_parts,$new_part);
1.259     banghart 2834: 	}
1.41      ng       2835:     }
1.301     albertel 2836:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2837:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2838: 
1.344     albertel 2839:     if (%newrecord) {
                   2840:         if (@version_parts) {
1.364     banghart 2841:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2842:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2843: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2844: 	    foreach my $new_part (@version_parts) {
                   2845: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2846: 				$new_part,\%newrecord);
                   2847: 	    }
1.259     banghart 2848:         }
1.44      ng       2849: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2850: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2851: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2852: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2853:     }
1.269     raeburn  2854:     if ($aggregateflag) {
                   2855:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2856: 			      $cdom,$cnum);
1.269     raeburn  2857:     }
1.301     albertel 2858:     return ('',$pts,$wgt);
1.36      ng       2859: }
1.322     albertel 2860: 
1.380     albertel 2861: sub check_and_remove_from_queue {
                   2862:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2863:     my @ungraded_parts;
                   2864:     foreach my $part (@{$parts}) {
                   2865: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2866: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2867: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2868: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2869: 		) {
                   2870: 	    push(@ungraded_parts, $part);
                   2871: 	}
                   2872:     }
                   2873:     if ( !@ungraded_parts ) {
                   2874: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2875: 					       $cnum,$domain,$stuname);
                   2876:     }
                   2877: }
                   2878: 
1.337     banghart 2879: sub handback_files {
                   2880:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2881:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2882:     my $res_error;
                   2883:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2884:     if ($res_error) {
                   2885:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2886:         return;
                   2887:     }
1.654     raeburn  2888:     my @handedback;
                   2889:     my $file_msg;
1.375     albertel 2890:     my @part_response_id = &flatten_responseType($responseType);
                   2891:     foreach my $part_response_id (@part_response_id) {
                   2892:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2893: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  2894:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   2895:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   2896:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   2897:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   2898:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 2899:                     my ($directory,$answer_file) = 
1.654     raeburn  2900:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 2901:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2902: 		        &file_name_version_ext($answer_file);
1.355     banghart 2903: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2904:                     my $getpropath = 1;
                   2905: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2906: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2907:                     # fix file name
                   2908:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2909:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  2910:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 2911:             	                                $save_file_name);
1.337     banghart 2912:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2913:                         $request->print('<br /><span class="LC_error">'.
                   2914:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  2915:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  2916:                                         '</span>');
1.356     banghart 2917:                     } else {
1.360     banghart 2918:                         # mark the file as read only
1.654     raeburn  2919:                         push(@handedback,$save_file_name);
1.367     albertel 2920: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2921: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2922: 			}
                   2923:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  2924: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 2925:                     }
1.654     raeburn  2926:                     $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 2927:                 }
                   2928:             }
                   2929:         }
1.654     raeburn  2930:     }
                   2931:     if (@handedback > 0) {
                   2932:         $request->print('<br />');
                   2933:         my @what = ($symb,$env{'request.course.id'},'handback');
                   2934:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   2935:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   2936:         my ($subject,$message);
                   2937:         if (scalar(@handedback) == 1) {
                   2938:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   2939:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   2940:         } else {
                   2941:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   2942:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   2943:         }
                   2944:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   2945:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   2946:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   2947:         my ($feedurl,$showsymb) =
                   2948:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   2949:         my $restitle = &Apache::lonnet::gettitle($symb);
                   2950:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   2951:         my $msgstatus =
                   2952:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   2953:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   2954:                  $restitle);
                   2955:         if ($msgstatus) {
                   2956:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   2957:         }
                   2958:     }
1.338     banghart 2959:     return;
1.337     banghart 2960: }
                   2961: 
1.418     albertel 2962: sub get_feedurl_and_symb {
                   2963:     my ($symb,$uname,$udom) = @_;
                   2964:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2965:     $url = &Apache::lonnet::clutter($url);
                   2966:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2967: 					$symb,$udom,$uname);
                   2968:     if ($encrypturl =~ /^yes$/i) {
                   2969: 	&Apache::lonenc::encrypted(\$url,1);
                   2970: 	&Apache::lonenc::encrypted(\$symb,1);
                   2971:     }
                   2972:     return ($url,$symb);
                   2973: }
                   2974: 
1.313     banghart 2975: sub get_submitted_files {
                   2976:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2977:     my @files;
                   2978:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2979:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2980:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2981:     	    push(@files,$file_url.$file);
                   2982:         }
                   2983:     }
                   2984:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2985:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2986:     }
                   2987:     return (\@files);
                   2988: }
1.322     albertel 2989: 
1.269     raeburn  2990: # ----------- Provides number of tries since last reset.
                   2991: sub get_num_tries {
                   2992:     my ($record,$last_reset,$part) = @_;
                   2993:     my $timestamp = '';
                   2994:     my $num_tries = 0;
                   2995:     if ($$record{'version'}) {
                   2996:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2997:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2998:                 $timestamp = $$record{$version.':timestamp'};
                   2999:                 if ($timestamp > $last_reset) {
                   3000:                     $num_tries ++;
                   3001:                 } else {
                   3002:                     last;
                   3003:                 }
                   3004:             }
                   3005:         }
                   3006:     }
                   3007:     return $num_tries;
                   3008: }
                   3009: 
                   3010: # ----------- Determine decrements required in aggregate totals 
                   3011: sub decrement_aggs {
                   3012:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3013:     my %decrement = (
                   3014:                         attempts => 0,
                   3015:                         users => 0,
                   3016:                         correct => 0
                   3017:                     );
                   3018:     $decrement{'attempts'} = $aggtries;
                   3019:     if ($solvedstatus =~ /^correct/) {
                   3020:         $decrement{'correct'} = 1;
                   3021:     }
                   3022:     if ($aggtries == $totaltries) {
                   3023:         $decrement{'users'} = 1;
                   3024:     }
1.524     raeburn  3025:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3026:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3027:     }
                   3028:     return;
                   3029: }
                   3030: 
                   3031: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3032: sub get_last_resets {
1.270     albertel 3033:     my ($symb,$courseid,$partids) =@_;
                   3034:     my %last_resets;
1.269     raeburn  3035:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3036:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3037:     my @keys;
                   3038:     foreach my $part (@{$partids}) {
                   3039: 	push(@keys,"$symb\0$part\0resettime");
                   3040:     }
                   3041:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3042: 				     $cdom,$cname);
                   3043:     foreach my $part (@{$partids}) {
                   3044: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3045:     }
1.270     albertel 3046:     return %last_resets;
1.269     raeburn  3047: }
                   3048: 
1.251     banghart 3049: # ----------- Handles creating versions for portfolio files as answers
                   3050: sub version_portfiles {
1.343     banghart 3051:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3052:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3053:     my @returned_keys;
1.255     banghart 3054:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3055:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3056:     foreach my $key (keys(%$record)) {
1.259     banghart 3057:         my $new_portfiles;
1.263     banghart 3058:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3059:             my @versioned_portfiles;
1.367     albertel 3060:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3061:             foreach my $file (@portfiles) {
1.306     banghart 3062:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3063:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3064: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3065: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3066:                 my $getpropath = 1;    
                   3067:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3068:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3069:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3070:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3071:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3072:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3073:                         [$directory.$new_answer],
1.306     banghart 3074:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3075:                 }
1.252     banghart 3076:             }
1.343     banghart 3077:             $$record{$key} = join(',',@versioned_portfiles);
                   3078:             push(@returned_keys,$key);
1.251     banghart 3079:         }
                   3080:     } 
1.343     banghart 3081:     return (@returned_keys);   
1.305     banghart 3082: }
                   3083: 
1.307     banghart 3084: sub get_next_version {
1.341     banghart 3085:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3086:     my $version;
                   3087:     foreach my $row (@$dir_list) {
                   3088:         my ($file) = split(/\&/,$row,2);
                   3089:         my ($file_name,$file_version,$file_ext) =
                   3090: 	    &file_name_version_ext($file);
                   3091:         if (($file_name eq $answer_name) && 
                   3092: 	    ($file_ext eq $answer_ext)) {
                   3093:                 # gets here if filename and extension match, regardless of version
                   3094:                 if ($file_version ne '') {
                   3095:                 # a versioned file is found  so save it for later
                   3096:                 if ($file_version > $version) {
                   3097: 		    $version = $file_version;
                   3098: 	        }
                   3099:             }
                   3100:         }
                   3101:     } 
                   3102:     $version ++;
                   3103:     return($version);
                   3104: }
                   3105: 
1.305     banghart 3106: sub version_selected_portfile {
1.306     banghart 3107:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3108:     my ($answer_name,$answer_ver,$answer_ext) =
                   3109:         &file_name_version_ext($file_name);
                   3110:     my $new_answer;
                   3111:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3112:     if($env{'form.copy'} eq '-1') {
                   3113:         $new_answer = 'problem getting file';
                   3114:     } else {
                   3115:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3116:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3117:                             $stu_name,$domain,'copy',
                   3118: 		        '/portfolio'.$directory.$new_answer);
                   3119:     }    
                   3120:     return ($new_answer);
1.251     banghart 3121: }
                   3122: 
1.304     albertel 3123: sub file_name_version_ext {
                   3124:     my ($file)=@_;
                   3125:     my @file_parts = split(/\./, $file);
                   3126:     my ($name,$version,$ext);
                   3127:     if (@file_parts > 1) {
                   3128: 	$ext=pop(@file_parts);
                   3129: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3130: 	    $version=pop(@file_parts);
                   3131: 	}
                   3132: 	$name=join('.',@file_parts);
                   3133:     } else {
                   3134: 	$name=join('.',@file_parts);
                   3135:     }
                   3136:     return($name,$version,$ext);
                   3137: }
                   3138: 
1.44      ng       3139: #--------------------------------------------------------------------------------------
                   3140: #
                   3141: #-------------------------- Next few routines handles grading by section or whole class
                   3142: #
                   3143: #--- Javascript to handle grading by section or whole class
1.42      ng       3144: sub viewgrades_js {
                   3145:     my ($request) = shift;
                   3146: 
1.539     riegler  3147:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3149:    function writePoint(partid,weight,point) {
1.125     ng       3150: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3151: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3152: 	if (point == "textval") {
1.125     ng       3153: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3154: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3155: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3156: 		var resetbox = false;
                   3157: 		for (var i=0; i<radioButton.length; i++) {
                   3158: 		    if (radioButton[i].checked) {
                   3159: 			textbox.value = i;
                   3160: 			resetbox = true;
                   3161: 		    }
                   3162: 		}
                   3163: 		if (!resetbox) {
                   3164: 		    textbox.value = "";
                   3165: 		}
                   3166: 		return;
                   3167: 	    }
1.109     matthew  3168: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3169: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3170: 				   ") greater than the weight for the part. Accept?");
                   3171: 		if (resp == false) {
                   3172: 		    textbox.value = "";
                   3173: 		    return;
                   3174: 		}
                   3175: 	    }
1.42      ng       3176: 	    for (var i=0; i<radioButton.length; i++) {
                   3177: 		radioButton[i].checked=false;
1.109     matthew  3178: 		if (parseFloat(point) == i) {
1.42      ng       3179: 		    radioButton[i].checked=true;
                   3180: 		}
                   3181: 	    }
1.41      ng       3182: 
1.42      ng       3183: 	} else {
1.125     ng       3184: 	    textbox.value = parseFloat(point);
1.42      ng       3185: 	}
1.41      ng       3186: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3187: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3188: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3189: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3190: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3191: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3192: 	    if (saveval != "correct") {
                   3193: 		scorename.value = point;
1.43      ng       3194: 		if (selname[0].selected != true) {
                   3195: 		    selname[0].selected = true;
                   3196: 		}
1.42      ng       3197: 	    }
                   3198: 	}
1.125     ng       3199: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3200:     }
                   3201: 
                   3202:     function writeRadText(partid,weight) {
1.125     ng       3203: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3204: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3205:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3206: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3207: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3208: 	    for (var i=0; i<radioButton.length; i++) {
                   3209: 		radioButton[i].checked=false;
                   3210: 
                   3211: 	    }
                   3212: 	    textbox.value = "";
                   3213: 
                   3214: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3215: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3216: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3217: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3218: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3219: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3220: 		if ((saveval != "correct") || override) {
1.42      ng       3221: 		    scorename.value = "";
1.125     ng       3222: 		    if (selval[1].selected) {
                   3223: 			selname[1].selected = true;
                   3224: 		    } else {
                   3225: 			selname[2].selected = true;
                   3226: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3227: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3228: 		    }
1.42      ng       3229: 		}
                   3230: 	    }
1.43      ng       3231: 	} else {
                   3232: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3233: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3234: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3235: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3236: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3237: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3238: 		if ((saveval != "correct") || override) {
1.125     ng       3239: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3240: 		    selname[0].selected = true;
                   3241: 		}
                   3242: 	    }
                   3243: 	}	    
1.42      ng       3244:     }
                   3245: 
                   3246:     function changeSelect(partid,user) {
1.125     ng       3247: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3248: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3249: 	var point  = textbox.value;
1.125     ng       3250: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3251: 
1.109     matthew  3252: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3253: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3254: 	    textbox.value = "";
                   3255: 	    return;
                   3256: 	}
1.109     matthew  3257: 	if (parseFloat(point) > parseFloat(weight)) {
                   3258: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3259: 			       ") greater than the weight of the part. Accept?");
                   3260: 	    if (resp == false) {
                   3261: 		textbox.value = "";
                   3262: 		return;
                   3263: 	    }
                   3264: 	}
1.42      ng       3265: 	selval[0].selected = true;
                   3266:     }
                   3267: 
                   3268:     function changeOneScore(partid,user) {
1.125     ng       3269: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3270: 	if (selval[1].selected || selval[2].selected) {
                   3271: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3272: 	    if (selval[2].selected) {
                   3273: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3274: 	    }
1.269     raeburn  3275:         }
1.42      ng       3276:     }
                   3277: 
                   3278:     function resetEntry(numpart) {
                   3279: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3280: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3281: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3282: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3283: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3284: 	    for (var i=0; i<radioButton.length; i++) {
                   3285: 		radioButton[i].checked=false;
                   3286: 
                   3287: 	    }
                   3288: 	    textbox.value = "";
                   3289: 	    selval[0].selected = true;
                   3290: 
                   3291: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3292: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3293: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3294: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3295: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3296: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3297: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3298: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3299: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3300: 		if (saveselval == "excused") {
1.43      ng       3301: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3302: 		} else {
1.43      ng       3303: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3304: 		}
                   3305: 	    }
1.41      ng       3306: 	}
1.42      ng       3307:     }
                   3308: 
1.41      ng       3309: VIEWJAVASCRIPT
1.42      ng       3310: }
                   3311: 
1.44      ng       3312: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3313: sub viewgrades {
1.608     www      3314:     my ($request,$symb) = @_;
1.42      ng       3315:     &viewgrades_js($request);
1.41      ng       3316: 
1.168     albertel 3317:     #need to make sure we have the correct data for later EXT calls, 
                   3318:     #thus invalidate the cache
                   3319:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3320:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3321:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3322:     &Apache::lonnet::clear_EXT_cache_status();
                   3323: 
1.398     albertel 3324:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3325: 
                   3326:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3327:     $result.=&jscriptNform($symb);
1.41      ng       3328: 
1.44      ng       3329:     #beginning of class grading form
1.442     banghart 3330:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3331:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3332: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3333: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3334: 	&build_section_inputs().
1.442     banghart 3335: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3336: 
1.560     raeburn  3337:     my ($common_header,$specific_header);
1.257     albertel 3338:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3339: 	$common_header = &mt('Assign Common Grade to Class');
                   3340:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3341:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3342:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3343: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3344:     } else {
1.560     raeburn  3345:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3346:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3347: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3348:     }
1.560     raeburn  3349:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3350:     #radio buttons/text box for assigning points for a section or class.
                   3351:     #handles different parts of a problem
1.582     raeburn  3352:     my $res_error;
                   3353:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3354:     if ($res_error) {
                   3355:         return &navmap_errormsg();
                   3356:     }
1.42      ng       3357:     my %weight = ();
                   3358:     my $ctsparts = 0;
1.45      ng       3359:     my %seen = ();
1.375     albertel 3360:     my @part_response_id = &flatten_responseType($responseType);
                   3361:     foreach my $part_response_id (@part_response_id) {
                   3362:     	my ($partid,$respid) = @{ $part_response_id };
                   3363: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3364: 	next if $seen{$partid};
                   3365: 	$seen{$partid}++;
1.375     albertel 3366: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3367: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3368: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3369: 
1.324     albertel 3370: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3371: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3372: 	my $ctr = 0;
1.42      ng       3373: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3374: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3375: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3376: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3377: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3378: 	    $ctr++;
                   3379: 	}
1.485     albertel 3380: 	$radio.='</tr></table>';
                   3381: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3382: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3383: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3384: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3385: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3386: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3387: 		$weight{$partid}.')"> '.
1.401     albertel 3388: 	    '<option selected="selected"> </option>'.
1.485     albertel 3389: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3390: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3391: 	    '</select></td>'.
                   3392:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3393: 	$line.='<input type="hidden" name="partid_'.
                   3394: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3395: 	$line.='<input type="hidden" name="weight_'.
                   3396: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3397: 
                   3398: 	$result.=
                   3399: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3400: 	    '<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 3401: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3402: 	$ctsparts++;
1.41      ng       3403:     }
1.474     albertel 3404:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3405: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3406:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3407: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3408: 
1.44      ng       3409:     #table listing all the students in a section/class
                   3410:     #header of table
1.560     raeburn  3411:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3412:               &Apache::loncommon::start_data_table().
                   3413: 	      &Apache::loncommon::start_data_table_header_row().
                   3414: 	      '<th>'.&mt('No.').'</th>'.
                   3415: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3416:     my $partserror;
                   3417:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3418:     if ($partserror) {
                   3419:         return &navmap_errormsg();
                   3420:     }
1.324     albertel 3421:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3422:     my @partids = ();
1.41      ng       3423:     foreach my $part (@parts) {
                   3424: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3425:         my $narrowtext = &mt('Tries');
                   3426: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3427: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3428: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3429:         push(@partids,$partid);
1.628     www      3430: #
                   3431: # FIXME: Looks like $display looks at English text
                   3432: #
1.324     albertel 3433: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3434: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3435: 	    $result.='<th>'.
                   3436: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3437: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3438: 	    next;
1.485     albertel 3439: 	    
1.207     albertel 3440: 	} else {
1.485     albertel 3441: 	    if ($display =~ /Problem Status/) {
                   3442: 		my $grade_status_mt = &mt('Grade Status');
                   3443: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3444: 	    }
                   3445: 	    my $part_mt = &mt('Part:');
                   3446: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3447: 	}
1.485     albertel 3448: 
1.474     albertel 3449: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3450:     }
1.474     albertel 3451:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3452: 
1.270     albertel 3453:     my %last_resets = 
                   3454: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3455: 
1.41      ng       3456:     #get info for each student
1.44      ng       3457:     #list all the students - with points and grade status
1.257     albertel 3458:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3459:     my $ctr = 0;
1.294     albertel 3460:     foreach (sort 
                   3461: 	     {
                   3462: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3463: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3464: 		 }
                   3465: 		 return $a cmp $b;
                   3466: 	     } (keys(%$fullname))) {
1.126     ng       3467: 	$ctr++;
1.324     albertel 3468: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3469: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3470:     }
1.474     albertel 3471:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3472:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3473:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3474: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3475:     if (scalar(%$fullname) eq 0) {
                   3476: 	my $colspan=3+scalar(@parts);
1.433     banghart 3477: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3478:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3479: 	$result='<span class="LC_warning">'.
1.485     albertel 3480: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3481: 	        $section_display, $stu_status).
1.433     banghart 3482: 	    '</span>';
1.96      albertel 3483:     }
1.41      ng       3484:     return $result;
                   3485: }
                   3486: 
1.44      ng       3487: #--- call by previous routine to display each student
1.41      ng       3488: sub viewstudentgrade {
1.324     albertel 3489:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3490:     my ($uname,$udom) = split(/:/,$student);
                   3491:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3492:     my %aggregates = (); 
1.474     albertel 3493:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3494: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3495: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3496: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3497: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3498: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3499:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3500:     foreach my $apart (@$parts) {
                   3501: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3502: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3503:         $result.='<td align="center">';
1.269     raeburn  3504:         my ($aggtries,$totaltries);
                   3505:         unless (exists($aggregates{$part})) {
1.270     albertel 3506: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3507: 
                   3508: 	    $aggtries = $totaltries;
1.269     raeburn  3509:             if ($$last_resets{$part}) {  
1.270     albertel 3510:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3511: 					   $part);
                   3512:             }
1.269     raeburn  3513:             $result.='<input type="hidden" name="'.
                   3514:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3515:             $result.='<input type="hidden" name="'.
                   3516:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3517:             $aggregates{$part} = 1;
                   3518:         }
1.41      ng       3519: 	if ($type eq 'awarded') {
1.320     albertel 3520: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3521: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3522: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3523: 	    $result.='<input type="text" name="'.
1.89      albertel 3524: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3525:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3526: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3527: 	} elsif ($type eq 'solved') {
                   3528: 	    my ($status,$foo)=split(/_/,$score,2);
                   3529: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3530: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3531: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3532: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3533: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3534:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3535: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3536: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3537: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3538: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3539: 	} else {
                   3540: 	    $result.='<input type="hidden" name="'.
                   3541: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3542: 		    "\n";
1.233     albertel 3543: 	    $result.='<input type="text" name="'.
1.122     ng       3544: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3545: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3546: 	}
                   3547:     }
1.474     albertel 3548:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3549:     return $result;
1.38      ng       3550: }
                   3551: 
1.44      ng       3552: #--- change scores for all the students in a section/class
                   3553: #    record does not get update if unchanged
1.38      ng       3554: sub editgrades {
1.608     www      3555:     my ($request,$symb) = @_;
1.41      ng       3556: 
1.433     banghart 3557:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3558:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3559:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3560: 
1.477     albertel 3561:     my $result= &Apache::loncommon::start_data_table().
                   3562: 	&Apache::loncommon::start_data_table_header_row().
                   3563: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3564: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3565:     my %scoreptr = (
                   3566: 		    'correct'  =>'correct_by_override',
                   3567: 		    'incorrect'=>'incorrect_by_override',
                   3568: 		    'excused'  =>'excused',
                   3569: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3570:                     'credited' =>'credit_attempted',
1.43      ng       3571: 		    'nothing'  => '',
                   3572: 		    );
1.257     albertel 3573:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3574: 
1.44      ng       3575:     my (@partid);
                   3576:     my %weight = ();
1.54      albertel 3577:     my %columns = ();
1.44      ng       3578:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3579: 
1.582     raeburn  3580:     my $partserror;
                   3581:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3582:     if ($partserror) {
                   3583:         return &navmap_errormsg();
                   3584:     }
1.54      albertel 3585:     my $header;
1.257     albertel 3586:     while ($ctr < $env{'form.totalparts'}) {
                   3587: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3588: 	push(@partid,$partid);
1.257     albertel 3589: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3590: 	$ctr++;
1.54      albertel 3591:     }
1.324     albertel 3592:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3593:     foreach my $partid (@partid) {
1.478     albertel 3594: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3595: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3596: 	$columns{$partid}=2;
                   3597: 	foreach my $stores (@parts) {
                   3598: 	    my ($part,$type) = &split_part_type($stores);
                   3599: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3600: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3601: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3602: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3603:             my $narrowtext = &mt('Tries');
                   3604: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3605: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3606: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3607: 	    $columns{$partid}+=2;
                   3608: 	}
                   3609:     }
                   3610:     foreach my $partid (@partid) {
1.324     albertel 3611: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3612: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3613: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3614: 	    '</th>';
1.54      albertel 3615: 
1.44      ng       3616:     }
1.477     albertel 3617:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3618: 	&Apache::loncommon::start_data_table_header_row().
                   3619: 	$header.
                   3620: 	&Apache::loncommon::end_data_table_header_row();
                   3621:     my @noupdate;
1.126     ng       3622:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3623:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3624: 	my $line;
1.257     albertel 3625: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3626: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3627: 	my %newrecord;
                   3628: 	my $updateflag = 0;
1.281     albertel 3629: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3630: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3631: 	if (!&canmodify($usec)) {
1.126     ng       3632: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3633: 	    push(@noupdate,
1.478     albertel 3634: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3635: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3636: 	    next;
                   3637: 	}
1.269     raeburn  3638:         my %aggregate = ();
                   3639:         my $aggregateflag = 0;
1.281     albertel 3640: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3641: 	foreach (@partid) {
1.257     albertel 3642: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3643: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3644: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3645: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3646: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3647: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3648: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3649: 	    my $score;
                   3650: 	    if ($partial eq '') {
1.257     albertel 3651: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3652: 	    } elsif ($partial > 0) {
                   3653: 		$score = 'correct_by_override';
                   3654: 	    } elsif ($partial == 0) {
                   3655: 		$score = 'incorrect_by_override';
                   3656: 	    }
1.257     albertel 3657: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3658: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3659: 
1.292     albertel 3660: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3661: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3662: 	    if ($dropMenu eq 'reset status' &&
                   3663: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3664: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3665: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3666: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3667: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3668: 		$updateflag = 1;
1.269     raeburn  3669:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3670:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3671:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3672:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3673:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3674:                     $aggregateflag = 1;
                   3675:                 }
1.139     albertel 3676: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3677: 		$updateflag = 1;
                   3678: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3679: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3680: 		$rec_update++;
1.125     ng       3681: 	    }
                   3682: 
1.93      albertel 3683: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3684: 		'<td align="center">'.$awarded.
                   3685: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3686: 
1.54      albertel 3687: 
                   3688: 	    my $partid=$_;
                   3689: 	    foreach my $stores (@parts) {
                   3690: 		my ($part,$type) = &split_part_type($stores);
                   3691: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3692: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3693: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3694: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3695: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3696: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3697: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3698: 		    $updateflag=1;
                   3699: 		}
1.93      albertel 3700: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3701: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3702: 	    }
1.44      ng       3703: 	}
1.477     albertel 3704: 	$line.="\n";
1.301     albertel 3705: 
                   3706: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3707: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3708: 
1.44      ng       3709: 	if ($updateflag) {
                   3710: 	    $count++;
1.257     albertel 3711: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3712: 				    $udom,$uname);
1.301     albertel 3713: 
                   3714: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3715: 					      $cnum,$udom,$uname)) {
                   3716: 		# need to figure out if should be in queue.
                   3717: 		my %record =  
                   3718: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3719: 					     $udom,$uname);
                   3720: 		my $all_graded = 1;
                   3721: 		my $none_graded = 1;
                   3722: 		foreach my $part (@parts) {
                   3723: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3724: 			$all_graded = 0;
                   3725: 		    } else {
                   3726: 			$none_graded = 0;
                   3727: 		    }
                   3728: 		}
                   3729: 
                   3730: 		if ($all_graded || $none_graded) {
                   3731: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3732: 							   $symb,$cdom,$cnum,
                   3733: 							   $udom,$uname);
                   3734: 		}
                   3735: 	    }
                   3736: 
1.477     albertel 3737: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3738: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3739: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3740: 	    $updateCtr++;
1.93      albertel 3741: 	} else {
1.477     albertel 3742: 	    push(@noupdate,
                   3743: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3744: 	    $noupdateCtr++;
1.44      ng       3745: 	}
1.269     raeburn  3746:         if ($aggregateflag) {
                   3747:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3748: 				  $cdom,$cnum);
1.269     raeburn  3749:         }
1.93      albertel 3750:     }
1.477     albertel 3751:     if (@noupdate) {
1.126     ng       3752: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3753: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3754: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3755: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3756: 	    &mt('No Changes Occurred For the Students Below').
                   3757: 	    '</td>'.
1.477     albertel 3758: 	    &Apache::loncommon::end_data_table_row();
                   3759: 	foreach my $line (@noupdate) {
                   3760: 	    $result.=
                   3761: 		&Apache::loncommon::start_data_table_row().
                   3762: 		$line.
                   3763: 		&Apache::loncommon::end_data_table_row();
                   3764: 	}
1.44      ng       3765:     }
1.614     www      3766:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3767:     my $msg = '<p><b>'.
                   3768: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3769: 	    $rec_update,$count).'</b><br />'.
                   3770: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3771: 	'</b></p>';
1.44      ng       3772:     return $title.$msg.$result;
1.5       albertel 3773: }
1.54      albertel 3774: 
                   3775: sub split_part_type {
                   3776:     my ($partstr) = @_;
                   3777:     my ($temp,@allparts)=split(/_/,$partstr);
                   3778:     my $type=pop(@allparts);
1.439     albertel 3779:     my $part=join('_',@allparts);
1.54      albertel 3780:     return ($part,$type);
                   3781: }
                   3782: 
1.44      ng       3783: #------------- end of section for handling grading by section/class ---------
                   3784: #
                   3785: #----------------------------------------------------------------------------
                   3786: 
1.5       albertel 3787: 
1.44      ng       3788: #----------------------------------------------------------------------------
                   3789: #
                   3790: #-------------------------- Next few routines handles grading by csv upload
                   3791: #
                   3792: #--- Javascript to handle csv upload
1.27      albertel 3793: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3794:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3795:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3796:   return(<<ENDPICK);
                   3797:   function verify(vf) {
                   3798:     var foundsomething=0;
                   3799:     var founduname=0;
1.243     albertel 3800:     var foundID=0;
1.27      albertel 3801:     for (i=0;i<=vf.nfields.value;i++) {
                   3802:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3803:       if (i==0 && tw!=0) { foundID=1; }
                   3804:       if (i==1 && tw!=0) { founduname=1; }
                   3805:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3806:     }
1.246     albertel 3807:     if (founduname==0 && foundID==0) {
                   3808: 	alert('$error1');
                   3809: 	return;
1.27      albertel 3810:     }
                   3811:     if (foundsomething==0) {
1.246     albertel 3812: 	alert('$error2');
                   3813: 	return;
1.27      albertel 3814:     }
                   3815:     vf.submit();
                   3816:   }
                   3817:   function flip(vf,tf) {
                   3818:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3819:     var i;
                   3820:     for (i=0;i<=vf.nfields.value;i++) {
                   3821:       //can not pick the same destination field for both name and domain
                   3822:       if (((i ==0)||(i ==1)) && 
                   3823:           ((tf==0)||(tf==1)) && 
                   3824:           (i!=tf) &&
                   3825:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3826:         eval('vf.f'+i+'.selectedIndex=0;')
                   3827:       }
                   3828:     }
                   3829:   }
                   3830: ENDPICK
                   3831: }
                   3832: 
                   3833: sub csvupload_javascript_forward_associate {
1.573     bisitz   3834:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3835:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3836:   return(<<ENDPICK);
                   3837:   function verify(vf) {
                   3838:     var foundsomething=0;
                   3839:     var founduname=0;
1.243     albertel 3840:     var foundID=0;
1.27      albertel 3841:     for (i=0;i<=vf.nfields.value;i++) {
                   3842:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3843:       if (tw==1) { foundID=1; }
                   3844:       if (tw==2) { founduname=1; }
                   3845:       if (tw>3) { foundsomething=1; }
1.27      albertel 3846:     }
1.246     albertel 3847:     if (founduname==0 && foundID==0) {
                   3848: 	alert('$error1');
                   3849: 	return;
1.27      albertel 3850:     }
                   3851:     if (foundsomething==0) {
1.246     albertel 3852: 	alert('$error2');
                   3853: 	return;
1.27      albertel 3854:     }
                   3855:     vf.submit();
                   3856:   }
                   3857:   function flip(vf,tf) {
                   3858:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3859:     var i;
                   3860:     //can not pick the same destination field twice
                   3861:     for (i=0;i<=vf.nfields.value;i++) {
                   3862:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3863:         eval('vf.f'+i+'.selectedIndex=0;')
                   3864:       }
                   3865:     }
                   3866:   }
                   3867: ENDPICK
                   3868: }
                   3869: 
1.26      albertel 3870: sub csvuploadmap_header {
1.324     albertel 3871:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3872:     my $javascript;
1.257     albertel 3873:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3874: 	$javascript=&csvupload_javascript_reverse_associate();
                   3875:     } else {
                   3876: 	$javascript=&csvupload_javascript_forward_associate();
                   3877:     }
1.45      ng       3878: 
1.418     albertel 3879:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3880:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3881:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3882:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3883:     my $reverse=&mt("Reverse Association");
1.41      ng       3884:     $request->print(<<ENDPICK);
1.632     www      3885: <br />
                   3886: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3887: <input type="hidden" name="associate"  value="" />
                   3888: <input type="hidden" name="phase"      value="three" />
                   3889: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3890: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3891: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3892: <input type="hidden" name="upfile_associate" 
1.257     albertel 3893:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3894: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3895: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3896: <hr />
                   3897: ENDPICK
1.597     wenzelju 3898:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3899:     return '';
1.26      albertel 3900: 
                   3901: }
                   3902: 
                   3903: sub csvupload_fields {
1.582     raeburn  3904:     my ($symb,$errorref) = @_;
                   3905:     my (@parts) = &getpartlist($symb,$errorref);
                   3906:     if (ref($errorref)) {
                   3907:         if ($$errorref) {
                   3908:             return;
                   3909:         }
                   3910:     }
                   3911: 
1.556     weissno  3912:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3913: 		['username','Student Username'],
                   3914: 		['domain','Student Domain']);
1.324     albertel 3915:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3916:     foreach my $part (sort(@parts)) {
                   3917: 	my @datum;
                   3918: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3919: 	my $name=$part;
                   3920: 	if  (!$display) { $display = $name; }
                   3921: 	@datum=($name,$display);
1.244     albertel 3922: 	if ($name=~/^stores_(.*)_awarded/) {
                   3923: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3924: 	}
1.41      ng       3925: 	push(@fields,\@datum);
                   3926:     }
                   3927:     return (@fields);
1.26      albertel 3928: }
                   3929: 
                   3930: sub csvuploadmap_footer {
1.41      ng       3931:     my ($request,$i,$keyfields) =@_;
                   3932:     $request->print(<<ENDPICK);
1.26      albertel 3933: </table>
                   3934: <input type="hidden" name="nfields" value="$i" />
                   3935: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3936: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3937: </form>
                   3938: ENDPICK
                   3939: }
                   3940: 
1.283     albertel 3941: sub checkforfile_js {
1.638     www      3942:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3943:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3944:     function checkUpload(formname) {
                   3945: 	if (formname.upfile.value == "") {
1.539     riegler  3946: 	    alert("$alertmsg");
1.86      ng       3947: 	    return false;
                   3948: 	}
                   3949: 	formname.submit();
                   3950:     }
                   3951: CSVFORMJS
1.283     albertel 3952:     return $result;
                   3953: }
                   3954: 
                   3955: sub upcsvScores_form {
1.608     www      3956:     my ($request,$symb) = @_;
1.283     albertel 3957:     if (!$symb) {return '';}
                   3958:     my $result=&checkforfile_js();
1.632     www      3959:     $result.=&Apache::loncommon::start_data_table().
                   3960:              &Apache::loncommon::start_data_table_header_row().
                   3961:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3962:              &Apache::loncommon::end_data_table_header_row().
                   3963:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3964:     my $upload=&mt("Upload Scores");
1.86      ng       3965:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3966:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3967:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3968:     $result.=<<ENDUPFORM;
1.106     albertel 3969: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3970: <input type="hidden" name="symb" value="$symb" />
                   3971: <input type="hidden" name="command" value="csvuploadmap" />
                   3972: $upfile_select
1.589     bisitz   3973: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3974: </form>
                   3975: ENDUPFORM
1.370     www      3976:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3977:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3978:              '</td>'.
                   3979:             &Apache::loncommon::end_data_table_row().
                   3980:             &Apache::loncommon::end_data_table();
1.86      ng       3981:     return $result;
                   3982: }
                   3983: 
                   3984: 
1.26      albertel 3985: sub csvuploadmap {
1.608     www      3986:     my ($request,$symb)= @_;
1.41      ng       3987:     if (!$symb) {return '';}
1.72      ng       3988: 
1.41      ng       3989:     my $datatoken;
1.257     albertel 3990:     if (!$env{'form.datatoken'}) {
1.41      ng       3991: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3992:     } else {
1.257     albertel 3993: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3994: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3995:     }
1.41      ng       3996:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3997:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3998:     my ($i,$keyfields);
                   3999:     if (@records) {
1.582     raeburn  4000:         my $fieldserror;
                   4001: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4002:         if ($fieldserror) {
                   4003:             $request->print(&navmap_errormsg());
                   4004:             return;
                   4005:         }
1.257     albertel 4006: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4007: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4008: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4009: 							  \@fields);
                   4010: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4011: 	    chop($keyfields);
                   4012: 	} else {
                   4013: 	    unshift(@fields,['none','']);
                   4014: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4015: 							    \@fields);
1.311     banghart 4016:             foreach my $rec (@records) {
                   4017:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4018:                 if (%temp) {
                   4019:                     $keyfields=join(',',sort(keys(%temp)));
                   4020:                     last;
                   4021:                 }
                   4022:             }
1.41      ng       4023: 	}
                   4024:     }
                   4025:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4026: 
1.41      ng       4027:     return '';
1.27      albertel 4028: }
                   4029: 
1.246     albertel 4030: sub csvuploadoptions {
1.608     www      4031:     my ($request,$symb)= @_;
1.632     www      4032:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4033:     $request->print(<<ENDPICK);
                   4034: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4035: <input type="hidden" name="command"    value="csvuploadassign" />
                   4036: <p>
                   4037: <label>
                   4038:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4039:    $overwrite
1.246     albertel 4040: </label>
                   4041: </p>
                   4042: ENDPICK
                   4043:     my %fields=&get_fields();
                   4044:     if (!defined($fields{'domain'})) {
1.257     albertel 4045: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4046: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4047:     }
1.257     albertel 4048:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4049: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4050: 	my $cleankey=$1;
                   4051: 	if ($cleankey eq 'command') { next; }
                   4052: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4053: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4054:     }
                   4055:     # FIXME do a check for any duplicated user ids...
                   4056:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4057:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4058: <hr /></form>'."\n");
1.246     albertel 4059:     return '';
                   4060: }
                   4061: 
                   4062: sub get_fields {
                   4063:     my %fields;
1.257     albertel 4064:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4065:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4066: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4067: 	    if ($env{'form.f'.$i} ne 'none') {
                   4068: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4069: 	    }
                   4070: 	} else {
1.257     albertel 4071: 	    if ($env{'form.f'.$i} ne 'none') {
                   4072: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4073: 	    }
                   4074: 	}
1.27      albertel 4075:     }
1.246     albertel 4076:     return %fields;
                   4077: }
                   4078: 
                   4079: sub csvuploadassign {
1.608     www      4080:     my ($request,$symb)= @_;
1.246     albertel 4081:     if (!$symb) {return '';}
1.345     bowersj2 4082:     my $error_msg = '';
1.246     albertel 4083:     &Apache::loncommon::load_tmp_file($request);
                   4084:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4085:     my %fields=&get_fields();
1.257     albertel 4086:     my $courseid=$env{'request.course.id'};
1.97      albertel 4087:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4088:     my @notallowed;
1.41      ng       4089:     my @skipped;
                   4090:     my $countdone=0;
                   4091:     foreach my $grade (@gradedata) {
                   4092: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4093: 	my $domain;
                   4094: 	if ($entries{$fields{'domain'}}) {
                   4095: 	    $domain=$entries{$fields{'domain'}};
                   4096: 	} else {
1.257     albertel 4097: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4098: 	}
1.243     albertel 4099: 	$domain=~s/\s//g;
1.41      ng       4100: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4101: 	$username=~s/\s//g;
1.243     albertel 4102: 	if (!$username) {
                   4103: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4104: 	    $id=~s/\s//g;
1.243     albertel 4105: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4106: 	    $username=$ids{$id};
                   4107: 	}
1.41      ng       4108: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4109: 	    my $id=$entries{$fields{'ID'}};
                   4110: 	    $id=~s/\s//g;
                   4111: 	    if ($id) {
                   4112: 		push(@skipped,"$id:$domain");
                   4113: 	    } else {
                   4114: 		push(@skipped,"$username:$domain");
                   4115: 	    }
1.41      ng       4116: 	    next;
                   4117: 	}
1.108     albertel 4118: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4119: 	if (!&canmodify($usec)) {
                   4120: 	    push(@notallowed,"$username:$domain");
                   4121: 	    next;
                   4122: 	}
1.244     albertel 4123: 	my %points;
1.41      ng       4124: 	my %grades;
                   4125: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4126: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4127: 		$dest eq 'domain') { next; }
                   4128: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4129: 	    if ($dest=~/stores_(.*)_points/) {
                   4130: 		my $part=$1;
                   4131: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4132: 					      $symb,$domain,$username);
1.345     bowersj2 4133:                 if ($wgt) {
                   4134:                     $entries{$fields{$dest}}=~s/\s//g;
                   4135:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4136:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4137:                                           : 'correct_by_override';
1.638     www      4138:                     if ($pcr>1) {
                   4139:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4140:                     }
1.345     bowersj2 4141:                     $grades{"resource.$part.awarded"}=$pcr;
                   4142:                     $grades{"resource.$part.solved"}=$award;
                   4143:                     $points{$part}=1;
                   4144:                 } else {
                   4145:                     $error_msg = "<br />" .
                   4146:                         &mt("Some point values were assigned"
                   4147:                             ." for problems with a weight "
                   4148:                             ."of zero. These values were "
                   4149:                             ."ignored.");
                   4150:                 }
1.244     albertel 4151: 	    } else {
                   4152: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4153: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4154: 		my $store_key=$dest;
                   4155: 		$store_key=~s/^stores/resource/;
                   4156: 		$store_key=~s/_/\./g;
                   4157: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4158: 	    }
1.41      ng       4159: 	}
1.508     www      4160: 	if (! %grades) { 
                   4161:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4162:         } else {
                   4163: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4164: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4165: 					   $env{'request.course.id'},
                   4166: 					   $domain,$username);
1.508     www      4167: 	   if ($result eq 'ok') {
1.627     www      4168: # Successfully stored
1.508     www      4169: 	      $request->print('.');
1.627     www      4170: # Remove from grading queue
                   4171:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4172:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4173:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4174:                                              $domain,$username);
                   4175:               $countdone++;
                   4176:            } else {
1.508     www      4177: 	      $request->print("<p><span class=\"LC_error\">".
                   4178:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4179:                                   "$username:$domain",$result)."</span></p>");
                   4180: 	   }
                   4181: 	   $request->rflush();
                   4182:         }
1.41      ng       4183:     }
1.570     www      4184:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4185:     if (@skipped) {
1.571     www      4186: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4187:         $request->print(join(', ',@skipped));
1.106     albertel 4188:     }
                   4189:     if (@notallowed) {
1.571     www      4190: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4191: 	$request->print(join(', ',@notallowed));
1.41      ng       4192:     }
1.106     albertel 4193:     $request->print("<br />\n");
1.345     bowersj2 4194:     return $error_msg;
1.26      albertel 4195: }
1.44      ng       4196: #------------- end of section for handling csv file upload ---------
                   4197: #
                   4198: #-------------------------------------------------------------------
                   4199: #
1.122     ng       4200: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4201: #
                   4202: #--- Select a page/sequence and a student to grade
1.68      ng       4203: sub pickStudentPage {
1.608     www      4204:     my ($request,$symb) = @_;
1.68      ng       4205: 
1.539     riegler  4206:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4207:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4208: 
                   4209: function checkPickOne(formname) {
1.76      ng       4210:     if (radioSelection(formname.student) == null) {
1.539     riegler  4211: 	alert("$alertmsg");
1.68      ng       4212: 	return;
                   4213:     }
1.125     ng       4214:     ptr = pullDownSelection(formname.selectpage);
                   4215:     formname.page.value = formname["page"+ptr].value;
                   4216:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4217:     formname.submit();
                   4218: }
                   4219: 
                   4220: LISTJAVASCRIPT
1.118     ng       4221:     &commonJSfunctions($request);
1.608     www      4222: 
1.257     albertel 4223:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4224:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4225:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4226: 
1.398     albertel 4227:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4228: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4229: 
1.80      ng       4230:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4231:     my $map_error;
                   4232:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4233:     if ($map_error) {
                   4234:         $request->print(&navmap_errormsg());
                   4235:         return; 
                   4236:     }
1.137     albertel 4237:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4238: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4239: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4240:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4241:     my $ctr=0;
1.68      ng       4242:     foreach (@$titles) {
                   4243: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4244: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4245: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4246: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4247: 	$ctr++;
1.68      ng       4248:     }
1.485     albertel 4249:     $select.= '</select>';
1.539     riegler  4250:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4251: 
1.70      ng       4252:     $ctr=0;
                   4253:     foreach (@$titles) {
                   4254: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4255: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4256: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4257: 	$ctr++;
                   4258:     }
1.72      ng       4259:     $result.='<input type="hidden" name="page" />'."\n".
                   4260: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4261: 
1.485     albertel 4262:     my $options =
                   4263: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4264: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4265:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4266: 
                   4267:     $options =
                   4268: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4269: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4270: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4271:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4272:     
                   4273:     $result.=&build_section_inputs();
1.442     banghart 4274:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4275:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4276: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4277: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4278: 
1.539     riegler  4279:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4280: 
1.80      ng       4281:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4282:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4283: 
1.68      ng       4284:     $request->print($result);
                   4285: 
1.485     albertel 4286:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4287: 	&Apache::loncommon::start_data_table().
                   4288: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4289: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4290: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4292: 	'<th>'.&nameUserString('header').'</th>'.
                   4293: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4294:  
1.76      ng       4295:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4296:     my $ptr = 1;
1.294     albertel 4297:     foreach my $student (sort 
                   4298: 			 {
                   4299: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4300: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4301: 			     }
                   4302: 			     return $a cmp $b;
                   4303: 			 } (keys(%$fullname))) {
1.68      ng       4304: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4305: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4306:                                   : '</td>');
1.126     ng       4307: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4308: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4309: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4310: 	$studentTable.=
                   4311: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4312:                          : '');
1.68      ng       4313: 	$ptr++;
                   4314:     }
1.484     albertel 4315:     if ($ptr%2 == 0) {
                   4316: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4317: 	    &Apache::loncommon::end_data_table_row();
                   4318:     }
                   4319:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4320:     $studentTable.='<input type="button" '.
1.589     bisitz   4321:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4322: 
                   4323:     $request->print($studentTable);
                   4324: 
                   4325:     return '';
                   4326: }
                   4327: 
                   4328: sub getSymbMap {
1.582     raeburn  4329:     my ($map_error) = @_;
1.132     bowersj2 4330:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4331:     unless (ref($navmap)) {
                   4332:         if (ref($map_error)) {
                   4333:             $$map_error = 'navmap';
                   4334:         }
                   4335:         return;
                   4336:     }
1.68      ng       4337:     my %symbx = ();
                   4338:     my @titles = ();
1.117     bowersj2 4339:     my $minder = 0;
                   4340: 
                   4341:     # Gather every sequence that has problems.
1.240     albertel 4342:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4343: 					       1,0,1);
1.117     bowersj2 4344:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4345: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4346: 	    my $title = $minder.'.'.
                   4347: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4348: 	    push(@titles, $title); # minder in case two titles are identical
                   4349: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4350: 	    $minder++;
1.241     albertel 4351: 	}
1.68      ng       4352:     }
                   4353:     return \@titles,\%symbx;
                   4354: }
                   4355: 
1.72      ng       4356: #
                   4357: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4358: sub displayPage {
1.608     www      4359:     my ($request,$symb) = @_;
1.257     albertel 4360:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4361:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4362:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4363:     my $pageTitle = $env{'form.page'};
1.103     albertel 4364:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4365:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4366:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4367: 
                   4368:     #need to make sure we have the correct data for later EXT calls, 
                   4369:     #thus invalidate the cache
                   4370:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4371:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4372:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4373:     &Apache::lonnet::clear_EXT_cache_status();
                   4374: 
1.103     albertel 4375:     if (!&canview($usec)) {
1.485     albertel 4376: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4377: 	return;
                   4378:     }
1.398     albertel 4379:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4380:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4381: 	'</h3>'."\n";
1.500     albertel 4382:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4383:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4384: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4385:     } else {
                   4386: 	delete($env{'form.CODE'});
                   4387:     }
1.71      ng       4388:     &sub_page_js($request);
                   4389:     $request->print($result);
                   4390: 
1.132     bowersj2 4391:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4392:     unless (ref($navmap)) {
                   4393:         $request->print(&navmap_errormsg());
                   4394:         return;
                   4395:     }
1.257     albertel 4396:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4397:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4398:     if (!$map) {
1.485     albertel 4399: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4400: 	return; 
                   4401:     }
1.68      ng       4402:     my $iterator = $navmap->getIterator($map->map_start(),
                   4403: 					$map->map_finish());
                   4404: 
1.71      ng       4405:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4406: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4407: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4408: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4409: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4410: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4411: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4412: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4413: 
1.382     albertel 4414:     if (defined($env{'form.CODE'})) {
                   4415: 	$studentTable.=
                   4416: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4417:     }
1.381     albertel 4418:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4419: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4420: 
1.594     bisitz   4421:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4422:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4423:         '</span>'."\n".
1.484     albertel 4424: 	&Apache::loncommon::start_data_table().
                   4425: 	&Apache::loncommon::start_data_table_header_row().
                   4426: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4427: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4428: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4429: 
1.329     albertel 4430:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4431:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4432:     $iterator->next(); # skip the first BEGIN_MAP
                   4433:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4434:     while ($depth > 0) {
1.68      ng       4435:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4436:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4437: 
1.385     albertel 4438:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4439: 	    my $parts = $curRes->parts();
1.68      ng       4440:             my $title = $curRes->compTitle();
1.71      ng       4441: 	    my $symbx = $curRes->symb();
1.484     albertel 4442: 	    $studentTable.=
                   4443: 		&Apache::loncommon::start_data_table_row().
                   4444: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4445: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4446: 		                        : '<br />('.&mt('[_1]parts)',
                   4447: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4448: 		 ).
                   4449: 		 '</td>';
1.71      ng       4450: 	    $studentTable.='<td valign="top">';
1.382     albertel 4451: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4452: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4453: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4454: 					     undef,'both',\%form);
1.71      ng       4455: 	    } else {
1.382     albertel 4456: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4457: 		$companswer =~ s|<form(.*?)>||g;
                   4458: 		$companswer =~ s|</form>||g;
1.71      ng       4459: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4460: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4461: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4462: #		}
1.116     ng       4463: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4464: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4465: 	    }
                   4466: 
1.257     albertel 4467: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4468: 
1.257     albertel 4469: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4470: 		if ($record{'version'} eq '') {
1.485     albertel 4471: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4472: 		} else {
1.116     ng       4473: 		    my %responseType = ();
                   4474: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4475: 			my @responseIds =$curRes->responseIds($partid);
                   4476: 			my @responseType =$curRes->responseType($partid);
                   4477: 			my %responseIds;
                   4478: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4479: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4480: 			}
                   4481: 			$responseType{$partid} = \%responseIds;
1.116     ng       4482: 		    }
1.148     albertel 4483: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4484: 
1.71      ng       4485: 		}
1.257     albertel 4486: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4487: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4488: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4489: 									$env{'request.course.id'},
1.71      ng       4490: 									'','.submission');
                   4491:  
                   4492: 	    }
1.103     albertel 4493: 	    if (&canmodify($usec)) {
1.585     bisitz   4494:             $studentTable.=&gradeBox_start();
1.103     albertel 4495: 		foreach my $partid (@{$parts}) {
                   4496: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4497: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4498: 		    $question++;
                   4499: 		}
1.585     bisitz   4500:             $studentTable.=&gradeBox_end();
1.196     albertel 4501: 		$prob++;
1.71      ng       4502: 	    }
                   4503: 	    $studentTable.='</td></tr>';
1.68      ng       4504: 
1.103     albertel 4505: 	}
1.68      ng       4506:         $curRes = $iterator->next();
                   4507:     }
                   4508: 
1.589     bisitz   4509:     $studentTable.=
                   4510:         '</table>'."\n".
                   4511:         '<input type="button" value="'.&mt('Save').'" '.
                   4512:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4513:         '</form>'."\n";
1.71      ng       4514:     $request->print($studentTable);
                   4515: 
                   4516:     return '';
1.119     ng       4517: }
                   4518: 
                   4519: sub displaySubByDates {
1.148     albertel 4520:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4521:     my $isCODE=0;
1.335     albertel 4522:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4523:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4524:     my $studentTable=&Apache::loncommon::start_data_table().
                   4525: 	&Apache::loncommon::start_data_table_header_row().
                   4526: 	'<th>'.&mt('Date/Time').'</th>'.
                   4527: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4528: 	'<th>'.&mt('Submission').'</th>'.
                   4529: 	'<th>'.&mt('Status').'</th>'.
                   4530: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4531:     my ($version);
                   4532:     my %mark;
1.148     albertel 4533:     my %orders;
1.119     ng       4534:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4535:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4536: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4537:     }
1.335     albertel 4538: 
                   4539:     my $interaction;
1.525     raeburn  4540:     my $no_increment = 1;
1.640     raeburn  4541:     my %lastrndseed;
1.119     ng       4542:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4543: 	my $timestamp = 
                   4544: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4545: 	if (exists($$record{$version.':resource.0.version'})) {
                   4546: 	    $interaction = $$record{$version.':resource.0.version'};
                   4547: 	}
                   4548: 
                   4549: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4550: 		             : "$version:resource");
1.467     albertel 4551: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4552: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4553: 	if ($isCODE) {
                   4554: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4555: 	}
1.119     ng       4556: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4557: 	my @displaySub = ();
                   4558: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4559:             my ($hidden,$type);
                   4560:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4561:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4562:                 $hidden = 1;
                   4563:             }
1.335     albertel 4564: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4565: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4566: 	    
1.122     ng       4567: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4568: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4569: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4570: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4571: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4572:                     
1.335     albertel 4573: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4574: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4575:                     $displaySub[0].='<span class="LC_nobreak"';
                   4576:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4577:                                    .' <span class="LC_internal_info">'
1.625     www      4578:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4579:                                    .'</span>'
                   4580:                                    .' <b>';
1.596     raeburn  4581:                     if ($hidden) {
                   4582:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4583:                     } else {
1.640     raeburn  4584:                         my ($trial,$rndseed,$newvariation);
                   4585:                         if ($type eq 'randomizetry') {
                   4586:                             $trial = $$record{"$where.$partid.tries"};
                   4587:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4588:                         }
1.596     raeburn  4589: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4590: 			    $displaySub[0].=&mt('Trial not counted');
                   4591: 		        } else {
                   4592: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4593: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4594:                             if ($rndseed || $lastrndseed{$partid}) {
                   4595:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4596:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4597:                                 }
                   4598:                             }
                   4599:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4600: 		        }
                   4601: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4602:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4603: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4604: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4605: 			    $orders{$partid}->{$responseId}=
                   4606: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4607:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4608: 		        }
1.640     raeburn  4609: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4610: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4611: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4612:                     }
1.147     albertel 4613: 		}
                   4614: 	    }
1.335     albertel 4615: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4616: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4617: 				    $$record{"$where.$partid.checkedin"},
                   4618: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4619: 					'<br />';
1.335     albertel 4620: 	    }
                   4621: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4622: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4623: 		    lc($$record{"$where.$partid.award"}).' '.
                   4624: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4625: 		    '<br />';
                   4626: 	    }
1.335     albertel 4627: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4628: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4629: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4630: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4631: 		$displaySub[2].=
                   4632: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4633: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4634: 	    }
                   4635: 	}
                   4636: 	# needed because old essay regrader has not parts info
                   4637: 	if (exists $$record{"$version:resource.regrader"}) {
                   4638: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4639: 	}
                   4640: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4641: 	if ($displaySub[2]) {
1.467     albertel 4642: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4643: 	}
1.467     albertel 4644: 	$studentTable.='&nbsp;</td>'.
                   4645: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4646:     }
1.467     albertel 4647:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4648:     return $studentTable;
1.71      ng       4649: }
                   4650: 
                   4651: sub updateGradeByPage {
1.608     www      4652:     my ($request,$symb) = @_;
1.71      ng       4653: 
1.257     albertel 4654:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4655:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4656:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4657:     my $pageTitle = $env{'form.page'};
1.103     albertel 4658:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4659:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4660:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4661:     if (!&canmodify($usec)) {
1.526     raeburn  4662: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4663: 	return;
                   4664:     }
1.398     albertel 4665:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4666:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4667: 	'</h3>'."\n";
1.70      ng       4668: 
1.68      ng       4669:     $request->print($result);
                   4670: 
1.582     raeburn  4671: 
1.132     bowersj2 4672:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4673:     unless (ref($navmap)) {
                   4674:         $request->print(&navmap_errormsg());
                   4675:         return;
                   4676:     }
1.257     albertel 4677:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4678:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4679:     if (!$map) {
1.527     raeburn  4680: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4681: 	return; 
                   4682:     }
1.71      ng       4683:     my $iterator = $navmap->getIterator($map->map_start(),
                   4684: 					$map->map_finish());
1.70      ng       4685: 
1.484     albertel 4686:     my $studentTable=
                   4687: 	&Apache::loncommon::start_data_table().
                   4688: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4689: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4690: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4691: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4692: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4693: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4694: 
                   4695:     $iterator->next(); # skip the first BEGIN_MAP
                   4696:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4697:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4698:     while ($depth > 0) {
1.71      ng       4699:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4700:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4701: 
1.385     albertel 4702:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4703: 	    my $parts = $curRes->parts();
1.71      ng       4704:             my $title = $curRes->compTitle();
                   4705: 	    my $symbx = $curRes->symb();
1.484     albertel 4706: 	    $studentTable.=
                   4707: 		&Apache::loncommon::start_data_table_row().
                   4708: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4709: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4710:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4711: 		.')').'</td>';
1.71      ng       4712: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4713: 
                   4714: 	    my %newrecord=();
                   4715: 	    my @displayPts=();
1.269     raeburn  4716:             my %aggregate = ();
                   4717:             my $aggregateflag = 0;
1.71      ng       4718: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4719: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4720: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4721: 
1.257     albertel 4722: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4723: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4724: 		my $partial = $newpts/$wgt;
                   4725: 		my $score;
                   4726: 		if ($partial > 0) {
                   4727: 		    $score = 'correct_by_override';
1.125     ng       4728: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4729: 		    $score = 'incorrect_by_override';
                   4730: 		}
1.257     albertel 4731: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4732: 		if ($dropMenu eq 'excused') {
1.71      ng       4733: 		    $partial = '';
                   4734: 		    $score = 'excused';
1.125     ng       4735: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4736: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4737: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4738: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4739: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4740: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4741: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4742: 		    $changeflag++;
                   4743: 		    $newpts = '';
1.269     raeburn  4744:                     
                   4745:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4746:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4747:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4748:                     if ($aggtries > 0) {
                   4749:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4750:                         $aggregateflag = 1;
                   4751:                     }
1.71      ng       4752: 		}
1.324     albertel 4753: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4754: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4755: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4756: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4757: 		    '&nbsp;<br />';
1.526     raeburn  4758: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4759: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4760: 		    '&nbsp;<br />';
1.71      ng       4761: 		$question++;
1.380     albertel 4762: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4763: 
1.71      ng       4764: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4765: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4766: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4767: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4768: 
                   4769: 		$changeflag++;
                   4770: 	    }
                   4771: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4772: 		my %record = 
                   4773: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4774: 					     $udom,$uname);
                   4775: 
                   4776: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4777: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4778: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4779: 		    $newrecord{'resource.CODE'} = '';
                   4780: 		}
1.257     albertel 4781: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4782: 					$udom,$uname);
1.382     albertel 4783: 		%record = &Apache::lonnet::restore($symbx,
                   4784: 						   $env{'request.course.id'},
                   4785: 						   $udom,$uname);
1.380     albertel 4786: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4787: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4788: 	    }
1.380     albertel 4789: 	    
1.269     raeburn  4790:             if ($aggregateflag) {
                   4791:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4792:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4793:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4794:             }
1.125     ng       4795: 
1.71      ng       4796: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4797: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4798: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4799: 
1.196     albertel 4800: 	    $prob++;
1.68      ng       4801: 	}
1.71      ng       4802:         $curRes = $iterator->next();
1.68      ng       4803:     }
1.98      albertel 4804: 
1.484     albertel 4805:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4806:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4807: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4808: 		  $changeflag));
1.76      ng       4809:     $request->print($grademsg.$studentTable);
1.68      ng       4810: 
1.70      ng       4811:     return '';
                   4812: }
                   4813: 
1.72      ng       4814: #-------- end of section for handling grading by page/sequence ---------
                   4815: #
                   4816: #-------------------------------------------------------------------
                   4817: 
1.581     www      4818: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4819: #
                   4820: #------ start of section for handling grading by page/sequence ---------
                   4821: 
1.423     albertel 4822: =pod
                   4823: 
                   4824: =head1 Bubble sheet grading routines
                   4825: 
1.424     albertel 4826:   For this documentation:
                   4827: 
                   4828:    'scanline' refers to the full line of characters
                   4829:    from the file that we are parsing that represents one entire sheet
                   4830: 
                   4831:    'bubble line' refers to the data
                   4832:    representing the line of bubbles that are on the physical bubble sheet
                   4833: 
                   4834: 
                   4835: The overall process is that a scanned in bubble sheet data is uploaded
                   4836: into a course. When a user wants to grade, they select a
                   4837: sequence/folder of resources, a file of bubble sheet info, and pick
                   4838: one of the predefined configurations for what each scanline looks
                   4839: like.
                   4840: 
                   4841: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4842: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4843: because too light bubbling), 'double bubble' (each bubble line should
                   4844: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4845: invalid student/employee ID
1.424     albertel 4846: 
                   4847: If the CODE option is used that determines the randomization of the
1.556     weissno  4848: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4849: username:domain.
                   4850: 
                   4851: During the validation phase the instructor can choose to skip scanlines. 
                   4852: 
1.435     foxr     4853: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4854: 
                   4855:   scantron_original_filename (unmodified original file)
                   4856:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4857:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4858: 
                   4859: Also there is a separate hash nohist_scantrondata that contains extra
                   4860: correction information that isn't representable in the bubble sheet
                   4861: file (see &scantron_getfile() for more information)
                   4862: 
                   4863: After all scanlines are either valid, marked as valid or skipped, then
                   4864: foreach line foreach problem in the picked sequence, an ssi request is
                   4865: made that simulates a user submitting their selected letter(s) against
                   4866: the homework problem.
1.423     albertel 4867: 
                   4868: =over 4
                   4869: 
                   4870: 
                   4871: 
                   4872: =item defaultFormData
                   4873: 
                   4874:   Returns html hidden inputs used to hold context/default values.
                   4875: 
                   4876:  Arguments:
                   4877:   $symb - $symb of the current resource 
                   4878: 
                   4879: =cut
1.422     foxr     4880: 
1.81      albertel 4881: sub defaultFormData {
1.324     albertel 4882:     my ($symb)=@_;
1.613     www      4883:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4884: }
                   4885: 
1.447     foxr     4886: 
1.423     albertel 4887: =pod 
                   4888: 
                   4889: =item getSequenceDropDown
                   4890: 
                   4891:    Return html dropdown of possible sequences to grade
                   4892:  
                   4893:  Arguments:
1.582     raeburn  4894:    $symb - $symb of the current resource
                   4895:    $map_error - ref to scalar which will container error if
                   4896:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4897: 
                   4898: =cut
1.422     foxr     4899: 
1.75      albertel 4900: sub getSequenceDropDown {
1.582     raeburn  4901:     my ($symb,$map_error)=@_;
1.75      albertel 4902:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4903:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4904:     if (ref($map_error)) {
                   4905:         return if ($$map_error);
                   4906:     }
1.137     albertel 4907:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4908:     my $ctr=0;
                   4909:     foreach (@$titles) {
                   4910: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4911: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4912: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4913: 	    '>'.$showtitle.'</option>'."\n";
                   4914: 	$ctr++;
                   4915:     }
                   4916:     $result.= '</select>';
                   4917:     return $result;
                   4918: }
                   4919: 
1.495     albertel 4920: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4921:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4922: 
                   4923: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4924: 
1.509     raeburn  4925: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4926:                                    # matchresponse or rankresponse, where 
                   4927:                                    # an individual response can have multiple 
                   4928:                                    # lines
1.503     raeburn  4929: 
                   4930: my %responsetype_per_response;     # responsetype for each response
                   4931: 
1.495     albertel 4932: # Save and restore the bubble lines array to the form env.
                   4933: 
                   4934: 
                   4935: sub save_bubble_lines {
                   4936:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4937: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4938: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4939: 	    $first_bubble_line{$line};
1.503     raeburn  4940:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4941:             $subdivided_bubble_lines{$line};
                   4942:         $env{"form.scantron.responsetype.$line"} =
                   4943:             $responsetype_per_response{$line};
1.495     albertel 4944:     }
                   4945: }
                   4946: 
                   4947: 
                   4948: sub restore_bubble_lines {
                   4949:     my $line = 0;
                   4950:     %bubble_lines_per_response = ();
                   4951:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4952: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4953: 	$bubble_lines_per_response{$line} = $value;
                   4954: 	$first_bubble_line{$line}  =
                   4955: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4956:         $subdivided_bubble_lines{$line} =
                   4957:             $env{"form.scantron.sub_bubblelines.$line"};
                   4958:         $responsetype_per_response{$line} =
                   4959:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4960: 	$line++;
                   4961:     }
                   4962: }
                   4963: 
                   4964: #  Given the parsed scanline, get the response for 
                   4965: #  'answer' number n:
                   4966: 
                   4967: sub get_response_bubbles {
                   4968:     my ($parsed_line, $response)  = @_;
                   4969: 
                   4970:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4971:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4972:     
                   4973:     my $selected = "";
                   4974: 
                   4975:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4976: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4977: 	$bubble_line++;
                   4978:     }
                   4979:     return $selected;
                   4980: }
1.423     albertel 4981: 
                   4982: =pod 
                   4983: 
                   4984: =item scantron_filenames
                   4985: 
                   4986:    Returns a list of the scantron files in the current course 
                   4987: 
                   4988: =cut
1.422     foxr     4989: 
1.202     albertel 4990: sub scantron_filenames {
1.257     albertel 4991:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4992:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4993:     my $getpropath = 1;
1.157     albertel 4994:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4995:                                        $getpropath);
1.202     albertel 4996:     my @possiblenames;
1.201     albertel 4997:     foreach my $filename (sort(@files)) {
1.157     albertel 4998: 	($filename)=split(/&/,$filename);
                   4999: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5000: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5001: 	push(@possiblenames,$filename);
                   5002:     }
                   5003:     return @possiblenames;
                   5004: }
                   5005: 
1.423     albertel 5006: =pod 
                   5007: 
                   5008: =item scantron_uploads
                   5009: 
                   5010:    Returns  html drop-down list of scantron files in current course.
                   5011: 
                   5012:  Arguments:
                   5013:    $file2grade - filename to set as selected in the dropdown
                   5014: 
                   5015: =cut
1.422     foxr     5016: 
1.202     albertel 5017: sub scantron_uploads {
1.209     ng       5018:     my ($file2grade) = @_;
1.202     albertel 5019:     my $result=	'<select name="scantron_selectfile">';
                   5020:     $result.="<option></option>";
                   5021:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5022: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5023:     }
                   5024:     $result.="</select>";
                   5025:     return $result;
                   5026: }
                   5027: 
1.423     albertel 5028: =pod 
                   5029: 
                   5030: =item scantron_scantab
                   5031: 
                   5032:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5033:   file.
                   5034: 
                   5035: =cut
1.422     foxr     5036: 
1.82      albertel 5037: sub scantron_scantab {
                   5038:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5039:     $result.='<option></option>'."\n";
1.518     raeburn  5040:     my @lines = &get_scantronformat_file();
                   5041:     if (@lines > 0) {
                   5042:         foreach my $line (@lines) {
                   5043:             next if (($line =~ /^\#/) || ($line eq ''));
                   5044: 	    my ($name,$descrip)=split(/:/,$line);
                   5045: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5046:         }
1.82      albertel 5047:     }
                   5048:     $result.='</select>'."\n";
1.518     raeburn  5049:     return $result;
                   5050: }
                   5051: 
                   5052: =pod
                   5053: 
                   5054: =item get_scantronformat_file
                   5055: 
                   5056:   Returns an array containing lines from the scantron format file for
                   5057:   the domain of the course.
                   5058: 
                   5059:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5060:   lines are from this file.
                   5061: 
                   5062:   Otherwise, if a default.tab has been published in RES space by the 
                   5063:   domainconfig user, lines are from this file.
                   5064: 
                   5065:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5066:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5067: 
1.518     raeburn  5068: =cut
                   5069: 
                   5070: sub get_scantronformat_file {
                   5071:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5072:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5073:     my $gottab = 0;
                   5074:     my @lines;
                   5075:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5076:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5077:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5078:             if ($formatfile ne '-1') {
                   5079:                 @lines = split("\n",$formatfile,-1);
                   5080:                 $gottab = 1;
                   5081:             }
                   5082:         }
                   5083:     }
                   5084:     if (!$gottab) {
                   5085:         my $confname = $cdom.'-domainconfig';
                   5086:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5087:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5088:         if ($formatfile ne '-1') {
                   5089:             @lines = split("\n",$formatfile,-1);
                   5090:             $gottab = 1;
                   5091:         }
                   5092:     }
                   5093:     if (!$gottab) {
1.519     raeburn  5094:         my @domains = &Apache::lonnet::current_machine_domains();
                   5095:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5096:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5097:             @lines = <$fh>;
                   5098:             close($fh);
                   5099:         } else {
                   5100:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5101:             @lines = <$fh>;
                   5102:             close($fh);
                   5103:         }
1.518     raeburn  5104:     }
                   5105:     return @lines;
1.82      albertel 5106: }
                   5107: 
1.423     albertel 5108: =pod 
                   5109: 
                   5110: =item scantron_CODElist
                   5111: 
                   5112:   Returns html drop down of the saved CODE lists from current course,
                   5113:   generated from earlier printings.
                   5114: 
                   5115: =cut
1.422     foxr     5116: 
1.186     albertel 5117: sub scantron_CODElist {
1.257     albertel 5118:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5119:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5120:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5121:     my $namechoice='<option></option>';
1.225     albertel 5122:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5123: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5124: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5125: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5126:     }
                   5127:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5128:     return $namechoice;
                   5129: }
                   5130: 
1.423     albertel 5131: =pod 
                   5132: 
                   5133: =item scantron_CODEunique
                   5134: 
                   5135:   Returns the html for "Each CODE to be used once" radio.
                   5136: 
                   5137: =cut
1.422     foxr     5138: 
1.186     albertel 5139: sub scantron_CODEunique {
1.532     bisitz   5140:     my $result='<span class="LC_nobreak">
1.272     albertel 5141:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5142:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5143:                 </span>
1.532     bisitz   5144:                 <span class="LC_nobreak">
1.272     albertel 5145:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5146:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5147:                 </span>';
1.186     albertel 5148:     return $result;
                   5149: }
1.423     albertel 5150: 
                   5151: =pod 
                   5152: 
                   5153: =item scantron_selectphase
                   5154: 
                   5155:   Generates the initial screen to start the bubble sheet process.
                   5156:   Allows for - starting a grading run.
1.424     albertel 5157:              - downloading existing scan data (original, corrected
1.423     albertel 5158:                                                 or skipped info)
                   5159: 
                   5160:              - uploading new scan data
                   5161: 
                   5162:  Arguments:
                   5163:   $r          - The Apache request object
                   5164:   $file2grade - name of the file that contain the scanned data to score
                   5165: 
                   5166: =cut
1.186     albertel 5167: 
1.75      albertel 5168: sub scantron_selectphase {
1.608     www      5169:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5170:     if (!$symb) {return '';}
1.582     raeburn  5171:     my $map_error;
                   5172:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5173:     if ($map_error) {
                   5174:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5175:         return;
                   5176:     }
1.324     albertel 5177:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5178:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5179:     my $format_selector=&scantron_scantab();
1.186     albertel 5180:     my $CODE_selector=&scantron_CODElist();
                   5181:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5182:     my $result;
1.422     foxr     5183: 
1.513     foxr     5184:     $ssi_error = 0;
                   5185: 
1.606     wenzelju 5186:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5187:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5188: 
                   5189: 	# Chunk of form to prompt for a scantron file upload.
                   5190: 
                   5191:         $r->print('
                   5192:     <br />
                   5193:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5194:        '.&Apache::loncommon::start_data_table_header_row().'
                   5195:             <th>
                   5196:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5197:             </th>
                   5198:        '.&Apache::loncommon::end_data_table_header_row().'
                   5199:        '.&Apache::loncommon::start_data_table_row().'
                   5200:             <td>
                   5201: ');
1.608     www      5202:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5203:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5204:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5205:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5206:     function checkUpload(formname) {
                   5207: 	if (formname.upfile.value == "") {
                   5208: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5209: 	    return false;
                   5210: 	}
                   5211: 	formname.submit();
                   5212:     }'));
                   5213:     $r->print('
                   5214:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5215:                 '.$default_form_data.'
                   5216:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5217:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5218:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5219:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5220:                 <br />
                   5221:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5222:               </form>
                   5223: ');
                   5224: 
                   5225:         $r->print('
                   5226:             </td>
                   5227:        '.&Apache::loncommon::end_data_table_row().'
                   5228:        '.&Apache::loncommon::end_data_table().'
                   5229: ');
                   5230:     }
                   5231: 
1.422     foxr     5232:     # Chunk of form to prompt for a file to grade and how:
                   5233: 
1.489     albertel 5234:     $result.= '
                   5235:     <br />
                   5236:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5237:     <input type="hidden" name="command" value="scantron_warning" />
                   5238:     '.$default_form_data.'
                   5239:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5240:        '.&Apache::loncommon::start_data_table_header_row().'
                   5241:             <th colspan="2">
1.492     albertel 5242:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5243:             </th>
                   5244:        '.&Apache::loncommon::end_data_table_header_row().'
                   5245:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5246:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5247:        '.&Apache::loncommon::end_data_table_row().'
                   5248:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5249:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5250:        '.&Apache::loncommon::end_data_table_row().'
                   5251:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5252:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5253:        '.&Apache::loncommon::end_data_table_row().'
                   5254:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5255:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5256:        '.&Apache::loncommon::end_data_table_row().'
                   5257:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5258:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5259:        '.&Apache::loncommon::end_data_table_row().'
                   5260:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5261: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5262:             <td>
1.492     albertel 5263: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5264:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5265:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5266: 	    </td>
1.489     albertel 5267:        '.&Apache::loncommon::end_data_table_row().'
                   5268:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5269:             <td colspan="2">
1.572     www      5270:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5271:             </td>
1.489     albertel 5272:        '.&Apache::loncommon::end_data_table_row().'
                   5273:     '.&Apache::loncommon::end_data_table().'
                   5274:     </form>
                   5275: ';
1.162     albertel 5276:    
                   5277:     $r->print($result);
                   5278: 
1.422     foxr     5279: 
                   5280: 
                   5281:     # Chunk of the form that prompts to view a scoring office file,
                   5282:     # corrected file, skipped records in a file.
                   5283: 
1.489     albertel 5284:     $r->print('
                   5285:    <br />
                   5286:    <form action="/adm/grades" name="scantron_download">
                   5287:      '.$default_form_data.'
                   5288:      <input type="hidden" name="command" value="scantron_download" />
                   5289:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5290:        '.&Apache::loncommon::start_data_table_header_row().'
                   5291:               <th>
1.492     albertel 5292:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5293:               </th>
                   5294:        '.&Apache::loncommon::end_data_table_header_row().'
                   5295:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5296:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5297:                 <br />
1.492     albertel 5298:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5299:        '.&Apache::loncommon::end_data_table_row().'
                   5300:      '.&Apache::loncommon::end_data_table().'
                   5301:    </form>
                   5302:    <br />
                   5303: ');
1.162     albertel 5304: 
1.457     banghart 5305:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5306: 
1.528     raeburn  5307:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5308:              $default_form_data."\n".
                   5309:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5310:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5311:              '<th colspan="2">
1.572     www      5312:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5313:              '</th>'."\n".
                   5314:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5315:               &Apache::loncommon::start_data_table_row()."\n".
                   5316:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5317:               '<td> '.$sequence_selector.' </td>'.
                   5318:               &Apache::loncommon::end_data_table_row()."\n".
                   5319:               &Apache::loncommon::start_data_table_row()."\n".
                   5320:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5321:               '<td> '.$file_selector.' </td>'."\n".
                   5322:               &Apache::loncommon::end_data_table_row()."\n".
                   5323:               &Apache::loncommon::start_data_table_row()."\n".
                   5324:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5325:               '<td> '.$format_selector.' </td>'."\n".
                   5326:               &Apache::loncommon::end_data_table_row()."\n".
                   5327:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5328:               '<td> '.&mt('Options').' </td>'."\n".
                   5329:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5330:               &Apache::loncommon::end_data_table_row()."\n".
                   5331:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5332:               '<td colspan="2">'."\n".
                   5333:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5334:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5335:               '</td>'."\n".
                   5336:               &Apache::loncommon::end_data_table_row()."\n".
                   5337:               &Apache::loncommon::end_data_table()."\n".
                   5338:               '</form><br />');
                   5339:     return;
1.75      albertel 5340: }
                   5341: 
1.423     albertel 5342: =pod
                   5343: 
                   5344: =item get_scantron_config
                   5345: 
                   5346:    Parse and return the scantron configuration line selected as a
                   5347:    hash of configuration file fields.
                   5348: 
                   5349:  Arguments:
                   5350:     which - the name of the configuration to parse from the file.
                   5351: 
                   5352: 
                   5353:  Returns:
                   5354:             If the named configuration is not in the file, an empty
                   5355:             hash is returned.
                   5356:     a hash with the fields
                   5357:       name         - internal name for the this configuration setup
                   5358:       description  - text to display to operator that describes this config
                   5359:       CODElocation - if 0 or the string 'none'
                   5360:                           - no CODE exists for this config
                   5361:                      if -1 || the string 'letter'
                   5362:                           - a CODE exists for this config and is
                   5363:                             a string of letters
                   5364:                      Unsupported value (but planned for future support)
                   5365:                           if a positive integer
                   5366:                                - The CODE exists as the first n items from
                   5367:                                  the question section of the form
                   5368:                           if the string 'number'
                   5369:                                - The CODE exists for this config and is
                   5370:                                  a string of numbers
                   5371:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5372:                      the CODE starts
                   5373:       CODElength  - length of the CODE
1.573     bisitz   5374:       IDstart     - column where the student/employee ID starts
1.556     weissno  5375:       IDlength    - length of the student/employee ID info
1.423     albertel 5376:       Qstart      - column where the information from the bubbled
                   5377:                     'questions' start
                   5378:       Qlength     - number of columns comprising a single bubble line from
                   5379:                     the sheet. (usually either 1 or 10)
1.424     albertel 5380:       Qon         - either a single character representing the character used
1.423     albertel 5381:                     to signal a bubble was chosen in the positional setup, or
                   5382:                     the string 'letter' if the letter of the chosen bubble is
                   5383:                     in the final, or 'number' if a number representing the
                   5384:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5385:       Qoff        - the character used to represent that a bubble was
                   5386:                     left blank
1.423     albertel 5387:       PaperID     - if the scanning process generates a unique number for each
                   5388:                     sheet scanned the column that this ID number starts in
                   5389:       PaperIDlength - number of columns that comprise the unique ID number
                   5390:                       for the sheet of paper
1.424     albertel 5391:       FirstName   - column that the first name starts in
1.423     albertel 5392:       FirstNameLength - number of columns that the first name spans
                   5393:  
                   5394:       LastName    - column that the last name starts in
                   5395:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5396:       BubblesPerRow - number of bubbles available in each row used to 
                   5397:                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5398: =cut
1.422     foxr     5399: 
1.82      albertel 5400: sub get_scantron_config {
                   5401:     my ($which) = @_;
1.518     raeburn  5402:     my @lines = &get_scantronformat_file();
1.82      albertel 5403:     my %config;
1.157     albertel 5404:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5405:     foreach my $line (@lines) {
1.82      albertel 5406: 	my ($name,$descrip)=split(/:/,$line);
                   5407: 	if ($name ne $which ) { next; }
                   5408: 	chomp($line);
                   5409: 	my @config=split(/:/,$line);
                   5410: 	$config{'name'}=$config[0];
                   5411: 	$config{'description'}=$config[1];
                   5412: 	$config{'CODElocation'}=$config[2];
                   5413: 	$config{'CODEstart'}=$config[3];
                   5414: 	$config{'CODElength'}=$config[4];
                   5415: 	$config{'IDstart'}=$config[5];
                   5416: 	$config{'IDlength'}=$config[6];
                   5417: 	$config{'Qstart'}=$config[7];
1.497     foxr     5418:  	$config{'Qlength'}=$config[8];
1.82      albertel 5419: 	$config{'Qoff'}=$config[9];
                   5420: 	$config{'Qon'}=$config[10];
1.157     albertel 5421: 	$config{'PaperID'}=$config[11];
                   5422: 	$config{'PaperIDlength'}=$config[12];
                   5423: 	$config{'FirstName'}=$config[13];
                   5424: 	$config{'FirstNamelength'}=$config[14];
                   5425: 	$config{'LastName'}=$config[15];
                   5426: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5427:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5428: 	last;
                   5429:     }
                   5430:     return %config;
                   5431: }
                   5432: 
1.423     albertel 5433: =pod 
                   5434: 
                   5435: =item username_to_idmap
                   5436: 
1.556     weissno  5437:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5438:     student username:domain.
                   5439: 
                   5440:   Arguments:
                   5441: 
                   5442:     $classlist - reference to the class list hash. This is a hash
                   5443:                  keyed by student name:domain  whose elements are references
1.424     albertel 5444:                  to arrays containing various chunks of information
1.423     albertel 5445:                  about the student. (See loncoursedata for more info).
                   5446: 
                   5447:   Returns
                   5448:     %idmap - the constructed hash
                   5449: 
                   5450: =cut
                   5451: 
1.82      albertel 5452: sub username_to_idmap {
                   5453:     my ($classlist)= @_;
                   5454:     my %idmap;
                   5455:     foreach my $student (keys(%$classlist)) {
                   5456: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5457: 	    $student;
                   5458:     }
                   5459:     return %idmap;
                   5460: }
1.423     albertel 5461: 
                   5462: =pod
                   5463: 
1.424     albertel 5464: =item scantron_fixup_scanline
1.423     albertel 5465: 
                   5466:    Process a requested correction to a scanline.
                   5467: 
                   5468:   Arguments:
                   5469:     $scantron_config   - hash from &get_scantron_config()
                   5470:     $scan_data         - hash of correction information 
                   5471:                           (see &scantron_getfile())
                   5472:     $line              - existing scanline
                   5473:     $whichline         - line number of the passed in scanline
                   5474:     $field             - type of change to process 
                   5475:                          (either 
1.573     bisitz   5476:                           'ID'     -> correct the student/employee ID
1.423     albertel 5477:                           'CODE'   -> correct the CODE
                   5478:                           'answer' -> fixup the submitted answers)
                   5479:     
                   5480:    $args               - hash of additional info,
                   5481:                           - 'ID' 
                   5482:                                'newid' -> studentID to use in replacement
1.424     albertel 5483:                                           of existing one
1.423     albertel 5484:                           - 'CODE' 
                   5485:                                'CODE_ignore_dup' - set to true if duplicates
                   5486:                                                    should be ignored.
                   5487: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5488:                                         if the existing unfound code should
1.423     albertel 5489:                                         be used as is
                   5490:                           - 'answer'
                   5491:                                'response' - new answer or 'none' if blank
                   5492:                                'question' - the bubble line to change
1.503     raeburn  5493:                                'questionnum' - the question identifier,
                   5494:                                                may include subquestion. 
1.423     albertel 5495: 
                   5496:   Returns:
                   5497:     $line - the modified scanline
                   5498: 
                   5499:   Side effects: 
                   5500:     $scan_data - may be updated
                   5501: 
                   5502: =cut
                   5503: 
1.82      albertel 5504: 
1.157     albertel 5505: sub scantron_fixup_scanline {
                   5506:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5507:     if ($field eq 'ID') {
                   5508: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5509: 	    return ($line,1,'New value too large');
1.157     albertel 5510: 	}
                   5511: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5512: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5513: 				     $args->{'newid'});
                   5514: 	}
                   5515: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5516: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5517: 	if ($args->{'newid'}=~/^\s*$/) {
                   5518: 	    &scan_data($scan_data,"$whichline.user",
                   5519: 		       $args->{'username'}.':'.$args->{'domain'});
                   5520: 	}
1.186     albertel 5521:     } elsif ($field eq 'CODE') {
1.192     albertel 5522: 	if ($args->{'CODE_ignore_dup'}) {
                   5523: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5524: 	}
                   5525: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5526: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5527: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5528: 		return ($line,1,'New CODE value too large');
                   5529: 	    }
                   5530: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5531: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5532: 	    }
                   5533: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5534: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5535: 	}
1.157     albertel 5536:     } elsif ($field eq 'answer') {
1.497     foxr     5537: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5538: 	my $off=$scantron_config->{'Qoff'};
                   5539: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5540: 	my $answer=${off}x$length;
                   5541: 	if ($args->{'response'} eq 'none') {
                   5542: 	    &scan_data($scan_data,
1.503     raeburn  5543: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5544: 	} else {
                   5545: 	    if ($on eq 'letter') {
                   5546: 		my @alphabet=('A'..'Z');
                   5547: 		$answer=$alphabet[$args->{'response'}];
                   5548: 	    } elsif ($on eq 'number') {
                   5549: 		$answer=$args->{'response'}+1;
                   5550: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5551: 	    } else {
1.497     foxr     5552: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5553: 	    }
1.497     foxr     5554: 	    &scan_data($scan_data,
1.503     raeburn  5555: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5556: 	}
1.497     foxr     5557: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5558: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5559:     }
                   5560:     return $line;
                   5561: }
1.423     albertel 5562: 
                   5563: =pod
                   5564: 
                   5565: =item scan_data
                   5566: 
                   5567:     Edit or look up  an item in the scan_data hash.
                   5568: 
                   5569:   Arguments:
                   5570:     $scan_data  - The hash (see scantron_getfile)
                   5571:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5572:                   scantronfilename_key).
1.423     albertel 5573:     $data        - New value of the hash entry.
                   5574:     $delete      - If true, the entry is removed from the hash.
                   5575: 
                   5576:   Returns:
                   5577:     The new value of the hash table field (undefined if deleted).
                   5578: 
                   5579: =cut
                   5580: 
                   5581: 
1.157     albertel 5582: sub scan_data {
                   5583:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5584:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5585:     if (defined($value)) {
                   5586: 	$scan_data->{$filename.'_'.$key} = $value;
                   5587:     }
                   5588:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5589:     return $scan_data->{$filename.'_'.$key};
                   5590: }
1.423     albertel 5591: 
1.495     albertel 5592: # ----- These first few routines are general use routines.----
                   5593: 
                   5594: # Return the number of occurences of a pattern in a string.
                   5595: 
                   5596: sub occurence_count {
                   5597:     my ($string, $pattern) = @_;
                   5598: 
                   5599:     my @matches = ($string =~ /$pattern/g);
                   5600: 
                   5601:     return scalar(@matches);
                   5602: }
                   5603: 
                   5604: 
                   5605: # Take a string known to have digits and convert all the
                   5606: # digits into letters in the range J,A..I.
                   5607: 
                   5608: sub digits_to_letters {
                   5609:     my ($input) = @_;
                   5610: 
                   5611:     my @alphabet = ('J', 'A'..'I');
                   5612: 
                   5613:     my @input    = split(//, $input);
                   5614:     my $output ='';
                   5615:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5616: 	if ($input[$i] =~ /\d/) {
                   5617: 	    $output .= $alphabet[$input[$i]];
                   5618: 	} else {
                   5619: 	    $output .= $input[$i];
                   5620: 	}
                   5621:     }
                   5622:     return $output;
                   5623: }
                   5624: 
1.423     albertel 5625: =pod 
                   5626: 
                   5627: =item scantron_parse_scanline
                   5628: 
                   5629:   Decodes a scanline from the selected scantron file
                   5630: 
                   5631:  Arguments:
                   5632:     line             - The text of the scantron file line to process
                   5633:     whichline        - Line number
                   5634:     scantron_config  - Hash describing the format of the scantron lines.
                   5635:     scan_data        - Hash of extra information about the scanline
                   5636:                        (see scantron_getfile for more information)
                   5637:     just_header      - True if should not process question answers but only
                   5638:                        the stuff to the left of the answers.
                   5639:  Returns:
                   5640:    Hash containing the result of parsing the scanline
                   5641: 
                   5642:    Keys are all proceeded by the string 'scantron.'
                   5643: 
                   5644:        CODE    - the CODE in use for this scanline
                   5645:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5646:                  by the operator
                   5647:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5648:                             CODEs were selected, but the usage has been
                   5649:                             forced by the operator
1.556     weissno  5650:        ID  - student/employee ID
1.423     albertel 5651:        PaperID - if used, the ID number printed on the sheet when the 
                   5652:                  paper was scanned
                   5653:        FirstName - first name from the sheet
                   5654:        LastName  - last name from the sheet
                   5655: 
                   5656:      if just_header was not true these key may also exist
                   5657: 
1.447     foxr     5658:        missingerror - a list of bubble ranges that are considered to be answers
                   5659:                       to a single question that don't have any bubbles filled in.
                   5660:                       Of the form questionnumber:firstbubblenumber:count.
                   5661:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5662:                       to a single question that have more than one bubble filled in.
                   5663:                       Of the form questionnumber::firstbubblenumber:count
                   5664:    
                   5665:                 In the above, count is the number of bubble responses in the
                   5666:                 input line needed to represent the possible answers to the question.
                   5667:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5668:                 per line would have count = 2.
                   5669: 
1.423     albertel 5670:        maxquest     - the number of the last bubble line that was parsed
                   5671: 
                   5672:        (<number> starts at 1)
                   5673:        <number>.answer - zero or more letters representing the selected
                   5674:                          letters from the scanline for the bubble line 
                   5675:                          <number>.
                   5676:                          if blank there was either no bubble or there where
                   5677:                          multiple bubbles, (consult the keys missingerror and
                   5678:                          doubleerror if this is an error condition)
                   5679: 
                   5680: =cut
                   5681: 
1.82      albertel 5682: sub scantron_parse_scanline {
1.423     albertel 5683:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5684: 
1.82      albertel 5685:     my %record;
1.550     raeburn  5686:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5687:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5688:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5689:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5690: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5691: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5692: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5693: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5694: 	    $record{'scantron.CODE'}=substr($data,
                   5695: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5696: 					    $$scantron_config{'CODElength'});
1.191     albertel 5697: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5698: 		$record{'scantron.useCODE'}=1;
                   5699: 	    }
1.192     albertel 5700: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5701: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5702: 	    }
1.82      albertel 5703: 	} else {
                   5704: 	    #FIXME interpret first N questions
                   5705: 	}
                   5706:     }
1.83      albertel 5707:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5708: 				  $$scantron_config{'IDlength'});
1.157     albertel 5709:     $record{'scantron.PaperID'}=
                   5710: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5711: 	       $$scantron_config{'PaperIDlength'});
                   5712:     $record{'scantron.FirstName'}=
                   5713: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5714: 	       $$scantron_config{'FirstNamelength'});
                   5715:     $record{'scantron.LastName'}=
                   5716: 	substr($data,$$scantron_config{'LastName'}-1,
                   5717: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5718:     if ($just_header) { return \%record; }
1.194     albertel 5719: 
1.82      albertel 5720:     my @alphabet=('A'..'Z');
                   5721:     my $questnum=0;
1.447     foxr     5722:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5723: 
1.470     foxr     5724:     chomp($questions);		# Get rid of any trailing \n.
                   5725:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5726:     while (length($questions)) {
1.447     foxr     5727: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5728:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5729:                              || 1;
                   5730:         $questnum++;
                   5731:         my $quest_id = $questnum;
                   5732:         my $currentquest = substr($questions,0,$answer_length);
                   5733:         $questions       = substr($questions,$answer_length);
                   5734:         if (length($currentquest) < $answer_length) { next; }
                   5735: 
                   5736:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5737:             my $subquestnum = 1;
                   5738:             my $subquestions = $currentquest;
                   5739:             my @subanswers_needed = 
                   5740:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5741:             foreach my $subans (@subanswers_needed) {
                   5742:                 my $subans_length =
                   5743:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5744:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5745:                 $subquestions   = substr($subquestions,$subans_length);
                   5746:                 $quest_id = "$questnum.$subquestnum";
                   5747:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5748:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5749:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5750:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5751:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5752:                 } else {
                   5753:                     $ansnum = &scantron_validator_positional($ansnum,
                   5754:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5755:                 }
                   5756:                 $subquestnum ++;
                   5757:             }
                   5758:         } else {
                   5759:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5760:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5761:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5762:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5763:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5764:             } else {
                   5765:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5766:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5767:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5768:             }
                   5769:         }
                   5770:     }
                   5771:     $record{'scantron.maxquest'}=$questnum;
                   5772:     return \%record;
                   5773: }
1.447     foxr     5774: 
1.503     raeburn  5775: sub scantron_validator_lettnum {
                   5776:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5777:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5778: 
                   5779:     # Qon 'letter' implies for each slot in currquest we have:
                   5780:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5781:     #    about anything else (esp. a value of Qoff) for missing
                   5782:     #    bubbles.
                   5783:     #
                   5784:     # Qon 'number' implies each slot gives a digit that indexes the
                   5785:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5786:     #    and * or ? for double bubbles on a single line.
                   5787:     #
1.447     foxr     5788: 
1.503     raeburn  5789:     my $matchon;
                   5790:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5791:         $matchon = '[A-Z]';
                   5792:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5793:         $matchon = '\d';
                   5794:     }
                   5795:     my $occurrences = 0;
                   5796:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5797:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5798:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5799:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5800:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5801:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5802:         my @singlelines = split('',$currquest);
                   5803:         foreach my $entry (@singlelines) {
                   5804:             $occurrences = &occurence_count($entry,$matchon);
                   5805:             if ($occurrences > 1) {
                   5806:                 last;
                   5807:             }
                   5808:         } 
                   5809:     } else {
                   5810:         $occurrences = &occurence_count($currquest,$matchon); 
                   5811:     }
                   5812:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5813:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5814:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5815:             my $bubble = substr($currquest,$ans,1);
                   5816:             if ($bubble =~ /$matchon/ ) {
                   5817:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5818:                     if ($bubble == 0) {
                   5819:                         $bubble = 10; 
                   5820:                     }
                   5821:                     $record->{"scantron.$ansnum.answer"} = 
                   5822:                         $alphabet->[$bubble-1];
                   5823:                 } else {
                   5824:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5825:                 }
                   5826:             } else {
                   5827:                 $record->{"scantron.$ansnum.answer"}='';
                   5828:             }
                   5829:             $ansnum++;
                   5830:         }
                   5831:     } elsif (!defined($currquest)
                   5832:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5833:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5834:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5835:             $record->{"scantron.$ansnum.answer"}='';
                   5836:             $ansnum++;
                   5837:         }
                   5838:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5839:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5840:         }
                   5841:     } else {
                   5842:         if ($$scantron_config{'Qon'} eq 'number') {
                   5843:             $currquest = &digits_to_letters($currquest);            
                   5844:         }
                   5845:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5846:             my $bubble = substr($currquest,$ans,1);
                   5847:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5848:             $ansnum++;
                   5849:         }
                   5850:     }
                   5851:     return $ansnum;
                   5852: }
1.447     foxr     5853: 
1.503     raeburn  5854: sub scantron_validator_positional {
                   5855:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5856:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5857: 
1.503     raeburn  5858:     # Otherwise there's a positional notation;
                   5859:     # each bubble line requires Qlength items, and there are filled in
                   5860:     # bubbles for each case where there 'Qon' characters.
                   5861:     #
1.447     foxr     5862: 
1.503     raeburn  5863:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5864: 
1.503     raeburn  5865:     # If the split only gives us one element.. the full length of the
                   5866:     # answer string, no bubbles are filled in:
1.447     foxr     5867: 
1.507     raeburn  5868:     if ($answers_needed eq '') {
                   5869:         return;
                   5870:     }
                   5871: 
1.503     raeburn  5872:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5873:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5874:             $record->{"scantron.$ansnum.answer"}='';
                   5875:             $ansnum++;
                   5876:         }
                   5877:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5878:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5879:         }
                   5880:     } elsif (scalar(@array) == 2) {
                   5881:         my $location = length($array[0]);
                   5882:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5883:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5884:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5885:             if ($ans eq $line_num) {
                   5886:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5887:             } else {
                   5888:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5889:             }
                   5890:             $ansnum++;
                   5891:          }
                   5892:     } else {
                   5893:         #  If there's more than one instance of a bubble character
                   5894:         #  That's a double bubble; with positional notation we can
                   5895:         #  record all the bubbles filled in as well as the
                   5896:         #  fact this response consists of multiple bubbles.
                   5897:         #
                   5898:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5899:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5900:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5901:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5902:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5903:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5904:             my $doubleerror = 0;
                   5905:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5906:                    (!$doubleerror)) {
                   5907:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5908:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5909:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5910:                if (length(@currarray) > 2) {
                   5911:                    $doubleerror = 1;
                   5912:                } 
                   5913:             }
                   5914:             if ($doubleerror) {
                   5915:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5916:             }
                   5917:         } else {
                   5918:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5919:         }
                   5920:         my $item = $ansnum;
                   5921:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5922:             $record->{"scantron.$item.answer"} = '';
                   5923:             $item ++;
                   5924:         }
1.447     foxr     5925: 
1.503     raeburn  5926:         my @ans=@array;
                   5927:         my $i=0;
                   5928:         my $increment = 0;
                   5929:         while ($#ans) {
                   5930:             $i+=length($ans[0]) + $increment;
                   5931:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5932:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5933:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5934:             shift(@ans);
                   5935:             $increment = 1;
                   5936:         }
                   5937:         $ansnum += $answers_needed;
1.82      albertel 5938:     }
1.503     raeburn  5939:     return $ansnum;
1.82      albertel 5940: }
                   5941: 
1.423     albertel 5942: =pod
                   5943: 
                   5944: =item scantron_add_delay
                   5945: 
                   5946:    Adds an error message that occurred during the grading phase to a
                   5947:    queue of messages to be shown after grading pass is complete
                   5948: 
                   5949:  Arguments:
1.424     albertel 5950:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5951:    $scanline    - the scanline that caused the error
                   5952:    $errormesage - the error message
                   5953:    $errorcode   - a numeric code for the error
                   5954: 
                   5955:  Side Effects:
1.424     albertel 5956:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5957: 
                   5958: =cut
                   5959: 
1.82      albertel 5960: sub scantron_add_delay {
1.140     albertel 5961:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5962:     push(@$delayqueue,
                   5963: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5964: 	  'ecode' => $errorcode }
                   5965: 	 );
1.82      albertel 5966: }
                   5967: 
1.423     albertel 5968: =pod
                   5969: 
                   5970: =item scantron_find_student
                   5971: 
1.424     albertel 5972:    Finds the username for the current scanline
                   5973: 
                   5974:   Arguments:
                   5975:    $scantron_record - hash result from scantron_parse_scanline
                   5976:    $scan_data       - hash of correction information 
                   5977:                       (see &scantron_getfile() form more information)
                   5978:    $idmap           - hash from &username_to_idmap()
                   5979:    $line            - number of current scanline
                   5980:  
                   5981:   Returns:
                   5982:    Either 'username:domain' or undef if unknown
                   5983: 
1.423     albertel 5984: =cut
                   5985: 
1.82      albertel 5986: sub scantron_find_student {
1.157     albertel 5987:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5988:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5989:     if ($scanID =~ /^\s*$/) {
                   5990:  	return &scan_data($scan_data,"$line.user");
                   5991:     }
1.83      albertel 5992:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5993:  	if (lc($id) eq lc($scanID)) {
                   5994:  	    return $$idmap{$id};
                   5995:  	}
1.83      albertel 5996:     }
                   5997:     return undef;
                   5998: }
                   5999: 
1.423     albertel 6000: =pod
                   6001: 
                   6002: =item scantron_filter
                   6003: 
1.424     albertel 6004:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6005:    hidden resources was selected
                   6006: 
1.423     albertel 6007: =cut
                   6008: 
1.83      albertel 6009: sub scantron_filter {
                   6010:     my ($curres)=@_;
1.331     albertel 6011: 
                   6012:     if (ref($curres) && $curres->is_problem()) {
                   6013: 	# if the user has asked to not have either hidden
                   6014: 	# or 'randomout' controlled resources to be graded
                   6015: 	# don't include them
                   6016: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6017: 	    && $curres->randomout) {
                   6018: 	    return 0;
                   6019: 	}
1.83      albertel 6020: 	return 1;
                   6021:     }
                   6022:     return 0;
1.82      albertel 6023: }
                   6024: 
1.423     albertel 6025: =pod
                   6026: 
                   6027: =item scantron_process_corrections
                   6028: 
1.424     albertel 6029:    Gets correction information out of submitted form data and corrects
                   6030:    the scanline
                   6031: 
1.423     albertel 6032: =cut
                   6033: 
1.157     albertel 6034: sub scantron_process_corrections {
                   6035:     my ($r) = @_;
1.257     albertel 6036:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6037:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6038:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6039:     my $which=$env{'form.scantron_line'};
1.200     albertel 6040:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6041:     my ($skip,$err,$errmsg);
1.257     albertel 6042:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6043: 	$skip=1;
1.257     albertel 6044:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6045: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6046: 	    $env{'form.scantron_domain'};
1.157     albertel 6047: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6048: 	($line,$err,$errmsg)=
                   6049: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6050: 				     'ID',{'newid'=>$newid,
1.257     albertel 6051: 				    'username'=>$env{'form.scantron_username'},
                   6052: 				    'domain'=>$env{'form.scantron_domain'}});
                   6053:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6054: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6055: 	my $newCODE;
1.192     albertel 6056: 	my %args;
1.190     albertel 6057: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6058: 	    $newCODE='use_unfound';
1.190     albertel 6059: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6060: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6061: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6062: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6063: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6064: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6065: 	}
1.257     albertel 6066: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6067: 	    $args{'CODE_ignore_dup'}=1;
                   6068: 	}
                   6069: 	$args{'CODE'}=$newCODE;
1.186     albertel 6070: 	($line,$err,$errmsg)=
                   6071: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6072: 				     'CODE',\%args);
1.257     albertel 6073:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6074: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6075: 	    ($line,$err,$errmsg)=
                   6076: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6077: 					 $which,'answer',
                   6078: 					 { 'question'=>$question,
1.503     raeburn  6079: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6080:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6081: 	    if ($err) { last; }
                   6082: 	}
                   6083:     }
                   6084:     if ($err) {
1.398     albertel 6085: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6086:     } else {
1.200     albertel 6087: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6088: 	&scantron_putfile($scanlines,$scan_data);
                   6089:     }
                   6090: }
                   6091: 
1.423     albertel 6092: =pod
                   6093: 
                   6094: =item reset_skipping_status
                   6095: 
1.424     albertel 6096:    Forgets the current set of remember skipped scanlines (and thus
                   6097:    reverts back to considering all lines in the
                   6098:    scantron_skipped_<filename> file)
                   6099: 
1.423     albertel 6100: =cut
                   6101: 
1.200     albertel 6102: sub reset_skipping_status {
                   6103:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6104:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6105:     &scantron_putfile(undef,$scan_data);
                   6106: }
                   6107: 
1.423     albertel 6108: =pod
                   6109: 
                   6110: =item start_skipping
                   6111: 
1.424     albertel 6112:    Marks a scanline to be skipped. 
                   6113: 
1.423     albertel 6114: =cut
                   6115: 
1.376     albertel 6116: sub start_skipping {
1.200     albertel 6117:     my ($scan_data,$i)=@_;
                   6118:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6119:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6120: 	$remembered{$i}=2;
                   6121:     } else {
                   6122: 	$remembered{$i}=1;
                   6123:     }
1.200     albertel 6124:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6125: }
                   6126: 
1.423     albertel 6127: =pod
                   6128: 
                   6129: =item should_be_skipped
                   6130: 
1.424     albertel 6131:    Checks whether a scanline should be skipped.
                   6132: 
1.423     albertel 6133: =cut
                   6134: 
1.200     albertel 6135: sub should_be_skipped {
1.376     albertel 6136:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6137:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6138: 	# not redoing old skips
1.376     albertel 6139: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6140: 	return 0;
                   6141:     }
                   6142:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6143: 
                   6144:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6145: 	return 0;
                   6146:     }
1.200     albertel 6147:     return 1;
                   6148: }
                   6149: 
1.423     albertel 6150: =pod
                   6151: 
                   6152: =item remember_current_skipped
                   6153: 
1.424     albertel 6154:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6155:    file and remembers them into scan_data for later use.
                   6156: 
1.423     albertel 6157: =cut
                   6158: 
1.200     albertel 6159: sub remember_current_skipped {
                   6160:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6161:     my %to_remember;
                   6162:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6163: 	if ($scanlines->{'skipped'}[$i]) {
                   6164: 	    $to_remember{$i}=1;
                   6165: 	}
                   6166:     }
1.376     albertel 6167: 
1.200     albertel 6168:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6169:     &scantron_putfile(undef,$scan_data);
                   6170: }
                   6171: 
1.423     albertel 6172: =pod
                   6173: 
                   6174: =item check_for_error
                   6175: 
1.424     albertel 6176:     Checks if there was an error when attempting to remove a specific
                   6177:     scantron_.. bubble sheet data file. Prints out an error if
                   6178:     something went wrong.
                   6179: 
1.423     albertel 6180: =cut
                   6181: 
1.200     albertel 6182: sub check_for_error {
                   6183:     my ($r,$result)=@_;
                   6184:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6185: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6186:     }
                   6187: }
1.157     albertel 6188: 
1.423     albertel 6189: =pod
                   6190: 
                   6191: =item scantron_warning_screen
                   6192: 
1.424     albertel 6193:    Interstitial screen to make sure the operator has selected the
                   6194:    correct options before we start the validation phase.
                   6195: 
1.423     albertel 6196: =cut
                   6197: 
1.203     albertel 6198: sub scantron_warning_screen {
1.650     raeburn  6199:     my ($button_text,$symb)=@_;
1.257     albertel 6200:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6201:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6202:     my $CODElist;
1.284     albertel 6203:     if ($scantron_config{'CODElocation'} &&
                   6204: 	$scantron_config{'CODEstart'} &&
                   6205: 	$scantron_config{'CODElength'}) {
                   6206: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6207: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6208: 	$CODElist=
1.492     albertel 6209: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6210: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6211:     }
1.492     albertel 6212:     return ('
1.203     albertel 6213: <p>
1.492     albertel 6214: <span class="LC_warning">
                   6215: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6216: </p>
                   6217: <table>
1.492     albertel 6218: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6219: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6220: '.$CODElist.'
1.203     albertel 6221: </table>
1.650     raeburn  6222: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6223: '.&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 6224: 
                   6225: <br />
1.492     albertel 6226: ');
1.203     albertel 6227: }
                   6228: 
1.423     albertel 6229: =pod
                   6230: 
                   6231: =item scantron_do_warning
                   6232: 
1.424     albertel 6233:    Check if the operator has picked something for all required
                   6234:    fields. Error out if something is missing.
                   6235: 
1.423     albertel 6236: =cut
                   6237: 
1.203     albertel 6238: sub scantron_do_warning {
1.608     www      6239:     my ($r,$symb)=@_;
1.203     albertel 6240:     if (!$symb) {return '';}
1.324     albertel 6241:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6242:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6243:     if ( $env{'form.selectpage'} eq '' ||
                   6244: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6245: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6246: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6247: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6248: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6249: 	} 
1.257     albertel 6250: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6251: 	    $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 6252: 	} 
1.257     albertel 6253: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6254: 	    $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 6255: 	} 
                   6256:     } else {
1.650     raeburn  6257: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.492     albertel 6258: 	$r->print('
                   6259: '.$warning.'
                   6260: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6261: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6262: ');
1.237     albertel 6263:     }
1.614     www      6264:     $r->print("</form><br />");
1.203     albertel 6265:     return '';
                   6266: }
                   6267: 
1.423     albertel 6268: =pod
                   6269: 
                   6270: =item scantron_form_start
                   6271: 
1.424     albertel 6272:     html hidden input for remembering all selected grading options
                   6273: 
1.423     albertel 6274: =cut
                   6275: 
1.203     albertel 6276: sub scantron_form_start {
                   6277:     my ($max_bubble)=@_;
                   6278:     my $result= <<SCANTRONFORM;
                   6279: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6280:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6281:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6282:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6283:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6284:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6285:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6286:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6287:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6288:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6289: SCANTRONFORM
1.447     foxr     6290: 
                   6291:   my $line = 0;
                   6292:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6293:        my $chunk =
                   6294: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6295:        $chunk .=
                   6296: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6297:        $chunk .= 
                   6298:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6299:        $chunk .=
                   6300:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6301:        $result .= $chunk;
                   6302:        $line++;
                   6303:    }
1.203     albertel 6304:     return $result;
                   6305: }
                   6306: 
1.423     albertel 6307: =pod
                   6308: 
                   6309: =item scantron_validate_file
                   6310: 
1.424     albertel 6311:     Dispatch routine for doing validation of a bubble sheet data file.
                   6312: 
                   6313:     Also processes any necessary information resets that need to
                   6314:     occur before validation begins (ignore previous corrections,
                   6315:     restarting the skipped records processing)
                   6316: 
1.423     albertel 6317: =cut
                   6318: 
1.157     albertel 6319: sub scantron_validate_file {
1.608     www      6320:     my ($r,$symb) = @_;
1.157     albertel 6321:     if (!$symb) {return '';}
1.324     albertel 6322:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6323:     
                   6324:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6325:     # them when doing the corrections reset
1.257     albertel 6326:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6327: 	&reset_skipping_status();
                   6328:     }
1.257     albertel 6329:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6330: 	&remember_current_skipped();
1.257     albertel 6331: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6332:     }
                   6333: 
1.257     albertel 6334:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6335: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6336: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6337: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6338: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6339:     }
1.200     albertel 6340: 
1.257     albertel 6341:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6342: 	&scantron_process_corrections($r);
                   6343:     }
1.503     raeburn  6344:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6345:     #get the student pick code ready
                   6346:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6347:     my $nav_error;
1.649     raeburn  6348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6349:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6350:     if ($nav_error) {
                   6351:         $r->print(&navmap_errormsg());
                   6352:         return '';
                   6353:     }
1.203     albertel 6354:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6355:     $r->print($result);
                   6356:     
1.334     albertel 6357:     my @validate_phases=( 'sequence',
                   6358: 			  'ID',
1.157     albertel 6359: 			  'CODE',
                   6360: 			  'doublebubble',
                   6361: 			  'missingbubbles');
1.257     albertel 6362:     if (!$env{'form.validatepass'}) {
                   6363: 	$env{'form.validatepass'} = 0;
1.157     albertel 6364:     }
1.257     albertel 6365:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6366: 
1.448     foxr     6367: 
1.157     albertel 6368:     my $stop=0;
                   6369:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6370: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6371: 	$r->rflush();
                   6372: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6373: 	{
                   6374: 	    no strict 'refs';
                   6375: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6376: 	}
                   6377:     }
                   6378:     if (!$stop) {
1.650     raeburn  6379: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6380: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6381:                   $warning.
                   6382:                   &mt('Perform verification for each student after storage of submissions?').
                   6383:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6384:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6385:                   ('&nbsp;'x3).'<label>'.
                   6386:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6387:                   '</label></span><br />'.
                   6388:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6389:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6390:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6391:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6392:     } else {
                   6393: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6394: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6395:     }
                   6396:     if ($stop) {
1.334     albertel 6397: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6398: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6399: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6400: 
1.650     raeburn  6401: 	    $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 6402: 	} else {
1.503     raeburn  6403:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6404: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6405:             } else {
1.539     riegler  6406:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6407:             }
1.492     albertel 6408: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6409: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6410: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6411: 	}
1.157     albertel 6412:     }
1.614     www      6413:     $r->print(" </form><br />");
1.157     albertel 6414:     return '';
                   6415: }
                   6416: 
1.423     albertel 6417: 
                   6418: =pod
                   6419: 
                   6420: =item scantron_remove_file
                   6421: 
1.424     albertel 6422:    Removes the requested bubble sheet data file, makes sure that
                   6423:    scantron_original_<filename> is never removed
                   6424: 
                   6425: 
1.423     albertel 6426: =cut
                   6427: 
1.200     albertel 6428: sub scantron_remove_file {
1.192     albertel 6429:     my ($which)=@_;
1.257     albertel 6430:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6431:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6432:     my $file='scantron_';
1.200     albertel 6433:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6434: 	$file.=$which.'_';
1.192     albertel 6435:     } else {
                   6436: 	return 'refused';
                   6437:     }
1.257     albertel 6438:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6439:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6440: }
                   6441: 
1.423     albertel 6442: 
                   6443: =pod
                   6444: 
                   6445: =item scantron_remove_scan_data
                   6446: 
1.424     albertel 6447:    Removes all scan_data correction for the requested bubble sheet
                   6448:    data file.  (In the case that both the are doing skipped records we need
                   6449:    to remember the old skipped lines for the time being so that element
                   6450:    persists for a while.)
                   6451: 
1.423     albertel 6452: =cut
                   6453: 
1.200     albertel 6454: sub scantron_remove_scan_data {
1.257     albertel 6455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6457:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6458:     my @todelete;
1.257     albertel 6459:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6460:     foreach my $key (@keys) {
                   6461: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6462: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6463: 		$key=~/remember_skipping/) {
                   6464: 		next;
                   6465: 	    }
1.192     albertel 6466: 	    push(@todelete,$key);
                   6467: 	}
                   6468:     }
1.200     albertel 6469:     my $result;
1.192     albertel 6470:     if (@todelete) {
1.491     albertel 6471: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6472: 				       \@todelete,$cdom,$cname);
                   6473:     } else {
                   6474: 	$result = 'ok';
1.192     albertel 6475:     }
                   6476:     return $result;
                   6477: }
                   6478: 
1.423     albertel 6479: 
                   6480: =pod
                   6481: 
                   6482: =item scantron_getfile
                   6483: 
1.424     albertel 6484:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6485:     the scan_data hash
                   6486:   
                   6487:   Arguments:
                   6488:     None
                   6489: 
                   6490:   Returns:
                   6491:     2 hash references
                   6492: 
                   6493:      - first one has 
                   6494:          orig      -
                   6495:          corrected -
                   6496:          skipped   -  each of which points to an array ref of the specified
                   6497:                       file broken up into individual lines
                   6498:          count     - number of scanlines
                   6499:  
                   6500:      - second is the scan_data hash possible keys are
1.425     albertel 6501:        ($number refers to scanline numbered $number and thus the key affects
                   6502:         only that scanline
                   6503:         $bubline refers to the specific bubble line element and the aspects
                   6504:         refers to that specific bubble line element)
                   6505: 
                   6506:        $number.user - username:domain to use
                   6507:        $number.CODE_ignore_dup 
                   6508:                     - ignore the duplicate CODE error 
                   6509:        $number.useCODE
                   6510:                     - use the CODE in the scanline as is
                   6511:        $number.no_bubble.$bubline
                   6512:                     - it is valid that there is no bubbled in bubble
                   6513:                       at $number $bubline
                   6514:        remember_skipping
                   6515:                     - a frozen hash containing keys of $number and values
                   6516:                       of either 
                   6517:                         1 - we are on a 'do skipped records pass' and plan
                   6518:                             on processing this line
                   6519:                         2 - we are on a 'do skipped records pass' and this
                   6520:                             scanline has been marked to skip yet again
1.424     albertel 6521: 
1.423     albertel 6522: =cut
                   6523: 
1.157     albertel 6524: sub scantron_getfile {
1.200     albertel 6525:     #FIXME really would prefer a scantron directory
1.257     albertel 6526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6528:     my $lines;
                   6529:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6530: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6531:     my %scanlines;
                   6532:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6533:     my $temp=$scanlines{'orig'};
                   6534:     $scanlines{'count'}=$#$temp;
                   6535: 
                   6536:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6537: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6538:     if ($lines eq '-1') {
                   6539: 	$scanlines{'corrected'}=[];
                   6540:     } else {
                   6541: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6542:     }
                   6543:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6544: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6545:     if ($lines eq '-1') {
                   6546: 	$scanlines{'skipped'}=[];
                   6547:     } else {
                   6548: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6549:     }
1.175     albertel 6550:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6551:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6552:     my %scan_data = @tmp;
                   6553:     return (\%scanlines,\%scan_data);
                   6554: }
                   6555: 
1.423     albertel 6556: =pod
                   6557: 
                   6558: =item lonnet_putfile
                   6559: 
1.424     albertel 6560:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6561: 
                   6562:  Arguments:
                   6563:    $contents - data to store
                   6564:    $filename - filename to store $contents into
                   6565: 
                   6566:  Returns:
                   6567:    result value from &Apache::lonnet::finishuserfileupload
                   6568: 
1.423     albertel 6569: =cut
                   6570: 
1.157     albertel 6571: sub lonnet_putfile {
                   6572:     my ($contents,$filename)=@_;
1.257     albertel 6573:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6574:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6575:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6576:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6577: 
                   6578: }
                   6579: 
1.423     albertel 6580: =pod
                   6581: 
                   6582: =item scantron_putfile
                   6583: 
1.424     albertel 6584:     Stores the current version of the bubble sheet data files, and the
                   6585:     scan_data hash. (Does not modify the original version only the
                   6586:     corrected and skipped versions.
                   6587: 
                   6588:  Arguments:
                   6589:     $scanlines - hash ref that looks like the first return value from
                   6590:                  &scantron_getfile()
                   6591:     $scan_data - hash ref that looks like the second return value from
                   6592:                  &scantron_getfile()
                   6593: 
1.423     albertel 6594: =cut
                   6595: 
1.157     albertel 6596: sub scantron_putfile {
                   6597:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6598:     #FIXME really would prefer a scantron directory
1.257     albertel 6599:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6600:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6601:     if ($scanlines) {
                   6602: 	my $prefix='scantron_';
1.157     albertel 6603: # no need to update orig, shouldn't change
                   6604: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6605: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6606: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6607: 			$prefix.'corrected_'.
1.257     albertel 6608: 			$env{'form.scantron_selectfile'});
1.200     albertel 6609: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6610: 			$prefix.'skipped_'.
1.257     albertel 6611: 			$env{'form.scantron_selectfile'});
1.200     albertel 6612:     }
1.175     albertel 6613:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6614: }
                   6615: 
1.423     albertel 6616: =pod
                   6617: 
                   6618: =item scantron_get_line
                   6619: 
1.424     albertel 6620:    Returns the correct version of the scanline
                   6621: 
                   6622:  Arguments:
                   6623:     $scanlines - hash ref that looks like the first return value from
                   6624:                  &scantron_getfile()
                   6625:     $scan_data - hash ref that looks like the second return value from
                   6626:                  &scantron_getfile()
                   6627:     $i         - number of the requested line (starts at 0)
                   6628: 
                   6629:  Returns:
                   6630:    A scanline, (either the original or the corrected one if it
                   6631:    exists), or undef if the requested scanline should be
                   6632:    skipped. (Either because it's an skipped scanline, or it's an
                   6633:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6634:    pass.
                   6635: 
1.423     albertel 6636: =cut
                   6637: 
1.157     albertel 6638: sub scantron_get_line {
1.200     albertel 6639:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6640:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6641:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6642:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6643:     return $scanlines->{'orig'}[$i]; 
                   6644: }
                   6645: 
1.423     albertel 6646: =pod
                   6647: 
                   6648: =item scantron_todo_count
                   6649: 
1.424     albertel 6650:     Counts the number of scanlines that need processing.
                   6651: 
                   6652:  Arguments:
                   6653:     $scanlines - hash ref that looks like the first return value from
                   6654:                  &scantron_getfile()
                   6655:     $scan_data - hash ref that looks like the second return value from
                   6656:                  &scantron_getfile()
                   6657: 
                   6658:  Returns:
                   6659:     $count - number of scanlines to process
                   6660: 
1.423     albertel 6661: =cut
                   6662: 
1.200     albertel 6663: sub get_todo_count {
                   6664:     my ($scanlines,$scan_data)=@_;
                   6665:     my $count=0;
                   6666:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6667: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6668: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6669: 	$count++;
                   6670:     }
                   6671:     return $count;
                   6672: }
                   6673: 
1.423     albertel 6674: =pod
                   6675: 
                   6676: =item scantron_put_line
                   6677: 
1.424     albertel 6678:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6679:     data file.
                   6680: 
                   6681:  Arguments:
                   6682:     $scanlines - hash ref that looks like the first return value from
                   6683:                  &scantron_getfile()
                   6684:     $scan_data - hash ref that looks like the second return value from
                   6685:                  &scantron_getfile()
                   6686:     $i         - line number to update
                   6687:     $newline   - contents of the updated scanline
                   6688:     $skip      - if true make the line for skipping and update the
                   6689:                  'skipped' file
                   6690: 
1.423     albertel 6691: =cut
                   6692: 
1.157     albertel 6693: sub scantron_put_line {
1.200     albertel 6694:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6695:     if ($skip) {
                   6696: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6697: 	&start_skipping($scan_data,$i);
1.157     albertel 6698: 	return;
                   6699:     }
                   6700:     $scanlines->{'corrected'}[$i]=$newline;
                   6701: }
                   6702: 
1.423     albertel 6703: =pod
                   6704: 
                   6705: =item scantron_clear_skip
                   6706: 
1.424     albertel 6707:    Remove a line from the 'skipped' file
                   6708: 
                   6709:  Arguments:
                   6710:     $scanlines - hash ref that looks like the first return value from
                   6711:                  &scantron_getfile()
                   6712:     $scan_data - hash ref that looks like the second return value from
                   6713:                  &scantron_getfile()
                   6714:     $i         - line number to update
                   6715: 
1.423     albertel 6716: =cut
                   6717: 
1.376     albertel 6718: sub scantron_clear_skip {
                   6719:     my ($scanlines,$scan_data,$i)=@_;
                   6720:     if (exists($scanlines->{'skipped'}[$i])) {
                   6721: 	undef($scanlines->{'skipped'}[$i]);
                   6722: 	return 1;
                   6723:     }
                   6724:     return 0;
                   6725: }
                   6726: 
1.423     albertel 6727: =pod
                   6728: 
                   6729: =item scantron_filter_not_exam
                   6730: 
1.424     albertel 6731:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6732:    filter out resources that are not marked as 'exam' mode
                   6733: 
1.423     albertel 6734: =cut
                   6735: 
1.334     albertel 6736: sub scantron_filter_not_exam {
                   6737:     my ($curres)=@_;
                   6738:     
                   6739:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6740: 	# if the user has asked to not have either hidden
                   6741: 	# or 'randomout' controlled resources to be graded
                   6742: 	# don't include them
                   6743: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6744: 	    && $curres->randomout) {
                   6745: 	    return 0;
                   6746: 	}
                   6747: 	return 1;
                   6748:     }
                   6749:     return 0;
                   6750: }
                   6751: 
1.423     albertel 6752: =pod
                   6753: 
                   6754: =item scantron_validate_sequence
                   6755: 
1.424     albertel 6756:     Validates the selected sequence, checking for resource that are
                   6757:     not set to exam mode.
                   6758: 
1.423     albertel 6759: =cut
                   6760: 
1.334     albertel 6761: sub scantron_validate_sequence {
                   6762:     my ($r,$currentphase) = @_;
                   6763: 
                   6764:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6765:     unless (ref($navmap)) {
                   6766:         $r->print(&navmap_errormsg());
                   6767:         return (1,$currentphase);
                   6768:     }
1.334     albertel 6769:     my (undef,undef,$sequence)=
                   6770: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6771: 
                   6772:     my $map=$navmap->getResourceByUrl($sequence);
                   6773: 
                   6774:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6775:                                     value="ignore" />');
                   6776:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6777: 	my @resources=
                   6778: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6779: 	if (@resources) {
1.357     banghart 6780: 	    $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 6781: 	    return (1,$currentphase);
                   6782: 	}
                   6783:     }
                   6784: 
                   6785:     return (0,$currentphase+1);
                   6786: }
                   6787: 
1.423     albertel 6788: 
                   6789: 
1.157     albertel 6790: sub scantron_validate_ID {
                   6791:     my ($r,$currentphase) = @_;
                   6792:     
                   6793:     #get student info
                   6794:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6795:     my %idmap=&username_to_idmap($classlist);
                   6796: 
                   6797:     #get scantron line setup
1.257     albertel 6798:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6799:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6800: 
                   6801:     my $nav_error;
1.649     raeburn  6802:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6803:     if ($nav_error) {
                   6804:         $r->print(&navmap_errormsg());
                   6805:         return(1,$currentphase);
                   6806:     }
1.157     albertel 6807: 
                   6808:     my %found=('ids'=>{},'usernames'=>{});
                   6809:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6810: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6811: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6812: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6813: 						 $scan_data);
                   6814: 	my $id=$$scan_record{'scantron.ID'};
                   6815: 	my $found;
                   6816: 	foreach my $checkid (keys(%idmap)) {
                   6817: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6818: 	}
                   6819: 	if ($found) {
                   6820: 	    my $username=$idmap{$found};
                   6821: 	    if ($found{'ids'}{$found}) {
                   6822: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6823: 					 $line,'duplicateID',$found);
1.194     albertel 6824: 		return(1,$currentphase);
1.157     albertel 6825: 	    } elsif ($found{'usernames'}{$username}) {
                   6826: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6827: 					 $line,'duplicateID',$username);
1.194     albertel 6828: 		return(1,$currentphase);
1.157     albertel 6829: 	    }
1.186     albertel 6830: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6831: 	    $found{'ids'}{$found}++;
                   6832: 	    $found{'usernames'}{$username}++;
                   6833: 	} else {
                   6834: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6835: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6836: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6837: 		    &scantron_get_correction($r,$i,$scan_record,
                   6838: 					     \%scantron_config,
                   6839: 					     $line,'duplicateID',$username);
1.194     albertel 6840: 		    return(1,$currentphase);
1.157     albertel 6841: 		} elsif (!defined($username)) {
                   6842: 		    &scantron_get_correction($r,$i,$scan_record,
                   6843: 					     \%scantron_config,
                   6844: 					     $line,'incorrectID');
1.194     albertel 6845: 		    return(1,$currentphase);
1.157     albertel 6846: 		}
                   6847: 		$found{'usernames'}{$username}++;
                   6848: 	    } else {
                   6849: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6850: 					 $line,'incorrectID');
1.194     albertel 6851: 		return(1,$currentphase);
1.157     albertel 6852: 	    }
                   6853: 	}
                   6854:     }
                   6855: 
                   6856:     return (0,$currentphase+1);
                   6857: }
                   6858: 
1.423     albertel 6859: 
1.157     albertel 6860: sub scantron_get_correction {
                   6861:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6862: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6863: #to show both the current line and the previous one and allow skipping
                   6864: #the previous one or the current one
                   6865: 
1.333     albertel 6866:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6867: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6868: 			    " for PaperID <tt>[_1]</tt>",
                   6869: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6870:     } else {
1.492     albertel 6871: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6872: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6873: 			    $i,$line)."</p> \n");
                   6874:     }
                   6875:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6876: 			  "The name on the paper is [_2],[_3]",
                   6877: 			  $$scan_record{'scantron.ID'},
                   6878: 			  $$scan_record{'scantron.LastName'},
                   6879: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6880: 
1.157     albertel 6881:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6882:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6883:                            # Array populated for doublebubble or
                   6884:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6885:                            # to validate radio button checking   
                   6886: 
1.157     albertel 6887:     if ($error =~ /ID$/) {
1.186     albertel 6888: 	if ($error eq 'incorrectID') {
1.492     albertel 6889: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6890: 		      "</p>\n");
1.157     albertel 6891: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6892: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6893: 	}
1.242     albertel 6894: 	$r->print($message);
1.492     albertel 6895: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6896: 	$r->print("\n<ul><li> ");
                   6897: 	#FIXME it would be nice if this sent back the user ID and
                   6898: 	#could do partial userID matches
                   6899: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6900: 				       'scantron_username','scantron_domain'));
                   6901: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6902: 	$r->print("\n@".
1.257     albertel 6903: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6904: 
                   6905: 	$r->print('</li>');
1.186     albertel 6906:     } elsif ($error =~ /CODE$/) {
                   6907: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6908: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6909: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6910: 	    $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 6911: 	}
1.492     albertel 6912: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6913: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6914: 	$r->print($message);
1.492     albertel 6915: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6916: 	$r->print("\n<br /> ");
1.194     albertel 6917: 	my $i=0;
1.273     albertel 6918: 	if ($error eq 'incorrectCODE' 
                   6919: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6920: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6921: 	    if ($closest > 0) {
                   6922: 		foreach my $testcode (@{$closest}) {
                   6923: 		    my $checked='';
1.569     bisitz   6924: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6925: 		    $r->print("
                   6926:    <label>
1.569     bisitz   6927:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6928:        ".&mt("Use the similar CODE [_1] instead.",
                   6929: 	    "<b><tt>".$testcode."</tt></b>")."
                   6930:     </label>
                   6931:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6932: 		    $r->print("\n<br />");
                   6933: 		    $i++;
                   6934: 		}
1.194     albertel 6935: 	    }
                   6936: 	}
1.273     albertel 6937: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6938: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6939: 	    $r->print("
                   6940:     <label>
1.569     bisitz   6941:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6942:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6943: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6944:     </label>");
1.273     albertel 6945: 	    $r->print("\n<br />");
                   6946: 	}
1.194     albertel 6947: 
1.597     wenzelju 6948: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6949: function change_radio(field) {
1.190     albertel 6950:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6951:     var i;
                   6952:     for (i=0;i<slct.length;i++) {
                   6953:         if (slct[i].value==field) { slct[i].checked=true; }
                   6954:     }
                   6955: }
                   6956: ENDSCRIPT
1.187     albertel 6957: 	my $href="/adm/pickcode?".
1.359     www      6958: 	   "form=".&escape("scantronupload").
                   6959: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6960: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6961: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6962: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6963: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6964: 	    $r->print("
                   6965:     <label>
                   6966:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6967:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6968: 	     "<a target='_blank' href='$href'>","</a>")."
                   6969:     </label> 
1.558     bisitz   6970:     ".&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 6971: 	    $r->print("\n<br />");
                   6972: 	}
1.492     albertel 6973: 	$r->print("
                   6974:     <label>
                   6975:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6976:        ".&mt("Use [_1] as the CODE.",
                   6977: 	     "</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 6978: 	$r->print("\n<br /><br />");
1.157     albertel 6979:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6980: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6981: 
                   6982: 	# The form field scantron_questions is acutally a list of line numbers.
                   6983: 	# represented by this form so:
                   6984: 
                   6985: 	my $line_list = &questions_to_line_list($arg);
                   6986: 
1.157     albertel 6987: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6988: 		  $line_list.'" />');
1.242     albertel 6989: 	$r->print($message);
1.492     albertel 6990: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6991: 	foreach my $question (@{$arg}) {
1.503     raeburn  6992: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6993:                                                    $scan_record, $error);
1.524     raeburn  6994:             push(@lines_to_correct,@linenums);
1.157     albertel 6995: 	}
1.503     raeburn  6996:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6997:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6998: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6999: 	$r->print($message);
1.492     albertel 7000: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7001: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7002: 
1.503     raeburn  7003: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7004: 	# a list of question numbers. Therefore:
                   7005: 	#
                   7006: 	
                   7007: 	my $line_list = &questions_to_line_list($arg);
                   7008: 
1.157     albertel 7009: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7010: 		  $line_list.'" />');
1.157     albertel 7011: 	foreach my $question (@{$arg}) {
1.503     raeburn  7012: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7013:                                                    $scan_record, $error);
1.524     raeburn  7014:             push(@lines_to_correct,@linenums);
1.157     albertel 7015: 	}
1.503     raeburn  7016:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7017:     } else {
                   7018: 	$r->print("\n<ul>");
                   7019:     }
                   7020:     $r->print("\n</li></ul>");
1.497     foxr     7021: }
                   7022: 
1.503     raeburn  7023: sub verify_bubbles_checked {
                   7024:     my (@ansnums) = @_;
                   7025:     my $ansnumstr = join('","',@ansnums);
                   7026:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7027:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7028: function verify_bubble_radio(form) {
                   7029:     var ansnumArray = new Array ("$ansnumstr");
                   7030:     var need_bubble_count = 0;
                   7031:     for (var i=0; i<ansnumArray.length; i++) {
                   7032:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7033:             var bubble_picked = 0; 
                   7034:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7035:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7036:                     bubble_picked = 1;
                   7037:                 }
                   7038:             }
                   7039:             if (bubble_picked == 0) {
                   7040:                 need_bubble_count ++;
                   7041:             }
                   7042:         }
                   7043:     }
                   7044:     if (need_bubble_count) {
                   7045:         alert("$warning");
                   7046:         return;
                   7047:     }
                   7048:     form.submit(); 
                   7049: }
                   7050: ENDSCRIPT
                   7051:     return $output;
                   7052: }
                   7053: 
1.497     foxr     7054: =pod
                   7055: 
                   7056: =item  questions_to_line_list
1.157     albertel 7057: 
1.497     foxr     7058: Converts a list of questions into a string of comma separated
                   7059: line numbers in the answer sheet used by the questions.  This is
                   7060: used to fill in the scantron_questions form field.
                   7061: 
                   7062:   Arguments:
                   7063:      questions    - Reference to an array of questions.
                   7064: 
                   7065: =cut
                   7066: 
                   7067: 
                   7068: sub questions_to_line_list {
                   7069:     my ($questions) = @_;
                   7070:     my @lines;
                   7071: 
1.503     raeburn  7072:     foreach my $item (@{$questions}) {
                   7073:         my $question = $item;
                   7074:         my ($first,$count,$last);
                   7075:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7076:             $question = $1;
                   7077:             my $subquestion = $2;
                   7078:             $first = $first_bubble_line{$question-1} + 1;
                   7079:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7080:             my $subcount = 1;
                   7081:             while ($subcount<$subquestion) {
                   7082:                 $first += $subans[$subcount-1];
                   7083:                 $subcount ++;
                   7084:             }
                   7085:             $count = $subans[$subquestion-1];
                   7086:         } else {
                   7087: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7088: 	    $count   = $bubble_lines_per_response{$question-1};
                   7089:         }
1.506     raeburn  7090:         $last = $first+$count-1;
1.503     raeburn  7091:         push(@lines, ($first..$last));
1.497     foxr     7092:     }
                   7093:     return join(',', @lines);
                   7094: }
                   7095: 
                   7096: =pod 
                   7097: 
                   7098: =item prompt_for_corrections
                   7099: 
                   7100: Prompts for a potentially multiline correction to the
                   7101: user's bubbling (factors out common code from scantron_get_correction
                   7102: for multi and missing bubble cases).
                   7103: 
                   7104:  Arguments:
                   7105:    $r           - Apache request object.
                   7106:    $question    - The question number to prompt for.
                   7107:    $scan_config - The scantron file configuration hash.
                   7108:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7109:    $error       - Type of error
1.497     foxr     7110: 
                   7111:  Implicit inputs:
                   7112:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7113:                                   Numbered from 0 (but question numbers are from
                   7114:                                   1.
                   7115:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7116:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7117:                                   type problems render as separate sub-questions, 
1.503     raeburn  7118:                                   in exam mode. This hash contains a 
                   7119:                                   comma-separated list of the lines per 
                   7120:                                   sub-question.
1.510     raeburn  7121:    %responsetype_per_response   - essayresponse, formularesponse,
                   7122:                                   stringresponse, imageresponse, reactionresponse,
                   7123:                                   and organicresponse type problem parts can have
1.503     raeburn  7124:                                   multiple lines per response if the weight
                   7125:                                   assigned exceeds 10.  In this case, only
                   7126:                                   one bubble per line is permitted, but more 
                   7127:                                   than one line might contain bubbles, e.g.
                   7128:                                   bubbling of: line 1 - J, line 2 - J, 
                   7129:                                   line 3 - B would assign 22 points.  
1.497     foxr     7130: 
                   7131: =cut
                   7132: 
                   7133: sub prompt_for_corrections {
1.503     raeburn  7134:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7135:     my ($current_line,$lines);
                   7136:     my @linenums;
                   7137:     my $questionnum = $question;
                   7138:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7139:         $question = $1;
                   7140:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7141:         my $subquestion = $2;
                   7142:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7143:         my $subcount = 1;
                   7144:         while ($subcount<$subquestion) {
                   7145:             $current_line += $subans[$subcount-1];
                   7146:             $subcount ++;
                   7147:         }
                   7148:         $lines = $subans[$subquestion-1];
                   7149:     } else {
                   7150:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7151:         $lines        = $bubble_lines_per_response{$question-1};
                   7152:     }
1.497     foxr     7153:     if ($lines > 1) {
1.503     raeburn  7154:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7155:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7156:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7157:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7158:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7159:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7160:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7161:             $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  7162:         } else {
                   7163:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7164:         }
1.497     foxr     7165:     }
                   7166:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7167:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7168: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7169: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7170:         push(@linenums,$current_line);
1.497     foxr     7171: 	$current_line++;
                   7172:     }
                   7173:     if ($lines > 1) {
                   7174: 	$r->print("<hr /><br />");
                   7175:     }
1.503     raeburn  7176:     return @linenums;
1.157     albertel 7177: }
1.423     albertel 7178: 
                   7179: =pod
                   7180: 
                   7181: =item scantron_bubble_selector
                   7182:   
                   7183:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7184:    possibly showing the existing the selected bubbles if known
1.423     albertel 7185: 
                   7186:  Arguments:
                   7187:     $r           - Apache request object
                   7188:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7189:     $line        - Number of the line being displayed.
1.503     raeburn  7190:     $questionnum - Question number (may include subquestion)
                   7191:     $error       - Type of error.
1.497     foxr     7192:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7193: 
                   7194: =cut
                   7195: 
1.157     albertel 7196: sub scantron_bubble_selector {
1.503     raeburn  7197:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7198:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7199: 
                   7200:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7201:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7202:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7203:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7204:             $max=$$scan_config{'BubblesPerRow'};
                   7205:             if (($scmode eq 'number') && ($max > 10)) {
                   7206:                 $max = 10;
                   7207:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7208:                 $max = 26;
                   7209:             }
                   7210:         } else {
                   7211:             $max = 10;
                   7212:         }
                   7213:     }
1.274     albertel 7214: 
1.157     albertel 7215:     my @alphabet=('A'..'Z');
1.503     raeburn  7216:     $r->print(&Apache::loncommon::start_data_table().
                   7217:               &Apache::loncommon::start_data_table_row());
                   7218:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7219:     for (my $i=0;$i<$max+1;$i++) {
                   7220: 	$r->print("\n".'<td align="center">');
                   7221: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7222: 	else { $r->print('&nbsp;'); }
                   7223: 	$r->print('</td>');
                   7224:     }
1.503     raeburn  7225:     $r->print(&Apache::loncommon::end_data_table_row().
                   7226:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7227:     for (my $i=0;$i<$max;$i++) {
                   7228: 	$r->print("\n".
                   7229: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7230: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7231:     }
1.503     raeburn  7232:     my $nobub_checked = ' ';
                   7233:     if ($error eq 'missingbubble') {
                   7234:         $nobub_checked = ' checked = "checked" ';
                   7235:     }
                   7236:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7237: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7238:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7239:               $line.'" value="'.$questionnum.'" /></td>');
                   7240:     $r->print(&Apache::loncommon::end_data_table_row().
                   7241:               &Apache::loncommon::end_data_table());
1.157     albertel 7242: }
                   7243: 
1.423     albertel 7244: =pod
                   7245: 
                   7246: =item num_matches
                   7247: 
1.424     albertel 7248:    Counts the number of characters that are the same between the two arguments.
                   7249: 
                   7250:  Arguments:
                   7251:    $orig - CODE from the scanline
                   7252:    $code - CODE to match against
                   7253: 
                   7254:  Returns:
                   7255:    $count - integer count of the number of same characters between the
                   7256:             two arguments
                   7257: 
1.423     albertel 7258: =cut
                   7259: 
1.194     albertel 7260: sub num_matches {
                   7261:     my ($orig,$code) = @_;
                   7262:     my @code=split(//,$code);
                   7263:     my @orig=split(//,$orig);
                   7264:     my $same=0;
                   7265:     for (my $i=0;$i<scalar(@code);$i++) {
                   7266: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7267:     }
                   7268:     return $same;
                   7269: }
                   7270: 
1.423     albertel 7271: =pod
                   7272: 
                   7273: =item scantron_get_closely_matching_CODEs
                   7274: 
1.424     albertel 7275:    Cycles through all CODEs and finds the set that has the greatest
                   7276:    number of same characters as the provided CODE
                   7277: 
                   7278:  Arguments:
                   7279:    $allcodes - hash ref returned by &get_codes()
                   7280:    $CODE     - CODE from the current scanline
                   7281: 
                   7282:  Returns:
                   7283:    2 element list
                   7284:     - first elements is number of how closely matching the best fit is 
                   7285:       (5 means best set has 5 matching characters)
                   7286:     - second element is an arrary ref containing the set of valid CODEs
                   7287:       that best fit the passed in CODE
                   7288: 
1.423     albertel 7289: =cut
                   7290: 
1.194     albertel 7291: sub scantron_get_closely_matching_CODEs {
                   7292:     my ($allcodes,$CODE)=@_;
                   7293:     my @CODEs;
                   7294:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7295: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7296:     }
                   7297: 
                   7298:     return ($#CODEs,$CODEs[-1]);
                   7299: }
                   7300: 
1.423     albertel 7301: =pod
                   7302: 
                   7303: =item get_codes
                   7304: 
1.424     albertel 7305:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7306:    set of remembered CODEs.
                   7307: 
                   7308:  Arguments:
                   7309:   $old_name - name of the set of remembered CODEs
                   7310:   $cdom     - domain of the course
                   7311:   $cnum     - internal course name
                   7312: 
                   7313:  Returns:
                   7314:   %allcodes - keys are the valid CODEs, values are all 1
                   7315: 
1.423     albertel 7316: =cut
                   7317: 
1.194     albertel 7318: sub get_codes {
1.280     foxr     7319:     my ($old_name, $cdom, $cnum) = @_;
                   7320:     if (!$old_name) {
                   7321: 	$old_name=$env{'form.scantron_CODElist'};
                   7322:     }
                   7323:     if (!$cdom) {
                   7324: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7325:     }
                   7326:     if (!$cnum) {
                   7327: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7328:     }
1.278     albertel 7329:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7330: 				    $cdom,$cnum);
                   7331:     my %allcodes;
                   7332:     if ($result{"type\0$old_name"} eq 'number') {
                   7333: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7334:     } else {
                   7335: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7336:     }
1.194     albertel 7337:     return %allcodes;
                   7338: }
                   7339: 
1.423     albertel 7340: =pod
                   7341: 
                   7342: =item scantron_validate_CODE
                   7343: 
1.424     albertel 7344:    Validates all scanlines in the selected file to not have any
                   7345:    invalid or underspecified CODEs and that none of the codes are
                   7346:    duplicated if this was requested.
                   7347: 
1.423     albertel 7348: =cut
                   7349: 
1.157     albertel 7350: sub scantron_validate_CODE {
                   7351:     my ($r,$currentphase) = @_;
1.257     albertel 7352:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7353:     if ($scantron_config{'CODElocation'} &&
                   7354: 	$scantron_config{'CODEstart'} &&
                   7355: 	$scantron_config{'CODElength'}) {
1.257     albertel 7356: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7357: 	    &FIXME_blow_up()
                   7358: 	}
                   7359:     } else {
                   7360: 	return (0,$currentphase+1);
                   7361:     }
                   7362:     
                   7363:     my %usedCODEs;
                   7364: 
1.194     albertel 7365:     my %allcodes=&get_codes();
1.186     albertel 7366: 
1.582     raeburn  7367:     my $nav_error;
1.649     raeburn  7368:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7369:     if ($nav_error) {
                   7370:         $r->print(&navmap_errormsg());
                   7371:         return(1,$currentphase);
                   7372:     }
1.447     foxr     7373: 
1.186     albertel 7374:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7375:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7376: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7377: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7378: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7379: 						 $scan_data);
                   7380: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7381: 	my $error=0;
1.224     albertel 7382: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7383: 	    &scantron_get_correction($r,$i,$scan_record,
                   7384: 				     \%scantron_config,
                   7385: 				     $line,'incorrectCODE',\%allcodes);
                   7386: 	    return(1,$currentphase);
                   7387: 	}
1.221     albertel 7388: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7389: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7390: 	    &scantron_get_correction($r,$i,$scan_record,
                   7391: 				     \%scantron_config,
1.194     albertel 7392: 				     $line,'incorrectCODE',\%allcodes);
                   7393: 	    return(1,$currentphase);
1.186     albertel 7394: 	}
1.214     albertel 7395: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7396: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7397: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7398: 	    &scantron_get_correction($r,$i,$scan_record,
                   7399: 				     \%scantron_config,
1.194     albertel 7400: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7401: 	    return(1,$currentphase);
1.186     albertel 7402: 	}
1.524     raeburn  7403: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7404:     }
1.157     albertel 7405:     return (0,$currentphase+1);
                   7406: }
                   7407: 
1.423     albertel 7408: =pod
                   7409: 
                   7410: =item scantron_validate_doublebubble
                   7411: 
1.424     albertel 7412:    Validates all scanlines in the selected file to not have any
                   7413:    bubble lines with multiple bubbles marked.
                   7414: 
1.423     albertel 7415: =cut
                   7416: 
1.157     albertel 7417: sub scantron_validate_doublebubble {
                   7418:     my ($r,$currentphase) = @_;
                   7419:     #get student info
                   7420:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7421:     my %idmap=&username_to_idmap($classlist);
                   7422: 
                   7423:     #get scantron line setup
1.257     albertel 7424:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7425:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7426:     my $nav_error;
1.649     raeburn  7427:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7428:     if ($nav_error) {
                   7429:         $r->print(&navmap_errormsg());
                   7430:         return(1,$currentphase);
                   7431:     }
1.447     foxr     7432: 
1.157     albertel 7433:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7434: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7435: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7436: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7437: 						 $scan_data);
                   7438: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7439: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7440: 				 'doublebubble',
                   7441: 				 $$scan_record{'scantron.doubleerror'});
                   7442:     	return (1,$currentphase);
                   7443:     }
                   7444:     return (0,$currentphase+1);
                   7445: }
                   7446: 
1.423     albertel 7447: 
1.503     raeburn  7448: sub scantron_get_maxbubble {
1.649     raeburn  7449:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7450:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7451: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7452: 	&restore_bubble_lines();
1.257     albertel 7453: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7454:     }
1.330     albertel 7455: 
1.447     foxr     7456:     my (undef, undef, $sequence) =
1.257     albertel 7457: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7458: 
1.447     foxr     7459:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7460:     unless (ref($navmap)) {
                   7461:         if (ref($nav_error)) {
                   7462:             $$nav_error = 1;
                   7463:         }
1.591     raeburn  7464:         return;
1.582     raeburn  7465:     }
1.191     albertel 7466:     my $map=$navmap->getResourceByUrl($sequence);
                   7467:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7468:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7469: 
                   7470:     &Apache::lonxml::clear_problem_counter();
                   7471: 
1.557     raeburn  7472:     my $uname       = $env{'user.name'};
                   7473:     my $udom        = $env{'user.domain'};
1.435     foxr     7474:     my $cid         = $env{'request.course.id'};
                   7475:     my $total_lines = 0;
                   7476:     %bubble_lines_per_response = ();
1.447     foxr     7477:     %first_bubble_line         = ();
1.503     raeburn  7478:     %subdivided_bubble_lines   = ();
                   7479:     %responsetype_per_response = ();
1.554     raeburn  7480: 
1.447     foxr     7481:     my $response_number = 0;
                   7482:     my $bubble_line     = 0;
1.191     albertel 7483:     foreach my $resource (@resources) {
1.649     raeburn  7484:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
1.542     raeburn  7485:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7486: 	    foreach my $part_id (@{$parts}) {
                   7487:                 my $lines;
                   7488: 
                   7489: 	        # TODO - make this a persistent hash not an array.
                   7490: 
                   7491:                 # optionresponse, matchresponse and rankresponse type items 
                   7492:                 # render as separate sub-questions in exam mode.
                   7493:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7494:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7495:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7496:                     my ($numbub,$numshown);
                   7497:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7498:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7499:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7500:                         }
                   7501:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7502:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7503:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7504:                         }
                   7505:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7506:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7507:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7508:                         }
                   7509:                     }
                   7510:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7511:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7512:                     }
1.649     raeburn  7513:                     my $bubbles_per_row =
                   7514:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7515:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7516:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7517:                         $inner_bubble_lines++;
                   7518:                     }
                   7519:                     for (my $i=0; $i<$numshown; $i++) {
                   7520:                         $subdivided_bubble_lines{$response_number} .= 
                   7521:                             $inner_bubble_lines.',';
                   7522:                     }
                   7523:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7524:                     $lines = $numshown * $inner_bubble_lines;
                   7525:                 } else {
                   7526:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7527:                 }
1.542     raeburn  7528: 
                   7529:                 $first_bubble_line{$response_number} = $bubble_line;
                   7530: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7531:                 $responsetype_per_response{$response_number} = 
                   7532:                     $analysis->{$part_id.'.type'};
                   7533: 	        $response_number++;
                   7534: 
                   7535: 	        $bubble_line +=  $lines;
                   7536: 	        $total_lines +=  $lines;
                   7537: 	    }
                   7538:         }
                   7539:     }
1.552     raeburn  7540:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7541: 
                   7542:     &save_bubble_lines();
                   7543:     $env{'form.scantron_maxbubble'} =
                   7544: 	$total_lines;
                   7545:     return $env{'form.scantron_maxbubble'};
                   7546: }
1.523     raeburn  7547: 
1.649     raeburn  7548: sub bubblesheet_bubbles_per_row {
                   7549:     my ($scantron_config) = @_;
                   7550:     my $bubbles_per_row;
                   7551:     if (ref($scantron_config) eq 'HASH') {
                   7552:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7553:     }
                   7554:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7555:         $bubbles_per_row = 10;
                   7556:     }
                   7557:     return $bubbles_per_row;
                   7558: }
                   7559: 
1.157     albertel 7560: sub scantron_validate_missingbubbles {
                   7561:     my ($r,$currentphase) = @_;
                   7562:     #get student info
                   7563:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7564:     my %idmap=&username_to_idmap($classlist);
                   7565: 
                   7566:     #get scantron line setup
1.257     albertel 7567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7568:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7569:     my $nav_error;
1.649     raeburn  7570:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7571:     if ($nav_error) {
                   7572:         return(1,$currentphase);
                   7573:     }
1.157     albertel 7574:     if (!$max_bubble) { $max_bubble=2**31; }
                   7575:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7576: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7577: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7578: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7579: 						 $scan_data);
                   7580: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7581: 	my @to_correct;
1.470     foxr     7582: 	
                   7583: 	# Probably here's where the error is...
                   7584: 
1.157     albertel 7585: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7586:             my $lastbubble;
                   7587:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7588:                my $question = $1;
                   7589:                my $subquestion = $2;
                   7590:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7591:                my $first = $first_bubble_line{$question-1};
                   7592:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7593:                my $subcount = 1;
                   7594:                while ($subcount<$subquestion) {
                   7595:                    $first += $subans[$subcount-1];
                   7596:                    $subcount ++;
                   7597:                }
                   7598:                my $count = $subans[$subquestion-1];
                   7599:                $lastbubble = $first + $count;
                   7600:             } else {
                   7601:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7602:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7603:             }
                   7604:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7605: 	    push(@to_correct,$missing);
                   7606: 	}
                   7607: 	if (@to_correct) {
                   7608: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7609: 				     $line,'missingbubble',\@to_correct);
                   7610: 	    return (1,$currentphase);
                   7611: 	}
                   7612: 
                   7613:     }
                   7614:     return (0,$currentphase+1);
                   7615: }
                   7616: 
1.423     albertel 7617: 
1.82      albertel 7618: sub scantron_process_students {
1.608     www      7619:     my ($r,$symb) = @_;
1.513     foxr     7620: 
1.257     albertel 7621:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7622:     if (!$symb) {
                   7623: 	return '';
                   7624:     }
1.324     albertel 7625:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7626: 
1.257     albertel 7627:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7628:     my $bubbles_per_row =
                   7629:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7630:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7631:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7632:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7633:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7634:     unless (ref($navmap)) {
                   7635:         $r->print(&navmap_errormsg());
                   7636:         return '';
                   7637:     }  
1.83      albertel 7638:     my $map=$navmap->getResourceByUrl($sequence);
                   7639:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7640:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7641:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7642:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7643:     my $resource_error;
1.557     raeburn  7644:     foreach my $resource (@resources) {
1.586     raeburn  7645:         my $ressymb;
                   7646:         if (ref($resource)) {
                   7647:             $ressymb = $resource->symb();
                   7648:         } else {
                   7649:             $resource_error = 1;
                   7650:             last;
                   7651:         }
1.557     raeburn  7652:         my ($analysis,$parts) =
                   7653:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7654:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7655:         $grader_partids_by_symb{$ressymb} = $parts;
                   7656:         if (ref($analysis) eq 'HASH') {
                   7657:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7658:                 $grader_randomlists_by_symb{$ressymb} = 
                   7659:                     $analysis->{'parts_withrandomlist'};
                   7660:             }
                   7661:         }
                   7662:     }
1.586     raeburn  7663:     if ($resource_error) {
                   7664:         $r->print(&navmap_errormsg());
                   7665:         return '';
                   7666:     }
1.557     raeburn  7667: 
1.554     raeburn  7668:     my ($uname,$udom);
1.82      albertel 7669:     my $result= <<SCANTRONFORM;
1.81      albertel 7670: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7671:   <input type="hidden" name="command" value="scantron_configphase" />
                   7672:   $default_form_data
                   7673: SCANTRONFORM
1.82      albertel 7674:     $r->print($result);
                   7675: 
                   7676:     my @delayqueue;
1.542     raeburn  7677:     my (%completedstudents,%scandata);
1.140     albertel 7678:     
1.520     www      7679:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7680:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7681:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7682:  				    'Bubblesheet Progress',$count,
1.195     albertel 7683: 				    'inline',undef,'scantronupload');
1.140     albertel 7684:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7685: 					  'Processing first student');
1.542     raeburn  7686:     $r->print('<br />');
1.140     albertel 7687:     my $start=&Time::HiRes::time();
1.158     albertel 7688:     my $i=-1;
1.542     raeburn  7689:     my $started;
1.447     foxr     7690: 
1.582     raeburn  7691:     my $nav_error;
1.649     raeburn  7692:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7693:     if ($nav_error) {
                   7694:         $r->print(&navmap_errormsg());
                   7695:         return '';
                   7696:     }
                   7697: 
1.513     foxr     7698:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7699:     # the user and return.
                   7700: 
                   7701:     if ($ssi_error) {
                   7702: 	$r->print("</form>");
                   7703: 	&ssi_print_error($r);
1.520     www      7704:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7705: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7706:     }
1.447     foxr     7707: 
1.542     raeburn  7708:     my %lettdig = &letter_to_digits();
                   7709:     my $numletts = scalar(keys(%lettdig));
                   7710: 
1.157     albertel 7711:     while ($i<$scanlines->{'count'}) {
                   7712:  	($uname,$udom)=('','');
                   7713:  	$i++;
1.200     albertel 7714:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7715:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7716: 	if ($started) {
                   7717: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7718: 						     'last student');
                   7719: 	}
                   7720: 	$started=1;
1.157     albertel 7721:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7722:  						 $scan_data);
                   7723:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7724:  					      \%idmap,$i)) {
                   7725:   	    &scantron_add_delay(\@delayqueue,$line,
                   7726:  				'Unable to find a student that matches',1);
                   7727:  	    next;
                   7728:   	}
                   7729:  	if (exists $completedstudents{$uname}) {
                   7730:  	    &scantron_add_delay(\@delayqueue,$line,
                   7731:  				'Student '.$uname.' has multiple sheets',2);
                   7732:  	    next;
                   7733:  	}
                   7734:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7735: 
1.586     raeburn  7736:         my (%partids_by_symb,$res_error);
1.554     raeburn  7737:         foreach my $resource (@resources) {
1.586     raeburn  7738:             my $ressymb;
                   7739:             if (ref($resource)) {
                   7740:                 $ressymb = $resource->symb();
                   7741:             } else {
                   7742:                 $res_error = 1;
                   7743:                 last;
                   7744:             }
1.557     raeburn  7745:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7746:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7747:                 my ($analysis,$parts) =
1.649     raeburn  7748:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7749:                 $partids_by_symb{$ressymb} = $parts;
                   7750:             } else {
                   7751:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7752:             }
1.554     raeburn  7753:         }
                   7754: 
1.586     raeburn  7755:         if ($res_error) {
                   7756:             &scantron_add_delay(\@delayqueue,$line,
                   7757:                                 'An error occurred while grading student '.$uname,2);
                   7758:             next;
                   7759:         }
                   7760: 
1.330     albertel 7761: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7762:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7763: 
                   7764: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7765: 	    &scantron_putfile($scanlines,$scan_data);
                   7766: 	}
1.161     albertel 7767: 	
1.542     raeburn  7768:         my $scancode;
                   7769:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7770:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7771:             $scancode = $scan_record->{'scantron.CODE'};
                   7772:         } else {
                   7773:             $scancode = '';
                   7774:         }
                   7775: 
                   7776:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7777:                                    \@resources,\%partids_by_symb,
                   7778:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  7779:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7780:             $r->print("</form>");
                   7781:             &ssi_print_error($r);
                   7782:             &Apache::lonnet::remove_lock($lock);
                   7783:             return '';      # Why return ''?  Beats me.
                   7784:         }
1.513     foxr     7785: 
1.140     albertel 7786: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7787:         if ($env{'form.verifyrecord'}) {
                   7788:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7789:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7790:             chomp($studentdata);
                   7791:             $studentdata =~ s/\r$//;
                   7792:             my $studentrecord = '';
                   7793:             my $counter = -1;
                   7794:             foreach my $resource (@resources) {
1.554     raeburn  7795:                 my $ressymb = $resource->symb();
1.542     raeburn  7796:                 ($counter,my $recording) =
                   7797:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7798:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7799:                                              \%scantron_config,\%lettdig,$numletts);
                   7800:                 $studentrecord .= $recording;
                   7801:             }
                   7802:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7803:                 &Apache::lonxml::clear_problem_counter();
                   7804:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7805:                                            \@resources,\%partids_by_symb,
                   7806:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  7807:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7808:                     $r->print("</form>");
                   7809:                     &ssi_print_error($r);
                   7810:                     &Apache::lonnet::remove_lock($lock);
                   7811:                     delete($completedstudents{$uname});
                   7812:                     return '';
                   7813:                 }
1.542     raeburn  7814:                 $counter = -1;
                   7815:                 $studentrecord = '';
                   7816:                 foreach my $resource (@resources) {
1.554     raeburn  7817:                     my $ressymb = $resource->symb();
1.542     raeburn  7818:                     ($counter,my $recording) =
                   7819:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7820:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7821:                                                  \%scantron_config,\%lettdig,$numletts);
                   7822:                     $studentrecord .= $recording;
                   7823:                 }
                   7824:                 if ($studentrecord ne $studentdata) {
                   7825:                     $r->print('<p><span class="LC_error">');
                   7826:                     if ($scancode eq '') {
                   7827:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7828:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7829:                     } else {
                   7830:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7831:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7832:                     }
                   7833:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7834:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7835:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7836:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7837:                               &Apache::loncommon::start_data_table_row().
                   7838:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7839:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7840:                               &Apache::loncommon::end_data_table_row().
                   7841:                               &Apache::loncommon::start_data_table_row().
                   7842:                               '<td>Stored submissions</td>'.
                   7843:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7844:                               &Apache::loncommon::end_data_table_row().
                   7845:                               &Apache::loncommon::end_data_table().'</p>');
                   7846:                 } else {
                   7847:                     $r->print('<br /><span class="LC_warning">'.
                   7848:                              &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 />'.
                   7849:                              &mt("As a consequence, this user's submission history records two tries.").
                   7850:                                  '</span><br />');
                   7851:                 }
                   7852:             }
                   7853:         }
1.543     raeburn  7854:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7855:     } continue {
1.330     albertel 7856: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7857: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7858:     }
1.140     albertel 7859:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7860:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7861: #    my $lasttime = &Time::HiRes::time()-$start;
                   7862: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7863: 
1.200     albertel 7864:     $r->print("</form>");
1.157     albertel 7865:     return '';
1.75      albertel 7866: }
1.157     albertel 7867: 
1.557     raeburn  7868: sub graders_resources_pass {
1.649     raeburn  7869:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   7870:         $bubbles_per_row) = @_;
1.557     raeburn  7871:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7872:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7873:         foreach my $resource (@{$resources}) {
                   7874:             my $ressymb = $resource->symb();
                   7875:             my ($analysis,$parts) =
                   7876:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7877:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7878:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7879:             if (ref($analysis) eq 'HASH') {
                   7880:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7881:                     $grader_randomlists_by_symb->{$ressymb} =
                   7882:                         $analysis->{'parts_withrandomlist'};
                   7883:                 }
                   7884:             }
                   7885:         }
                   7886:     }
                   7887:     return;
                   7888: }
                   7889: 
1.542     raeburn  7890: sub grade_student_bubbles {
1.649     raeburn  7891:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   7892: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  7893:     if (ref($resources) eq 'ARRAY') {
                   7894:         my $count = 0;
                   7895:         foreach my $resource (@{$resources}) {
                   7896:             my $ressymb = $resource->symb();
                   7897:             my %form = ('submitted'      => 'scantron',
                   7898:                         'grade_target'   => 'grade',
                   7899:                         'grade_username' => $uname,
                   7900:                         'grade_domain'   => $udom,
                   7901:                         'grade_courseid' => $env{'request.course.id'},
                   7902:                         'grade_symb'     => $ressymb,
                   7903:                         'CODE'           => $scancode
                   7904:                        );
1.649     raeburn  7905:             if ($bubbles_per_row ne '') {
                   7906:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   7907:             }
1.554     raeburn  7908:             if (ref($parts) eq 'HASH') {
                   7909:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7910:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7911:                         $form{'scantron_questnum_start.'.$part} =
                   7912:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7913:                         $count++;
                   7914:                     }
                   7915:                 }
                   7916:             }
                   7917:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7918:             return 'ssi_error' if ($ssi_error);
                   7919:             last if (&Apache::loncommon::connection_aborted($r));
                   7920:         }
1.542     raeburn  7921:     }
                   7922:     return;
                   7923: }
                   7924: 
1.157     albertel 7925: sub scantron_upload_scantron_data {
1.608     www      7926:     my ($r,$symb)=@_;
1.565     raeburn  7927:     my $dom = $env{'request.role.domain'};
                   7928:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7929:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7930:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7931: 							  'domainid',
1.565     raeburn  7932: 							  'coursename',$dom);
                   7933:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7934:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7935:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7936:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7937:     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 7938:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7939:     function checkUpload(formname) {
                   7940: 	if (formname.upfile.value == "") {
1.579     raeburn  7941: 	    alert("'.$nofile_alert.'");
1.157     albertel 7942: 	    return false;
                   7943: 	}
1.565     raeburn  7944:         if (formname.courseid.value == "") {
1.579     raeburn  7945:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7946:             return false;
                   7947:         }
1.157     albertel 7948: 	formname.submit();
                   7949:     }
1.565     raeburn  7950: 
                   7951:     function ToSyllabus() {
                   7952:         var cdom = '."'$dom'".';
                   7953:         var cnum = document.rules.courseid.value;
                   7954:         if (cdom == "" || cdom == null) {
                   7955:             return;
                   7956:         }
                   7957:         if (cnum == "" || cnum == null) {
                   7958:            return;
                   7959:         }
                   7960:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7961:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7962:         return;
                   7963:     }
                   7964: 
1.597     wenzelju 7965: '));
                   7966:     $r->print('
1.648     bisitz   7967: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  7968: 
1.492     albertel 7969: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7970: '.$default_form_data.
                   7971:   &Apache::lonhtmlcommon::start_pick_box().
                   7972:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7973:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7974:   &Apache::lonhtmlcommon::row_closure().
                   7975:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7976:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7977:   &Apache::lonhtmlcommon::row_closure().
                   7978:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7979:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7980:   &Apache::lonhtmlcommon::row_closure().
                   7981:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7982:   '<input type="file" name="upfile" size="50" />'.
                   7983:   &Apache::lonhtmlcommon::row_closure(1).
                   7984:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7985: 
1.492     albertel 7986: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7987: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7988: </form>
1.492     albertel 7989: ');
1.157     albertel 7990:     return '';
                   7991: }
                   7992: 
1.423     albertel 7993: 
1.157     albertel 7994: sub scantron_upload_scantron_data_save {
1.608     www      7995:     my($r,$symb)=@_;
1.182     albertel 7996:     my $doanotherupload=
                   7997: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7998: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7999: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8000: 	'</form>'."\n";
1.257     albertel 8001:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8002: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8003: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8004: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8005: 	unless ($symb) {
1.182     albertel 8006: 	    $r->print($doanotherupload);
                   8007: 	}
1.162     albertel 8008: 	return '';
                   8009:     }
1.257     albertel 8010:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8011:     my $uploadedfile;
1.567     raeburn  8012:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8013:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8014:         $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 8015:     } else {
1.568     raeburn  8016:         my $result = 
                   8017:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8018:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8019: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8020: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8021:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8022: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8023:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8024:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8025:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8026: 	} else {
1.567     raeburn  8027: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8028:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8029: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8030: 	}
                   8031:     }
1.174     albertel 8032:     if ($symb) {
1.612     www      8033: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8034:     } else {
1.182     albertel 8035: 	$r->print($doanotherupload);
1.174     albertel 8036:     }
1.157     albertel 8037:     return '';
                   8038: }
                   8039: 
1.567     raeburn  8040: sub validate_uploaded_scantron_file {
                   8041:     my ($cdom,$cname,$fname) = @_;
                   8042:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8043:     my @lines;
                   8044:     if ($scanlines ne '-1') {
                   8045:         @lines=split("\n",$scanlines,-1);
                   8046:     }
                   8047:     my $output;
                   8048:     if (@lines) {
                   8049:         my (%counts,$max_match_format);
                   8050:         my ($max_match_count,$max_match_pct) = (0,0);
                   8051:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8052:         my %idmap = &username_to_idmap($classlist);
                   8053:         foreach my $key (keys(%idmap)) {
                   8054:             my $lckey = lc($key);
                   8055:             $idmap{$lckey} = $idmap{$key};
                   8056:         }
                   8057:         my %unique_formats;
                   8058:         my @formatlines = &get_scantronformat_file();
                   8059:         foreach my $line (@formatlines) {
                   8060:             chomp($line);
                   8061:             my @config = split(/:/,$line);
                   8062:             my $idstart = $config[5];
                   8063:             my $idlength = $config[6];
                   8064:             if (($idstart ne '') && ($idlength > 0)) {
                   8065:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8066:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8067:                 } else {
                   8068:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8069:                 }
                   8070:             }
                   8071:         }
                   8072:         foreach my $key (keys(%unique_formats)) {
                   8073:             my ($idstart,$idlength) = split(':',$key);
                   8074:             %{$counts{$key}} = (
                   8075:                                'found'   => 0,
                   8076:                                'total'   => 0,
                   8077:                               );
                   8078:             foreach my $line (@lines) {
                   8079:                 next if ($line =~ /^#/);
                   8080:                 next if ($line =~ /^[\s\cz]*$/);
                   8081:                 my $id = substr($line,$idstart-1,$idlength);
                   8082:                 $id = lc($id);
                   8083:                 if (exists($idmap{$id})) {
                   8084:                     $counts{$key}{'found'} ++;
                   8085:                 }
                   8086:                 $counts{$key}{'total'} ++;
                   8087:             }
                   8088:             if ($counts{$key}{'total'}) {
                   8089:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8090:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8091:                     $max_match_pct = $percent_match;
                   8092:                     $max_match_format = $key;
                   8093:                     $max_match_count = $counts{$key}{'total'};
                   8094:                 }
                   8095:             }
                   8096:         }
                   8097:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8098:             my $format_descs;
                   8099:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8100:             for (my $i=0; $i<$numwithformat; $i++) {
                   8101:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8102:                 if ($i<$numwithformat-2) {
                   8103:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8104:                 } elsif ($i==$numwithformat-2) {
                   8105:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8106:                 } elsif ($i==$numwithformat-1) {
                   8107:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8108:                 }
                   8109:             }
                   8110:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8111:             $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).
                   8112:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8113:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8114:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8115:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8116:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8117:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8118:                        '</ul>';
                   8119:         }
                   8120:     } else {
                   8121:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8122:     }
                   8123:     return $output;
                   8124: }
                   8125: 
1.202     albertel 8126: sub valid_file {
                   8127:     my ($requested_file)=@_;
                   8128:     foreach my $filename (sort(&scantron_filenames())) {
                   8129: 	if ($requested_file eq $filename) { return 1; }
                   8130:     }
                   8131:     return 0;
                   8132: }
                   8133: 
                   8134: sub scantron_download_scantron_data {
1.608     www      8135:     my ($r,$symb)=@_;
                   8136:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8137:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8138:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8139:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8140:     if (! &valid_file($file)) {
1.492     albertel 8141: 	$r->print('
1.202     albertel 8142: 	<p>
1.492     albertel 8143: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8144:         </p>
1.492     albertel 8145: ');
1.202     albertel 8146: 	return;
                   8147:     }
                   8148:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8149:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8150:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8151:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8152:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8153:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8154:     $r->print('
1.202     albertel 8155:     <p>
1.492     albertel 8156: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8157: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8158:     </p>
                   8159:     <p>
1.492     albertel 8160: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8161: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8162:     </p>
                   8163:     <p>
1.492     albertel 8164: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8165: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8166:     </p>
1.492     albertel 8167: ');
1.202     albertel 8168:     return '';
                   8169: }
1.157     albertel 8170: 
1.523     raeburn  8171: sub checkscantron_results {
1.608     www      8172:     my ($r,$symb) = @_;
1.523     raeburn  8173:     if (!$symb) {return '';}
                   8174:     my $cid = $env{'request.course.id'};
1.542     raeburn  8175:     my %lettdig = &letter_to_digits();
1.523     raeburn  8176:     my $numletts = scalar(keys(%lettdig));
                   8177:     my $cnum = $env{'course.'.$cid.'.num'};
                   8178:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8179:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8180:     my %record;
                   8181:     my %scantron_config =
                   8182:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8183:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8184:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8185:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8186:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8187:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8188:     unless (ref($navmap)) {
                   8189:         $r->print(&navmap_errormsg());
                   8190:         return '';
                   8191:     }
1.523     raeburn  8192:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8193:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8194:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8195:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8196: 
1.554     raeburn  8197:     my ($uname,$udom);
1.523     raeburn  8198:     my (%scandata,%lastname,%bylast);
                   8199:     $r->print('
                   8200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8201: 
                   8202:     my @delayqueue;
                   8203:     my %completedstudents;
                   8204: 
                   8205:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8206:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8207:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8208:                                     'inline',undef,'checkscantron');
1.546     raeburn  8209:     my ($username,$domain,$started);
1.582     raeburn  8210:     my $nav_error;
1.649     raeburn  8211:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8212:     if ($nav_error) {
                   8213:         $r->print(&navmap_errormsg());
                   8214:         return '';
                   8215:     }
1.523     raeburn  8216: 
                   8217:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8218:                                           'Processing first student');
                   8219:     my $start=&Time::HiRes::time();
                   8220:     my $i=-1;
                   8221: 
                   8222:     while ($i<$scanlines->{'count'}) {
                   8223:         ($username,$domain,$uname)=('','','');
                   8224:         $i++;
                   8225:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8226:         if ($line=~/^[\s\cz]*$/) { next; }
                   8227:         if ($started) {
                   8228:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8229:                                                      'last student');
                   8230:         }
                   8231:         $started=1;
                   8232:         my $scan_record=
                   8233:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8234:                                                      $scan_data);
                   8235:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8236:                                                               \%idmap,$i)) {
                   8237:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8238:                                 'Unable to find a student that matches',1);
                   8239:             next;
                   8240:         }
                   8241:         if (exists $completedstudents{$uname}) {
                   8242:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8243:                                 'Student '.$uname.' has multiple sheets',2);
                   8244:             next;
                   8245:         }
                   8246:         my $pid = $scan_record->{'scantron.ID'};
                   8247:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8248:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8249:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8250:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8251:         chomp($scandata{$pid});
                   8252:         $scandata{$pid} =~ s/\r$//;
                   8253:         ($username,$domain)=split(/:/,$uname);
                   8254:         my $counter = -1;
                   8255:         foreach my $resource (@resources) {
1.557     raeburn  8256:             my $parts;
1.554     raeburn  8257:             my $ressymb = $resource->symb();
1.557     raeburn  8258:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8259:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8260:                 (my $analysis,$parts) =
1.649     raeburn  8261:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
1.557     raeburn  8262:             } else {
                   8263:                 $parts = $grader_partids_by_symb{$ressymb};
                   8264:             }
1.542     raeburn  8265:             ($counter,my $recording) =
                   8266:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8267:                                          $scandata{$pid},$parts,
1.542     raeburn  8268:                                          \%scantron_config,\%lettdig,$numletts);
                   8269:             $record{$pid} .= $recording;
1.523     raeburn  8270:         }
                   8271:     }
                   8272:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8273:     $r->print('<br />');
                   8274:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8275:     $passed = 0;
                   8276:     $failed = 0;
                   8277:     $numstudents = 0;
                   8278:     foreach my $last (sort(keys(%bylast))) {
                   8279:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8280:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8281:                 my $showscandata = $scandata{$pid};
                   8282:                 my $showrecord = $record{$pid};
                   8283:                 $showscandata =~ s/\s/&nbsp;/g;
                   8284:                 $showrecord =~ s/\s/&nbsp;/g;
                   8285:                 if ($scandata{$pid} eq $record{$pid}) {
                   8286:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8287:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8288: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8289: '</tr>'."\n".
                   8290: '<tr class="'.$css_class.'">'."\n".
                   8291: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8292:                     $passed ++;
                   8293:                 } else {
                   8294:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8295:                     $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  8296: '</tr>'."\n".
                   8297: '<tr class="'.$css_class.'">'."\n".
                   8298: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8299: '</tr>'."\n";
                   8300:                     $failed ++;
                   8301:                 }
                   8302:                 $numstudents ++;
                   8303:             }
                   8304:         }
                   8305:     }
1.648     bisitz   8306:     $r->print(
                   8307:         '<p>'
                   8308:        .&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).',
                   8309:             '<b>',
                   8310:             $numstudents,
                   8311:             '</b>',
                   8312:             $env{'form.scantron_maxbubble'})
                   8313:        .'</p>'
                   8314:     );
1.523     raeburn  8315:     $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>');
                   8316:     if ($passed) {
1.572     www      8317:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8318:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8319:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8320:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8321:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8322:                  $okstudents."\n".
                   8323:                  &Apache::loncommon::end_data_table().'<br />');
                   8324:     }
                   8325:     if ($failed) {
1.572     www      8326:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8327:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8328:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8329:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8330:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8331:                  $badstudents."\n".
                   8332:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8333:                  &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  8334:     }
1.614     www      8335:     $r->print('</form><br />');
1.523     raeburn  8336:     return;
                   8337: }
                   8338: 
1.542     raeburn  8339: sub verify_scantron_grading {
1.554     raeburn  8340:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8341:         $scantron_config,$lettdig,$numletts) = @_;
                   8342:     my ($record,%expected,%startpos);
                   8343:     return ($counter,$record) if (!ref($resource));
                   8344:     return ($counter,$record) if (!$resource->is_problem());
                   8345:     my $symb = $resource->symb();
1.554     raeburn  8346:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8347:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8348:         $counter ++;
                   8349:         $expected{$part_id} = 0;
                   8350:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8351:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8352:             foreach my $item (@sub_lines) {
                   8353:                 $expected{$part_id} += $item;
                   8354:             }
                   8355:         } else {
                   8356:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8357:         }
                   8358:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8359:     }
                   8360:     if ($symb) {
                   8361:         my %recorded;
                   8362:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8363:         if ($returnhash{'version'}) {
                   8364:             my %lasthash=();
                   8365:             my $version;
                   8366:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8367:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8368:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8369:                 }
                   8370:             }
                   8371:             foreach my $key (keys(%lasthash)) {
                   8372:                 if ($key =~ /\.scantron$/) {
                   8373:                     my $value = &unescape($lasthash{$key});
                   8374:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8375:                     if ($value eq '') {
                   8376:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8377:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8378:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8379:                             }
                   8380:                         }
                   8381:                     } else {
                   8382:                         my @tocheck;
                   8383:                         my @items = split(//,$value);
                   8384:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8385:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8386:                             if (@items < $expected{$part_id}) {
                   8387:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8388:                                 my @singles = split(//,$fragment);
                   8389:                                 foreach my $pos (@singles) {
                   8390:                                     if ($pos eq ' ') {
                   8391:                                         push(@tocheck,$pos);
                   8392:                                     } else {
                   8393:                                         my $next = shift(@items);
                   8394:                                         push(@tocheck,$next);
                   8395:                                     }
                   8396:                                 }
                   8397:                             } else {
                   8398:                                 @tocheck = @items;
                   8399:                             }
                   8400:                             foreach my $letter (@tocheck) {
                   8401:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8402:                                     if ($letter !~ /^[A-J]$/) {
                   8403:                                         $letter = $scantron_config->{'Qoff'};
                   8404:                                     }
                   8405:                                     $recorded{$part_id} .= $letter;
                   8406:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8407:                                     my $digit;
                   8408:                                     if ($letter !~ /^[A-J]$/) {
                   8409:                                         $digit = $scantron_config->{'Qoff'};
                   8410:                                     } else {
                   8411:                                         $digit = $lettdig->{$letter};
                   8412:                                     }
                   8413:                                     $recorded{$part_id} .= $digit;
                   8414:                                 }
                   8415:                             }
                   8416:                         } else {
                   8417:                             @tocheck = @items;
                   8418:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8419:                                 my $curr_sub = shift(@tocheck);
                   8420:                                 my $digit;
                   8421:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8422:                                     $digit = $lettdig->{$curr_sub}-1;
                   8423:                                 }
                   8424:                                 if ($curr_sub eq 'J') {
                   8425:                                     $digit += scalar($numletts);
                   8426:                                 }
                   8427:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8428:                                     if ($j == $digit) {
                   8429:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8430:                                     } else {
                   8431:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8432:                                     }
                   8433:                                 }
                   8434:                             }
                   8435:                         }
                   8436:                     }
                   8437:                 }
                   8438:             }
                   8439:         }
1.554     raeburn  8440:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8441:             if ($recorded{$part_id} eq '') {
                   8442:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8443:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8444:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8445:                     }
                   8446:                 }
                   8447:             }
                   8448:             $record .= $recorded{$part_id};
                   8449:         }
                   8450:     }
                   8451:     return ($counter,$record);
                   8452: }
                   8453: 
                   8454: sub letter_to_digits { 
                   8455:     my %lettdig = (
                   8456:                     A => 1,
                   8457:                     B => 2,
                   8458:                     C => 3,
                   8459:                     D => 4,
                   8460:                     E => 5,
                   8461:                     F => 6,
                   8462:                     G => 7,
                   8463:                     H => 8,
                   8464:                     I => 9,
                   8465:                     J => 0,
                   8466:                   );
                   8467:     return %lettdig;
                   8468: }
                   8469: 
1.423     albertel 8470: 
1.75      albertel 8471: #-------- end of section for handling grading scantron forms -------
                   8472: #
                   8473: #-------------------------------------------------------------------
                   8474: 
1.72      ng       8475: #-------------------------- Menu interface -------------------------
                   8476: #
1.614     www      8477: #--- Href with symb and command ---
                   8478: 
                   8479: sub href_symb_cmd {
                   8480:     my ($symb,$cmd)=@_;
                   8481:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8482: }
                   8483: 
1.443     banghart 8484: sub grading_menu {
1.608     www      8485:     my ($request,$symb) = @_;
1.443     banghart 8486:     if (!$symb) {return '';}
                   8487: 
                   8488:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8489:                   'command'=>'individual');
1.538     schulted 8490:     
1.598     www      8491:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8492: 
                   8493:     $fields{'command'}='ungraded';
                   8494:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8495: 
                   8496:     $fields{'command'}='table';
                   8497:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8498: 
                   8499:     $fields{'command'}='all_for_one';
                   8500:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8501: 
1.621     www      8502:     $fields{'command'}='downloadfilesselect';
                   8503:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8504: 
1.443     banghart 8505:     $fields{'command'} = 'csvform';
1.538     schulted 8506:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8507:     
1.443     banghart 8508:     $fields{'command'} = 'processclicker';
1.538     schulted 8509:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8510:     
1.443     banghart 8511:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8512:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8513: 
                   8514:     $fields{'command'} = 'initialverifyreceipt';
                   8515:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8516:     
1.598     www      8517:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8518:             items =>[
1.598     www      8519:                         {	linktext => 'Select individual students to grade',
                   8520:                     		url => $url1a,
1.538     schulted 8521:                     		permission => 'F',
1.636     wenzelju 8522:                     		icon => 'grade_students.png',
1.598     www      8523:                     		linktitle => 'Grade current resource for a selection of students.'
                   8524:                         }, 
                   8525:                         {       linktext => 'Grade ungraded submissions.',
                   8526:                                 url => $url1b,
                   8527:                                 permission => 'F',
1.636     wenzelju 8528:                                 icon => 'ungrade_sub.png',
1.598     www      8529:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8530:                         },
1.598     www      8531: 
                   8532:                         {       linktext => 'Grading table',
                   8533:                                 url => $url1c,
                   8534:                                 permission => 'F',
1.636     wenzelju 8535:                                 icon => 'grading_table.png',
1.598     www      8536:                                 linktitle => 'Grade current resource for all students.'
                   8537:                         },
1.615     www      8538:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8539:                                 url => $url1d,
                   8540:                                 permission => 'F',
1.636     wenzelju 8541:                                 icon => 'grade_PageFolder.png',
1.598     www      8542:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8543:                         },
                   8544:                         {       linktext => 'Download submissions',
                   8545:                                 url => $url1e,
                   8546:                                 permission => 'F',
1.636     wenzelju 8547:                                 icon => 'download_sub.png',
1.621     www      8548:                                 linktitle => 'Download all students submissions.'
1.598     www      8549:                         }]},
                   8550:                          { categorytitle=>'Automated Grading',
                   8551:                items =>[
                   8552: 
1.538     schulted 8553:                 	    {	linktext => 'Upload Scores',
                   8554:                     		url => $url2,
                   8555:                     		permission => 'F',
                   8556:                     		icon => 'uploadscores.png',
                   8557:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8558:                 	    },
                   8559:                 	    {	linktext => 'Process Clicker',
                   8560:                     		url => $url3,
                   8561:                     		permission => 'F',
                   8562:                     		icon => 'addClickerInfoFile.png',
                   8563:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8564:                 	    },
1.587     raeburn  8565:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8566:                     		url => $url4,
                   8567:                     		permission => 'F',
1.636     wenzelju 8568:                     		icon => 'bubblesheet.png',
1.648     bisitz   8569:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8570:                 	    },
1.616     www      8571:                             {   linktext => 'Verify Receipt Number',
1.602     www      8572:                                 url => $url5,
                   8573:                                 permission => 'F',
1.636     wenzelju 8574:                                 icon => 'receipt_number.png',
1.602     www      8575:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8576:                             }
                   8577: 
1.538     schulted 8578:                     ]
                   8579:             });
                   8580: 
1.443     banghart 8581:     # Create the menu
                   8582:     my $Str;
1.445     banghart 8583:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8584:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8585:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8586: 
1.602     www      8587:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8588:     return $Str;    
                   8589: }
                   8590: 
1.598     www      8591: 
                   8592: sub ungraded {
                   8593:     my ($request)=@_;
                   8594:     &submit_options($request);
                   8595: }
                   8596: 
1.599     www      8597: sub submit_options_sequence {
1.608     www      8598:     my ($request,$symb) = @_;
1.599     www      8599:     if (!$symb) {return '';}
1.600     www      8600:     &commonJSfunctions($request);
                   8601:     my $result;
1.599     www      8602: 
1.600     www      8603:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8604:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8605:     $result.=&selectfield(0).
1.601     www      8606:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8607:             <div>
                   8608:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8609:             </div>
                   8610:         </div>
                   8611:   </form>';
                   8612:     return $result;
                   8613: }
                   8614: 
                   8615: sub submit_options_table {
1.608     www      8616:     my ($request,$symb) = @_;
1.600     www      8617:     if (!$symb) {return '';}
1.599     www      8618:     &commonJSfunctions($request);
                   8619:     my $result;
                   8620: 
                   8621:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8622:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8623: 
1.632     www      8624:     $result.=&selectfield(0).
1.601     www      8625:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8626:             <div>
                   8627:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8628:             </div>
                   8629:         </div>
                   8630:   </form>';
                   8631:     return $result;
                   8632: }
1.443     banghart 8633: 
1.621     www      8634: sub submit_options_download {
                   8635:     my ($request,$symb) = @_;
                   8636:     if (!$symb) {return '';}
                   8637: 
                   8638:     &commonJSfunctions($request);
                   8639: 
                   8640:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8641:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8642:     $result.='
                   8643: <h2>
                   8644:   '.&mt('Select Students for Which to Download Submissions').'
                   8645: </h2>'.&selectfield(1).'
                   8646:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8647:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8648:             </div>
                   8649:           </div>
1.600     www      8650: 
                   8651: 
1.621     www      8652:   </form>';
                   8653:     return $result;
                   8654: }
                   8655: 
1.443     banghart 8656: #--- Displays the submissions first page -------
                   8657: sub submit_options {
1.608     www      8658:     my ($request,$symb) = @_;
1.72      ng       8659:     if (!$symb) {return '';}
                   8660: 
1.118     ng       8661:     &commonJSfunctions($request);
1.473     albertel 8662:     my $result;
1.533     bisitz   8663: 
1.72      ng       8664:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8665: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8666:     $result.=&selectfield(1).'
1.601     www      8667:                 <input type="hidden" name="command" value="submission" /> 
                   8668: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8669:             </div>
                   8670:           </div>
                   8671: 
                   8672: 
                   8673:   </form>';
                   8674:     return $result;
                   8675: }
1.533     bisitz   8676: 
1.601     www      8677: sub selectfield {
                   8678:    my ($full)=@_;
1.635     raeburn  8679:    my %options = 
                   8680:           (&Apache::lonlocal::texthash(
                   8681:              'yes'       => 'with submissions',
                   8682:              'queued'    => 'in grading queue',
                   8683:              'graded'    => 'with ungraded submissions',
                   8684:              'incorrect' => 'with incorrect submissions',
                   8685:              'all'       => 'with any status'),
                   8686:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8687:    my $result='<div class="LC_columnSection">
1.537     harmsja  8688:   
1.533     bisitz   8689:     <fieldset>
                   8690:       <legend>
                   8691:        '.&mt('Sections').'
                   8692:       </legend>
1.601     www      8693:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8694:     </fieldset>
1.537     harmsja  8695:   
1.533     bisitz   8696:     <fieldset>
                   8697:       <legend>
                   8698:         '.&mt('Groups').'
                   8699:       </legend>
                   8700:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8701:     </fieldset>
1.537     harmsja  8702:   
1.533     bisitz   8703:     <fieldset>
                   8704:       <legend>
                   8705:         '.&mt('Access Status').'
                   8706:       </legend>
1.601     www      8707:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8708:     </fieldset>';
                   8709:     if ($full) {
                   8710:        $result.='
1.533     bisitz   8711:     <fieldset>
                   8712:       <legend>
                   8713:         '.&mt('Submission Status').'
1.601     www      8714:       </legend>'.
1.635     raeburn  8715:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8716:    '</fieldset>';
                   8717:     }
                   8718:     $result.='</div><br />';
1.44      ng       8719:     return $result;
1.2       albertel 8720: }
                   8721: 
1.285     albertel 8722: sub reset_perm {
                   8723:     undef(%perm);
                   8724: }
                   8725: 
                   8726: sub init_perm {
                   8727:     &reset_perm();
1.300     albertel 8728:     foreach my $test_perm ('vgr','mgr','opa') {
                   8729: 
                   8730: 	my $scope = $env{'request.course.id'};
                   8731: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8732: 
                   8733: 	    $scope .= '/'.$env{'request.course.sec'};
                   8734: 	    if ( $perm{$test_perm}=
                   8735: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8736: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8737: 	    } else {
                   8738: 		delete($perm{$test_perm});
                   8739: 	    }
1.285     albertel 8740: 	}
                   8741:     }
                   8742: }
                   8743: 
1.400     www      8744: sub gather_clicker_ids {
1.408     albertel 8745:     my %clicker_ids;
1.400     www      8746: 
                   8747:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8748: 
                   8749:     # Set up a couple variables.
1.407     albertel 8750:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8751:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8752:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8753: 
1.407     albertel 8754:     foreach my $student (keys(%$classlist)) {
1.438     www      8755:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8756:         my $username = $classlist->{$student}->[$username_idx];
                   8757:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8758:         my $clickers =
1.408     albertel 8759: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8760:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8761:             $id=~s/^[\#0]+//;
1.421     www      8762:             $id=~s/[\-\:]//g;
1.407     albertel 8763:             if (exists($clicker_ids{$id})) {
1.408     albertel 8764: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8765:             } else {
1.408     albertel 8766: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8767:             }
                   8768:         }
                   8769:     }
1.407     albertel 8770:     return %clicker_ids;
1.400     www      8771: }
                   8772: 
1.402     www      8773: sub gather_adv_clicker_ids {
1.408     albertel 8774:     my %clicker_ids;
1.402     www      8775:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8776:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8777:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8778:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8779:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8780:             my ($puname,$pudom)=split(/\:/,$person);
                   8781:             my $clickers =
1.408     albertel 8782: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8783:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8784: 		$id=~s/^[\#0]+//;
1.421     www      8785:                 $id=~s/[\-\:]//g;
1.408     albertel 8786: 		if (exists($clicker_ids{$id})) {
                   8787: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8788: 		} else {
                   8789: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8790: 		}
1.405     www      8791:             }
1.402     www      8792:         }
                   8793:     }
1.407     albertel 8794:     return %clicker_ids;
1.402     www      8795: }
                   8796: 
1.413     www      8797: sub clicker_grading_parameters {
                   8798:     return ('gradingmechanism' => 'scalar',
                   8799:             'upfiletype' => 'scalar',
                   8800:             'specificid' => 'scalar',
                   8801:             'pcorrect' => 'scalar',
                   8802:             'pincorrect' => 'scalar');
                   8803: }
                   8804: 
1.400     www      8805: sub process_clicker {
1.608     www      8806:     my ($r,$symb)=@_;
1.400     www      8807:     if (!$symb) {return '';}
                   8808:     my $result=&checkforfile_js();
1.632     www      8809:     $result.=&Apache::loncommon::start_data_table().
                   8810:              &Apache::loncommon::start_data_table_header_row().
                   8811:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8812:              &Apache::loncommon::end_data_table_header_row().
                   8813:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8814: # Attempt to restore parameters from last session, set defaults if not present
                   8815:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8816:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8817:                                                  \%Saveable_Parameters);
                   8818:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8819:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8820:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8821:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8822: 
                   8823:     my %checked;
1.521     www      8824:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8825:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8826:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8827:        }
                   8828:     }
                   8829: 
1.632     www      8830:     my $upload=&mt("Evaluate File");
1.400     www      8831:     my $type=&mt("Type");
1.402     www      8832:     my $attendance=&mt("Award points just for participation");
                   8833:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8834:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8835:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8836:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8837:     my $pcorrect=&mt("Percentage points for correct solution");
                   8838:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8839:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8840: 						   {'iclicker' => 'i>clicker',
                   8841:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8842:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8843:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8844: function sanitycheck() {
                   8845: // Accept only integer percentages
                   8846:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8847:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8848: // Find out grading choice
                   8849:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8850:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8851:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8852:       }
                   8853:    }
                   8854: // By default, new choice equals user selection
                   8855:    newgradingchoice=gradingchoice;
                   8856: // Not good to give more points for false answers than correct ones
                   8857:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8858:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8859:    }
                   8860: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8861:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8862:       document.forms.gradesupload.pcorrect.value=100;
                   8863:       document.forms.gradesupload.pincorrect.value=100;
                   8864:    }
                   8865: // If the values are different, cannot be attendance only
                   8866:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8867:        (gradingchoice=='attendance')) {
                   8868:        newgradingchoice='personnel';
                   8869:    }
                   8870: // Change grading choice to new one
                   8871:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8872:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8873:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8874:       } else {
                   8875:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8876:       }
                   8877:    }
                   8878: // Remember the old state
                   8879:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8880: }
1.597     wenzelju 8881: ENDUPFORM
                   8882:     $result.= <<ENDUPFORM;
1.400     www      8883: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8884: <input type="hidden" name="symb" value="$symb" />
                   8885: <input type="hidden" name="command" value="processclickerfile" />
                   8886: <input type="file" name="upfile" size="50" />
                   8887: <br /><label>$type: $selectform</label>
1.632     www      8888: ENDUPFORM
                   8889:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8890:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8891:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8892: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8893: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8894: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8895: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8896: <br />&nbsp;&nbsp;&nbsp;
                   8897: <input type="text" name="givenanswer" size="50" />
1.413     www      8898: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8899: ENDGRADINGFORM
                   8900:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8901:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8902:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8903: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8904: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8905: </form>'
1.632     www      8906: ENDPERCFORM
                   8907:     $result.='</td>'.
                   8908:              &Apache::loncommon::end_data_table_row().
                   8909:              &Apache::loncommon::end_data_table();
1.400     www      8910:     return $result;
                   8911: }
                   8912: 
                   8913: sub process_clicker_file {
1.608     www      8914:     my ($r,$symb)=@_;
1.400     www      8915:     if (!$symb) {return '';}
1.413     www      8916: 
                   8917:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8918:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8919:                                               \%Saveable_Parameters);
1.598     www      8920:     my $result='';
1.404     www      8921:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8922: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8923: 	return $result;
1.404     www      8924:     }
1.522     www      8925:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8926:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8927:         return $result;
1.521     www      8928:     }
1.522     www      8929:     my $foundgiven=0;
1.521     www      8930:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8931:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8932:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      8933:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      8934:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8935:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8936:         $foundgiven=$#answers+1;
1.521     www      8937:     }
1.407     albertel 8938:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8939:     my %correct_ids;
1.404     www      8940:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8941: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8942:     }
                   8943:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8944: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8945: 	   $correct_id=~tr/a-z/A-Z/;
                   8946: 	   $correct_id=~s/\s//gs;
                   8947: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8948:            $correct_id=~s/[\-\:]//g;
1.414     www      8949:            if ($correct_id) {
                   8950: 	      $correct_ids{$correct_id}='specified';
                   8951:            }
                   8952:         }
1.400     www      8953:     }
1.404     www      8954:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8955: 	$result.=&mt('Score based on attendance only');
1.521     www      8956:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8957:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8958:     } else {
1.408     albertel 8959: 	my $number=0;
1.411     www      8960: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8961: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8962: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8963: 	    if ($correct_ids{$id} eq 'specified') {
                   8964: 		$result.=&mt('specified');
                   8965: 	    } else {
                   8966: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8967: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8968: 	    }
                   8969: 	    $number++;
                   8970: 	}
1.411     www      8971:         $result.="</p>\n";
1.408     albertel 8972: 	if ($number==0) {
                   8973: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8974: 	    return $result;
1.408     albertel 8975: 	}
1.404     www      8976:     }
1.405     www      8977:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8978:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8979: 		     '<span class="LC_error">',
                   8980: 		     '</span>',
                   8981: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8982:         return $result;
1.405     www      8983:     }
1.410     www      8984: 
                   8985: # Were able to get all the info needed, now analyze the file
                   8986: 
1.411     www      8987:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8988:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8989:     $result.=&Apache::loncommon::start_data_table().
                   8990:              &Apache::loncommon::start_data_table_header_row().
                   8991:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8992:              &Apache::loncommon::end_data_table_header_row().
                   8993:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8994: <td>
1.410     www      8995: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8996: <input type="hidden" name="symb" value="$symb" />
                   8997: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8998: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8999: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9000: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9001: ENDHEADER
1.522     www      9002:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9003:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9004:     } 
1.408     albertel 9005:     my %responses;
                   9006:     my @questiontitles;
1.405     www      9007:     my $errormsg='';
                   9008:     my $number=0;
                   9009:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9010: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9011:     }
1.419     www      9012:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9013:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9014:     }
1.411     www      9015:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9016:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9017:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9018:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9019:              '<br />';
1.522     www      9020:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9021:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9022:        return $result;
1.522     www      9023:     } 
1.414     www      9024: # Remember Question Titles
                   9025: # FIXME: Possibly need delimiter other than ":"
                   9026:     for (my $i=0;$i<$number;$i++) {
                   9027:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9028:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9029:     }
1.411     www      9030:     my $correct_count=0;
                   9031:     my $student_count=0;
                   9032:     my $unknown_count=0;
1.414     www      9033: # Match answers with usernames
                   9034: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9035:     foreach my $id (keys(%responses)) {
1.410     www      9036:        if ($correct_ids{$id}) {
1.414     www      9037:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9038:           $correct_count++;
1.410     www      9039:        } elsif ($clicker_ids{$id}) {
1.437     www      9040:           if ($clicker_ids{$id}=~/\,/) {
                   9041: # More than one user with the same clicker!
1.632     www      9042:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9043:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9044:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9045:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9046:                            "<select name='multi".$id."'>";
                   9047:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9048:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9049:              }
                   9050:              $result.='</select>';
                   9051:              $unknown_count++;
                   9052:           } else {
                   9053: # Good: found one and only one user with the right clicker
                   9054:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9055:              $student_count++;
                   9056:           }
1.410     www      9057:        } else {
1.632     www      9058:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9059:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9060:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9061:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9062:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9063:                    "\n".&mt("Domain").": ".
                   9064:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9065:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9066:           $unknown_count++;
1.410     www      9067:        }
1.405     www      9068:     }
1.412     www      9069:     $result.='<hr />'.
                   9070:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9071:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9072:        if ($correct_count==0) {
                   9073:           $errormsg.="Found no correct answers answers for grading!";
                   9074:        } elsif ($correct_count>1) {
1.414     www      9075:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9076:        }
                   9077:     }
1.428     www      9078:     if ($number<1) {
                   9079:        $errormsg.="Found no questions.";
                   9080:     }
1.412     www      9081:     if ($errormsg) {
                   9082:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9083:     } else {
                   9084:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9085:     }
1.632     www      9086:     $result.='</form></td>'.
                   9087:              &Apache::loncommon::end_data_table_row().
                   9088:              &Apache::loncommon::end_data_table();
1.614     www      9089:     return $result;
1.400     www      9090: }
                   9091: 
1.405     www      9092: sub iclicker_eval {
1.406     www      9093:     my ($questiontitles,$responses)=@_;
1.405     www      9094:     my $number=0;
                   9095:     my $errormsg='';
                   9096:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9097:         my %components=&Apache::loncommon::record_sep($line);
                   9098:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9099: 	if ($entries[0] eq 'Question') {
                   9100: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9101: 		$$questiontitles[$number]=$entries[$i];
                   9102: 		$number++;
                   9103: 	    }
                   9104: 	}
                   9105: 	if ($entries[0]=~/^\#/) {
                   9106: 	    my $id=$entries[0];
                   9107: 	    my @idresponses;
                   9108: 	    $id=~s/^[\#0]+//;
                   9109: 	    for (my $i=0;$i<$number;$i++) {
                   9110: 		my $idx=3+$i*6;
1.644     www      9111:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9112: 		push(@idresponses,$entries[$idx]);
                   9113: 	    }
                   9114: 	    $$responses{$id}=join(',',@idresponses);
                   9115: 	}
1.405     www      9116:     }
                   9117:     return ($errormsg,$number);
                   9118: }
                   9119: 
1.419     www      9120: sub interwrite_eval {
                   9121:     my ($questiontitles,$responses)=@_;
                   9122:     my $number=0;
                   9123:     my $errormsg='';
1.420     www      9124:     my $skipline=1;
                   9125:     my $questionnumber=0;
                   9126:     my %idresponses=();
1.419     www      9127:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9128:         my %components=&Apache::loncommon::record_sep($line);
                   9129:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9130:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9131:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9132:         next if $skipline;
                   9133:         if ($entries[0]!=$questionnumber) {
                   9134:            $questionnumber=$entries[0];
                   9135:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9136:            $number++;
1.419     www      9137:         }
1.420     www      9138:         my $id=$entries[4];
                   9139:         $id=~s/^[\#0]+//;
1.421     www      9140:         $id=~s/^v\d*\://i;
                   9141:         $id=~s/[\-\:]//g;
1.420     www      9142:         $idresponses{$id}[$number]=$entries[6];
                   9143:     }
1.524     raeburn  9144:     foreach my $id (keys(%idresponses)) {
1.420     www      9145:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9146:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9147:     }
                   9148:     return ($errormsg,$number);
                   9149: }
                   9150: 
1.414     www      9151: sub assign_clicker_grades {
1.608     www      9152:     my ($r,$symb)=@_;
1.414     www      9153:     if (!$symb) {return '';}
1.416     www      9154: # See which part we are saving to
1.582     raeburn  9155:     my $res_error;
                   9156:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9157:     if ($res_error) {
                   9158:         return &navmap_errormsg();
                   9159:     }
1.416     www      9160: # FIXME: This should probably look for the first handgradeable part
                   9161:     my $part=$$partlist[0];
                   9162: # Start screen output
1.632     www      9163:     my $result=&Apache::loncommon::start_data_table().
                   9164:              &Apache::loncommon::start_data_table_header_row().
                   9165:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9166:              &Apache::loncommon::end_data_table_header_row().
                   9167:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9168: # Get correct result
                   9169: # FIXME: Possibly need delimiter other than ":"
                   9170:     my @correct=();
1.415     www      9171:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9172:     my $number=$env{'form.number'};
                   9173:     if ($gradingmechanism ne 'attendance') {
1.414     www      9174:        foreach my $key (keys(%env)) {
                   9175:           if ($key=~/^form\.correct\:/) {
                   9176:              my @input=split(/\,/,$env{$key});
                   9177:              for (my $i=0;$i<=$#input;$i++) {
                   9178:                  if (($correct[$i]) && ($input[$i]) &&
                   9179:                      ($correct[$i] ne $input[$i])) {
                   9180:                     $result.='<br /><span class="LC_warning">'.
                   9181:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9182:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9183:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9184:                     $correct[$i]=$input[$i];
                   9185:                  }
                   9186:              }
                   9187:           }
                   9188:        }
1.415     www      9189:        for (my $i=0;$i<$number;$i++) {
1.644     www      9190:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9191:              $result.='<br /><span class="LC_error">'.
                   9192:                       &mt('No correct result given for question "[_1]"!',
                   9193:                           $env{'form.question:'.$i}).'</span>';
                   9194:           }
                   9195:        }
1.644     www      9196:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9197:     }
                   9198: # Start grading
1.415     www      9199:     my $pcorrect=$env{'form.pcorrect'};
                   9200:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9201:     my $storecount=0;
1.632     www      9202:     my %users=();
1.415     www      9203:     foreach my $key (keys(%env)) {
1.420     www      9204:        my $user='';
1.415     www      9205:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9206:           $user=$1;
                   9207:        }
                   9208:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9209:           my $id=$1;
                   9210:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9211:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9212:           } elsif ($env{'form.multi'.$id}) {
                   9213:              $user=$env{'form.multi'.$id};
1.420     www      9214:           }
                   9215:        }
1.632     www      9216:        if ($user) {
                   9217:           if ($users{$user}) {
                   9218:              $result.='<br /><span class="LC_warning">'.
                   9219:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9220:                       '</span><br />';
                   9221:           }
                   9222:           $users{$user}=1; 
1.415     www      9223:           my @answer=split(/\,/,$env{$key});
                   9224:           my $sum=0;
1.522     www      9225:           my $realnumber=$number;
1.415     www      9226:           for (my $i=0;$i<$number;$i++) {
1.576     www      9227:              if  ($correct[$i] eq '-') {
                   9228:                 $realnumber--;
1.644     www      9229:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9230:                 if ($gradingmechanism eq 'attendance') {
                   9231:                    $sum+=$pcorrect;
1.576     www      9232:                 } elsif ($correct[$i] eq '*') {
1.522     www      9233:                    $sum+=$pcorrect;
1.415     www      9234:                 } else {
1.644     www      9235: # We actually grade if correct or not
                   9236:                    my $increment=$pincorrect;
                   9237: # Special case: numerical answer "0"
                   9238:                    if ($correct[$i] eq '0') {
                   9239:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9240:                          $increment=$pcorrect;
                   9241:                       }
                   9242: # General numerical answer, both evaluate to something non-zero
                   9243:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9244:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9245:                          $increment=$pcorrect;
                   9246:                       }
                   9247: # Must be just alphanumeric
                   9248:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9249:                       $increment=$pcorrect;
1.415     www      9250:                    }
1.644     www      9251:                    $sum+=$increment;
1.415     www      9252:                 }
                   9253:              }
                   9254:           }
1.522     www      9255:           my $ave=$sum/(100*$realnumber);
1.416     www      9256: # Store
                   9257:           my ($username,$domain)=split(/\:/,$user);
                   9258:           my %grades=();
                   9259:           $grades{"resource.$part.solved"}='correct_by_override';
                   9260:           $grades{"resource.$part.awarded"}=$ave;
                   9261:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9262:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9263:                                                  $env{'request.course.id'},
                   9264:                                                  $domain,$username);
                   9265:           if ($returncode ne 'ok') {
                   9266:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9267:           } else {
                   9268:              $storecount++;
                   9269:           }
1.415     www      9270:        }
                   9271:     }
                   9272: # We are done
1.549     hauer    9273:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9274:              '</td>'.
                   9275:              &Apache::loncommon::end_data_table_row().
                   9276:              &Apache::loncommon::end_data_table();
1.614     www      9277:     return $result;
1.414     www      9278: }
                   9279: 
1.582     raeburn  9280: sub navmap_errormsg {
                   9281:     return '<div class="LC_error">'.
                   9282:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9283:            &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  9284:            '</div>';
                   9285: }
1.607     droeschl 9286: 
1.609     www      9287: sub startpage {
1.613     www      9288:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9289:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9290:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9291:                                           {'bread_crumbs' => $crumbs}));
1.645     www      9292:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
1.613     www      9293:     unless ($nodisplayflag) {
                   9294:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9295:     }
1.607     droeschl 9296: }
1.582     raeburn  9297: 
1.622     www      9298: sub select_problem {
                   9299:     my ($r)=@_;
1.632     www      9300:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9301:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9302:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9303:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9304: }
                   9305: 
1.1       albertel 9306: sub handler {
1.41      ng       9307:     my $request=$_[0];
1.434     albertel 9308:     &reset_caches();
1.646     raeburn  9309:     if ($request->header_only) {
                   9310:         &Apache::loncommon::content_type($request,'text/html');
                   9311:         $request->send_http_header;
                   9312:         return OK;
                   9313:     }
                   9314:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9315: 
                   9316:     &init_perm();
                   9317:     if (!$env{'request.course.id'}) {
                   9318:         # Not in a course.
                   9319:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9320:         return HTTP_NOT_ACCEPTABLE;
                   9321:     } elsif (!%perm) {
                   9322:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9323:     }
1.646     raeburn  9324:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9325:     $request->send_http_header;
1.646     raeburn  9326: 
1.608     www      9327: 
                   9328: # see what command we need to execute
                   9329: 
1.160     albertel 9330:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9331:     my $command=$commands[0];
1.447     foxr     9332: 
1.160     albertel 9333:     if ($#commands > 0) {
                   9334: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9335:     }
1.608     www      9336: 
                   9337: # see what the symb is
                   9338: 
                   9339:     my $symb=$env{'form.symb'};
                   9340:     unless ($symb) {
                   9341:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9342:        $symb=&Apache::lonnet::symbread($url);
                   9343:     }
1.646     raeburn  9344:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9345: 
1.513     foxr     9346:     $ssi_error = 0;
1.637     www      9347:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9348: #
1.637     www      9349: # Not called from a resource, but inside a course
1.601     www      9350: #    
1.622     www      9351:         &startpage($request,undef,[],1,1);
                   9352:         &select_problem($request);
1.41      ng       9353:     } else {
1.104     albertel 9354: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9355:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9356: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9357: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9358:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9359:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9360: 	    &pickStudentPage($request,$symb);
1.103     albertel 9361: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9362:             &startpage($request,$symb,
                   9363:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9364:                                        {href=>'',text=>'Select student'},
                   9365:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9366: 	    &displayPage($request,$symb);
1.104     albertel 9367: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9368:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9369:                                        {href=>'',text=>'Select student'},
                   9370:                                        {href=>'',text=>'Grade student'},
                   9371:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9372: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9373: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9374:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9375:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9376: 	    &processGroup($request,$symb);
1.104     albertel 9377: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9378:             &startpage($request,$symb);
                   9379: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9380: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9381:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9382: 	    $request->print(&submit_options($request,$symb));
1.598     www      9383:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9384:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9385:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9386:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9387:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9388:             $request->print(&submit_options_table($request,$symb));
1.598     www      9389:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9390:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9391:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9392: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9393:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9394: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9395: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9396:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9397:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9398: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9399: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9400:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9401:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9402:                                                                              text=>"Modify grades"},
                   9403:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9404: 	    $request->print(&editgrades($request,$symb));
1.602     www      9405:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9406:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9407:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9408: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9409:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9410:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9411: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9412:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9413:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9414:             $request->print(&process_clicker($request,$symb));
1.400     www      9415:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9416:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9417:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9418:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9419:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9420:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9421:                                        {href=>'', text=>'Process clicker file'},
                   9422:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9423:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9424: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9425:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9426: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9427: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9428:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9429: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9430: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9431:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9432: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9433: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9434: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9435:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9436: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9437: 	    } else {
1.257     albertel 9438: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9439: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9440: 		} else {
1.257     albertel 9441: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9442: 		}
1.627     www      9443:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9444: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9445: 	    }
1.246     albertel 9446: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9447:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9448: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9449: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9450:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9451: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9452:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9453:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9454:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9455: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9456:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9457: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9458: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9459:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9460: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9461:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9462:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9463: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9464:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9465:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9466:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9467:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9468: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9469:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9470:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9471:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9472: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9473:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9474:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9475:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9476:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9477:             $request->print(&checkscantron_results($request,$symb));
                   9478:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9479:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9480:             $request->print(&submit_options_download($request,$symb));
                   9481:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9482:             &startpage($request,$symb,
                   9483:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9484:     {href=>'', text=>'Download submissions'}]);
                   9485:             &submit_download_link($request,$symb);
1.106     albertel 9486: 	} elsif ($command) {
1.620     www      9487:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9488: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9489: 	}
1.2       albertel 9490:     }
1.513     foxr     9491:     if ($ssi_error) {
                   9492: 	&ssi_print_error($request);
                   9493:     }
1.639     www      9494:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9495:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9496:     &reset_caches();
1.646     raeburn  9497:     return OK;
1.44      ng       9498: }
                   9499: 
1.1       albertel 9500: 1;
                   9501: 
1.13      albertel 9502: __END__;
1.531     jms      9503: 
                   9504: 
                   9505: =head1 NAME
                   9506: 
                   9507: Apache::grades
                   9508: 
                   9509: =head1 SYNOPSIS
                   9510: 
                   9511: Handles the viewing of grades.
                   9512: 
                   9513: This is part of the LearningOnline Network with CAPA project
                   9514: described at http://www.lon-capa.org.
                   9515: 
                   9516: =head1 OVERVIEW
                   9517: 
                   9518: Do an ssi with retries:
                   9519: While I'd love to factor out this with the vesrion in lonprintout,
                   9520: 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
                   9521: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9522: 
                   9523: At least the logic that drives this has been pulled out into loncommon.
                   9524: 
                   9525: 
                   9526: 
                   9527: ssi_with_retries - Does the server side include of a resource.
                   9528:                      if the ssi call returns an error we'll retry it up to
                   9529:                      the number of times requested by the caller.
                   9530:                      If we still have a proble, no text is appended to the
                   9531:                      output and we set some global variables.
                   9532:                      to indicate to the caller an SSI error occurred.  
                   9533:                      All of this is supposed to deal with the issues described
                   9534:                      in LonCAPA BZ 5631 see:
                   9535:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9536:                      by informing the user that this happened.
                   9537: 
                   9538: Parameters:
                   9539:   resource   - The resource to include.  This is passed directly, without
                   9540:                interpretation to lonnet::ssi.
                   9541:   form       - The form hash parameters that guide the interpretation of the resource
                   9542:                
                   9543:   retries    - Number of retries allowed before giving up completely.
                   9544: Returns:
                   9545:   On success, returns the rendered resource identified by the resource parameter.
                   9546: Side Effects:
                   9547:   The following global variables can be set:
                   9548:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9549:                               It is up to the caller to initialize this to false
                   9550:                               if desired.
                   9551:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9552:                               of the resource that could not be rendered by the ssi
                   9553:                               call.
                   9554:    ssi_error_message   - The error string fetched from the ssi response
                   9555:                               in the event of an error.
                   9556: 
                   9557: 
                   9558: =head1 HANDLER SUBROUTINE
                   9559: 
                   9560: ssi_with_retries()
                   9561: 
                   9562: =head1 SUBROUTINES
                   9563: 
                   9564: =over
                   9565: 
                   9566: =item scantron_get_correction() : 
                   9567: 
                   9568:    Builds the interface screen to interact with the operator to fix a
                   9569:    specific error condition in a specific scanline
                   9570: 
                   9571:  Arguments:
                   9572:     $r           - Apache request object
                   9573:     $i           - number of the current scanline
                   9574:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9575:     $scan_config - hash ref as returned from &get_scantron_config()
                   9576:     $line        - full contents of the current scanline
                   9577:     $error       - error condition, valid values are
                   9578:                    'incorrectCODE', 'duplicateCODE',
                   9579:                    'doublebubble', 'missingbubble',
                   9580:                    'duplicateID', 'incorrectID'
                   9581:     $arg         - extra information needed
                   9582:        For errors:
                   9583:          - duplicateID   - paper number that this studentID was seen before on
                   9584:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9585:                            seen on before
                   9586:          - incorrectCODE - current incorrect CODE 
                   9587:          - doublebubble  - array ref of the bubble lines that have double
                   9588:                            bubble errors
                   9589:          - missingbubble - array ref of the bubble lines that have missing
                   9590:                            bubble errors
                   9591: 
                   9592: =item  scantron_get_maxbubble() : 
                   9593: 
1.582     raeburn  9594:    Arguments:
                   9595:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9596:                       failure to retrieve a navmap object.
                   9597:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9598:        calling routine should trap the error condition and display the warning
                   9599:        found in &navmap_errormsg().
                   9600: 
1.649     raeburn  9601:        $scantron_config - Reference to bubblesheet format configuration hash.
                   9602: 
1.531     jms      9603:    Returns the maximum number of bubble lines that are expected to
                   9604:    occur. Does this by walking the selected sequence rendering the
                   9605:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9606:    for what the current value of the problem counter is.
                   9607: 
                   9608:    Caches the results to $env{'form.scantron_maxbubble'},
                   9609:    $env{'form.scantron.bubble_lines.n'}, 
                   9610:    $env{'form.scantron.first_bubble_line.n'} and
                   9611:    $env{"form.scantron.sub_bubblelines.n"}
                   9612:    which are the total number of bubble, lines, the number of bubble
                   9613:    lines for response n and number of the first bubble line for response n,
                   9614:    and a comma separated list of numbers of bubble lines for sub-questions
                   9615:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9616: 
                   9617: 
                   9618: =item  scantron_validate_missingbubbles() : 
                   9619: 
                   9620:    Validates all scanlines in the selected file to not have any
                   9621:     answers that don't have bubbles that have not been verified
                   9622:     to be bubble free.
                   9623: 
                   9624: =item  scantron_process_students() : 
                   9625: 
                   9626:    Routine that does the actual grading of the bubble sheet information.
                   9627: 
                   9628:    The parsed scanline hash is added to %env 
                   9629: 
                   9630:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9631:    foreach resource , with the form data of
                   9632: 
                   9633: 	'submitted'     =>'scantron' 
                   9634: 	'grade_target'  =>'grade',
                   9635: 	'grade_username'=> username of student
                   9636: 	'grade_domain'  => domain of student
                   9637: 	'grade_courseid'=> of course
                   9638: 	'grade_symb'    => symb of resource to grade
                   9639: 
                   9640:     This triggers a grading pass. The problem grading code takes care
                   9641:     of converting the bubbled letter information (now in %env) into a
                   9642:     valid submission.
                   9643: 
                   9644: =item  scantron_upload_scantron_data() :
                   9645: 
                   9646:     Creates the screen for adding a new bubble sheet data file to a course.
                   9647: 
                   9648: =item  scantron_upload_scantron_data_save() : 
                   9649: 
                   9650:    Adds a provided bubble information data file to the course if user
                   9651:    has the correct privileges to do so. 
                   9652: 
                   9653: =item  valid_file() :
                   9654: 
                   9655:    Validates that the requested bubble data file exists in the course.
                   9656: 
                   9657: =item  scantron_download_scantron_data() : 
                   9658: 
                   9659:    Shows a list of the three internal files (original, corrected,
                   9660:    skipped) for a specific bubble sheet data file that exists in the
                   9661:    course.
                   9662: 
                   9663: =item  scantron_validate_ID() : 
                   9664: 
                   9665:    Validates all scanlines in the selected file to not have any
1.556     weissno  9666:    invalid or underspecified student/employee IDs
1.531     jms      9667: 
1.582     raeburn  9668: =item navmap_errormsg() :
                   9669: 
                   9670:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9671:    Should be called whenever the request to instantiate a navmap object fails.  
                   9672: 
1.531     jms      9673: =back
                   9674: 
                   9675: =cut

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