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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.656   ! raeburn     4: # $Id: grades.pm,v 1.655 2011/10/09 15:31:12 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',
1.656   ! raeburn  1417:                 type => 'Type',
1.652     raeburn  1418:                 subj => 'Subject',
                   1419:                 mesa => 'Message',
                   1420:                 new  => 'New',
                   1421:                 save => 'Save',
                   1422:                 canc => 'Cancel',
                   1423:                 kehi => 'Keyword Highlight Options',
                   1424:                 txtc => 'Text Color',
                   1425:                 font => 'Font Size',
1.656   ! raeburn  1426:                 fnst => 'Font Style',
1.652     raeburn  1427:              );
1.597     wenzelju 1428:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1429: 
1.44      ng       1430: //===================== Show list of keywords ====================
1.122     ng       1431:   function keywords(formname) {
1.652     raeburn  1432:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1433:     if (nret==null) return;
1.122     ng       1434:     formname.keywords.value = nret;
1.44      ng       1435: 
1.122     ng       1436:     if (formname.keywords.value != "") {
1.128     ng       1437: 	formname.refresh.value = "on";
1.122     ng       1438: 	formname.submit();
1.44      ng       1439:     }
                   1440:     return;
                   1441:   }
                   1442: 
                   1443: //===================== Script to view submitted by ==================
                   1444:   function viewSubmitter(submitter) {
                   1445:     document.SCORE.refresh.value = "on";
                   1446:     document.SCORE.NCT.value = "1";
                   1447:     document.SCORE.unamedom0.value = submitter;
                   1448:     document.SCORE.submit();
                   1449:     return;
                   1450:   }
                   1451: 
                   1452: //===================== Script to add keyword(s) ==================
                   1453:   function getSel() {
                   1454:     if (document.getSelection) txt = document.getSelection();
                   1455:     else if (document.selection) txt = document.selection.createRange().text;
                   1456:     else return;
                   1457:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1458:     if (cleantxt=="") {
1.652     raeburn  1459: 	alert("$lt{'plse'}");
1.44      ng       1460: 	return;
                   1461:     }
1.652     raeburn  1462:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1463:     if (nret==null) return;
1.127     ng       1464:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1465:     if (document.SCORE.keywords.value != "") {
1.127     ng       1466: 	document.SCORE.refresh.value = "on";
1.44      ng       1467: 	document.SCORE.submit();
                   1468:     }
                   1469:     return;
                   1470:   }
                   1471: 
                   1472: //====================== Script for composing message ==============
1.80      ng       1473:    // preload images
                   1474:    img1 = new Image();
                   1475:    img1.src = "$iconpath/mailbkgrd.gif";
                   1476:    img2 = new Image();
                   1477:    img2.src = "$iconpath/mailto.gif";
                   1478: 
1.44      ng       1479:   function msgCenter(msgform,usrctr,fullname) {
                   1480:     var Nmsg  = msgform.savemsgN.value;
                   1481:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1482:     var subject = msgform.msgsub.value;
1.127     ng       1483:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1484:     re = /msgsub/;
                   1485:     var shwsel = "";
                   1486:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1487:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1488:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1489:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1490: 	var testmsg = "savemsg"+i+",";
                   1491: 	re = new RegExp(testmsg,"g");
1.44      ng       1492: 	shwsel = "";
                   1493: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1494: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1495: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1496: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1497: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1498:     }
1.125     ng       1499:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1500:     shwsel = "";
                   1501:     re = /newmsg/;
                   1502:     if (re.test(msgchk)) { shwsel = "checked" }
                   1503:     newMsg(newmsg,shwsel);
                   1504:     msgTail(); 
                   1505:     return;
                   1506:   }
                   1507: 
1.123     ng       1508:   function checkEntities(strx) {
                   1509:     if (strx.length == 0) return strx;
                   1510:     var orgStr = ["&", "<", ">", '"']; 
                   1511:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1512:     var counter = 0;
                   1513:     while (counter < 4) {
                   1514: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1515: 	counter++;
                   1516:     }
                   1517:     return strx;
                   1518:   }
                   1519: 
                   1520:   function strReplace(strx, orgStr, newStr) {
                   1521:     return strx.split(orgStr).join(newStr);
                   1522:   }
                   1523: 
1.44      ng       1524:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1525:     var height = 70*Nmsg+250;
1.44      ng       1526:     var scrollbar = "no";
                   1527:     if (height > 600) {
                   1528: 	height = 600;
                   1529: 	scrollbar = "yes";
                   1530:     }
1.118     ng       1531:     var xpos = (screen.width-600)/2;
                   1532:     xpos = (xpos < 0) ? '0' : xpos;
                   1533:     var ypos = (screen.height-height)/2-30;
                   1534:     ypos = (ypos < 0) ? '0' : ypos;
                   1535: 
1.647     bisitz   1536:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1537:     pWin.focus();
                   1538:     pDoc = pWin.document;
1.219     www      1539:     pDoc.$docopen;
1.351     albertel 1540:     pDoc.write('$start_page_msg_central');
1.76      ng       1541: 
                   1542:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1543:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.652     raeburn  1544:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1545: 
1.564     bisitz   1546:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1547:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656   ! raeburn  1548:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1549: }
                   1550:     function displaySubject(msg,shwsel) {
1.76      ng       1551:     pDoc = pWin.document;
                   1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1553:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1554:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1555:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1556: }
                   1557: 
1.72      ng       1558:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1559:     pDoc = pWin.document;
                   1560:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1561:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1562:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1563:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1564: }
                   1565: 
                   1566:   function newMsg(newmsg,shwsel) {
1.76      ng       1567:     pDoc = pWin.document;
                   1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1569:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1570:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1571:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1572: }
                   1573: 
                   1574:   function msgTail() {
1.76      ng       1575:     pDoc = pWin.document;
1.465     albertel 1576:     pDoc.write("<\\/table>");
                   1577:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1578:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1579:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1580:     pDoc.write("<\\/form>");
1.351     albertel 1581:     pDoc.write('$end_page_msg_central');
1.128     ng       1582:     pDoc.close();
1.44      ng       1583: }
                   1584: 
                   1585: //====================== Script for keyword highlight options ==============
                   1586:   function kwhighlight() {
                   1587:     var kwclr    = document.SCORE.kwclr.value;
                   1588:     var kwsize   = document.SCORE.kwsize.value;
                   1589:     var kwstyle  = document.SCORE.kwstyle.value;
                   1590:     var redsel = "";
                   1591:     var grnsel = "";
                   1592:     var blusel = "";
                   1593:     if (kwclr=="red")   {var redsel="checked"};
                   1594:     if (kwclr=="green") {var grnsel="checked"};
                   1595:     if (kwclr=="blue")  {var blusel="checked"};
                   1596:     var sznsel = "";
                   1597:     var sz1sel = "";
                   1598:     var sz2sel = "";
                   1599:     if (kwsize=="0")  {var sznsel="checked"};
                   1600:     if (kwsize=="+1") {var sz1sel="checked"};
                   1601:     if (kwsize=="+2") {var sz2sel="checked"};
                   1602:     var synsel = "";
                   1603:     var syisel = "";
                   1604:     var sybsel = "";
                   1605:     if (kwstyle=="")    {var synsel="checked"};
                   1606:     if (kwstyle=="<i>") {var syisel="checked"};
                   1607:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1608:     highlightCentral();
                   1609:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1610:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1611:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1612:     highlightend();
                   1613:     return;
                   1614:   }
                   1615: 
                   1616:   function highlightCentral() {
1.76      ng       1617: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1618:     var xpos = (screen.width-400)/2;
                   1619:     xpos = (xpos < 0) ? '0' : xpos;
                   1620:     var ypos = (screen.height-330)/2-30;
                   1621:     ypos = (ypos < 0) ? '0' : ypos;
                   1622: 
1.206     albertel 1623:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1624:     hwdWin.focus();
                   1625:     var hDoc = hwdWin.document;
1.219     www      1626:     hDoc.$docopen;
1.351     albertel 1627:     hDoc.write('$start_page_highlight_central');
1.76      ng       1628:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1629:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1630: 
1.564     bisitz   1631:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1632:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656   ! raeburn  1633:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1634:   }
                   1635: 
                   1636:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1637:     var hDoc = hwdWin.document;
                   1638:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1639:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1640:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1641:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1642:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1643:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1644:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1645:     hDoc.write("<\\/tr>");
1.44      ng       1646:   }
                   1647: 
                   1648:   function highlightend() { 
1.76      ng       1649:     var hDoc = hwdWin.document;
1.465     albertel 1650:     hDoc.write("<\\/table>");
                   1651:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1652:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1653:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1654:     hDoc.write("<\\/form>");
1.351     albertel 1655:     hDoc.write('$end_page_highlight_central');
1.128     ng       1656:     hDoc.close();
1.44      ng       1657:   }
                   1658: 
                   1659: SUBJAVASCRIPT
                   1660: }
                   1661: 
1.349     albertel 1662: sub get_increment {
1.348     bowersj2 1663:     my $increment = $env{'form.increment'};
                   1664:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1665:         $increment != .1) {
                   1666:         $increment = 1;
                   1667:     }
                   1668:     return $increment;
                   1669: }
                   1670: 
1.585     bisitz   1671: sub gradeBox_start {
                   1672:     return (
                   1673:         &Apache::loncommon::start_data_table()
                   1674:        .&Apache::loncommon::start_data_table_header_row()
                   1675:        .'<th>'.&mt('Part').'</th>'
                   1676:        .'<th>'.&mt('Points').'</th>'
                   1677:        .'<th>&nbsp;</th>'
                   1678:        .'<th>'.&mt('Assign Grade').'</th>'
                   1679:        .'<th>'.&mt('Weight').'</th>'
                   1680:        .'<th>'.&mt('Grade Status').'</th>'
                   1681:        .&Apache::loncommon::end_data_table_header_row()
                   1682:     );
                   1683: }
                   1684: 
                   1685: sub gradeBox_end {
                   1686:     return (
                   1687:         &Apache::loncommon::end_data_table()
                   1688:     );
                   1689: }
1.71      ng       1690: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1691: sub gradeBox {
1.322     albertel 1692:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1693:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1694: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1695:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1696:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1697:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1698:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1699:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1700: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1701:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1702:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1703:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1704: 				       [$partid]);
                   1705:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1706:     if ($last_resets{$partid}) {
                   1707:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1708:     }
1.585     bisitz   1709:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1710:     my $ctr = 0;
1.348     bowersj2 1711:     my $thisweight = 0;
1.349     albertel 1712:     my $increment = &get_increment();
1.485     albertel 1713: 
                   1714:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1715:     while ($thisweight<=$wgt) {
1.532     bisitz   1716: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1717:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1718: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1719: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1720: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1721:         $thisweight += $increment;
1.71      ng       1722: 	$ctr++;
                   1723:     }
1.485     albertel 1724:     $radio.='</tr></table>';
                   1725: 
                   1726:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1727: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1728: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1729: 	$wgt.')" /></td>'."\n";
1.485     albertel 1730:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1731: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1732: 	' </td>'."\n";
                   1733:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1734: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1735:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1736: 	$line.='<option></option>'.
                   1737: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1738:     } else {
1.485     albertel 1739: 	$line.='<option selected="selected"></option>'.
                   1740: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1741:     }
1.485     albertel 1742:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1743: 
                   1744: 
                   1745:     $result .= 
1.585     bisitz   1746: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1747:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1748:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1749: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1750: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1751: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1752:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1753:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1754:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1755:         $aggtries.'" />'."\n";
1.582     raeburn  1756:     my $res_error;
                   1757:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1758:     if ($res_error) {
                   1759:         return &navmap_errormsg();
                   1760:     }
1.318     banghart 1761:     return $result;
                   1762: }
1.322     albertel 1763: 
                   1764: sub handback_box {
1.623     www      1765:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1766:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1767:     my (@respids);
1.652     raeburn  1768:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1769:     foreach my $part_response_id (@part_response_id) {
                   1770:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1771:         if ($part eq $partid) {
1.375     albertel 1772:             push(@respids,$resp);
1.323     banghart 1773:         }
                   1774:     }
1.318     banghart 1775:     my $result;
1.323     banghart 1776:     foreach my $respid (@respids) {
1.322     albertel 1777: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1778: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1779: 	next if (!@$files);
1.654     raeburn  1780: 	my $file_counter = 0;
1.313     banghart 1781: 	foreach my $file (@$files) {
1.368     banghart 1782: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1783:                 $file_counter++;
1.368     banghart 1784:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1785:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1786:     	        $file_disp = "$name.$ext";
                   1787:     	        $file = $file_path.$file_disp;
                   1788:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1789:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1790:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1791:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1792: 	    }
1.322     albertel 1793: 	}
1.654     raeburn  1794:         if ($file_counter) {
                   1795:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1796:                        '<span class="LC_info">'.
                   1797:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1798:         }
1.313     banghart 1799:     }
1.318     banghart 1800:     return $result;    
1.71      ng       1801: }
1.44      ng       1802: 
1.58      albertel 1803: sub show_problem {
1.382     albertel 1804:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1805:     my $rendered;
1.382     albertel 1806:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1807:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1808:     if ($mode eq 'both' or $mode eq 'text') {
                   1809: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1810: 						       $env{'request.course.id'},
                   1811: 						       undef,\%form);
1.144     albertel 1812:     }
1.58      albertel 1813:     if ($removeform) {
                   1814: 	$rendered=~s|<form(.*?)>||g;
                   1815: 	$rendered=~s|</form>||g;
1.374     albertel 1816: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1817:     }
1.144     albertel 1818:     my $companswer;
                   1819:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1820: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1821: 	$companswer=
                   1822: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1823: 						    $env{'request.course.id'},
                   1824: 						    %form);
1.144     albertel 1825:     }
1.58      albertel 1826:     if ($removeform) {
                   1827: 	$companswer=~s|<form(.*?)>||g;
                   1828: 	$companswer=~s|</form>||g;
1.144     albertel 1829: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1830:     }
1.468     albertel 1831:     $rendered=
1.588     bisitz   1832:         '<div class="LC_Box">'
                   1833:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1834:        .$rendered
                   1835:        .'</div>';
1.468     albertel 1836:     $companswer=
1.588     bisitz   1837:         '<div class="LC_Box">'
                   1838:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1839:        .$companswer
                   1840:        .'</div>';
1.468     albertel 1841:     my $result;
1.144     albertel 1842:     if ($mode eq 'both') {
1.588     bisitz   1843:         $result=$rendered.$companswer;
1.144     albertel 1844:     } elsif ($mode eq 'text') {
1.588     bisitz   1845:         $result=$rendered;
1.144     albertel 1846:     } elsif ($mode eq 'answer') {
1.588     bisitz   1847:         $result=$companswer;
1.144     albertel 1848:     }
1.71      ng       1849:     return $result;
1.58      albertel 1850: }
1.397     albertel 1851: 
1.396     banghart 1852: sub files_exist {
                   1853:     my ($r, $symb) = @_;
                   1854:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1855: 
1.396     banghart 1856:     foreach my $student (@students) {
                   1857:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1858:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1859: 					      $udom,$uname);
1.396     banghart 1860:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1861:         foreach my $submission (@$string) {
                   1862:             my ($partid,$respid) =
                   1863: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1864:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1865: 					   \%record);
                   1866:             return 1 if (@$files);
1.396     banghart 1867:         }
                   1868:     }
1.397     albertel 1869:     return 0;
1.396     banghart 1870: }
1.397     albertel 1871: 
1.394     banghart 1872: sub download_all_link {
                   1873:     my ($r,$symb) = @_;
1.621     www      1874:     unless (&files_exist($r, $symb)) {
                   1875:        $r->print(&mt('There are currently no submitted documents.'));
                   1876:        return;
                   1877:     }
                   1878: 
1.395     albertel 1879:     my $all_students = 
                   1880: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1881: 
                   1882:     my $parts =
                   1883: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1884: 
1.394     banghart 1885:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1886:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1887:                              'cgi.'.$identifier.'.symb' => $symb,
                   1888:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1889:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1890: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1891:     return;
                   1892: }
                   1893: 
                   1894: sub submit_download_link {
                   1895:     my ($request,$symb) = @_;
                   1896:     if (!$symb) { return ''; }
                   1897: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1898:     &download_all_link($request,$symb);
1.394     banghart 1899: }
1.395     albertel 1900: 
1.432     banghart 1901: sub build_section_inputs {
                   1902:     my $section_inputs;
                   1903:     if ($env{'form.section'} eq '') {
                   1904:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1905:     } else {
                   1906:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1907:         foreach my $section (@sections) {
1.432     banghart 1908:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1909:         }
                   1910:     }
                   1911:     return $section_inputs;
                   1912: }
                   1913: 
1.44      ng       1914: # --------------------------- show submissions of a student, option to grade 
                   1915: sub submission {
1.608     www      1916:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1917:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1918:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1919:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1920:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1921: 
1.605     www      1922:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1923:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1924: 
                   1925:     if (!&canview($usec)) {
1.398     albertel 1926: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1927: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1928: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1929: 	return;
                   1930:     }
                   1931: 
1.257     albertel 1932:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1933:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1934:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1935:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1936:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1937: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1938: 	'/check.gif" height="16" border="0" />';
1.41      ng       1939: 
1.426     albertel 1940:     my %old_essays;
1.41      ng       1941:     # header info
                   1942:     if ($counter == 0) {
                   1943: 	&sub_page_js($request);
1.621     www      1944: 	&sub_page_kw_js($request);
1.118     ng       1945: 
1.44      ng       1946: 	# option to display problem, only once else it cause problems 
                   1947:         # with the form later since the problem has a form.
1.257     albertel 1948: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1949: 	    my $mode;
1.257     albertel 1950: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1951: 		$mode='both';
1.257     albertel 1952: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1953: 		$mode='text';
1.257     albertel 1954: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1955: 		$mode='answer';
                   1956: 	    }
1.329     albertel 1957: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1958: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1959: 	}
1.441     www      1960: 
1.44      ng       1961: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1962:         # if this subroutine has been called once.
1.41      ng       1963: 	my %keyhash = ();
1.624     www      1964: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1965:         if (1) {
1.41      ng       1966: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1967: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1968: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1969: 
1.257     albertel 1970: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1971: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1972: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1973: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1974: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1975: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1976: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1977: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1978: 	}
1.257     albertel 1979: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1980: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1981: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1982: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1983: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1984: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1985: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1986: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1987: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1988: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1989: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1990: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1991: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1992: 			&build_section_inputs().
1.326     albertel 1993: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1994: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1995: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1996: #	if ($env{'form.handgrade'} eq 'yes') {
                   1997:         if (1) {
1.257     albertel 1998: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1999: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2000: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2001: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2002: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2003: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2004: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2005: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2006: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2007: 	    }
1.123     ng       2008: 	}
1.41      ng       2009: 	
                   2010: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2011: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2012: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2013: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2014: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2015: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2016: 		'" />'."\n".
                   2017: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2018: 	    $cts++;
                   2019: 	}
                   2020: 	$request->print($prnmsg);
1.32      ng       2021: 
1.624     www      2022: #	if ($env{'form.handgrade'} eq 'yes') {
                   2023:         if (1) {
1.652     raeburn  2024: 
                   2025:             my %lt = &Apache::lonlocal::texthash(
                   2026:                           keyw => 'Keyword Options',
1.655     raeburn  2027:                           list => 'List',
1.652     raeburn  2028:                           past => 'Paste Selection to List',
                   2029:                           high => 'Hightlight Attribute',
                   2030:                      );    
1.88      www      2031: #
                   2032: # Print out the keyword options line
                   2033: #
1.41      ng       2034: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2035: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2036: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2037: <a href="#" onmousedown="javascript:getSel(); return false"
1.652     raeburn  2038:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2039: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2040: KEYWORDS
1.88      www      2041: #
                   2042: # Load the other essays for similarity check
                   2043: #
1.324     albertel 2044:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2045: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2046: 	    $apath=&escape($apath);
1.88      www      2047: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2048: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2049:         }
                   2050:     }
1.44      ng       2051: 
1.441     www      2052: # This is where output for one specific student would start
1.592     bisitz   2053:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2054:     $request->print(
                   2055:         "\n\n"
                   2056:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2057:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2058:        ."\n"
                   2059:     );
1.441     www      2060: 
1.592     bisitz   2061:     # Show additional functions if allowed
                   2062:     if ($perm{'vgr'}) {
                   2063:         $request->print(
                   2064:             &Apache::loncommon::track_student_link(
                   2065:                 &mt('View recent activity'),
                   2066:                 $uname,$udom,'check')
                   2067:            .' '
                   2068:         );
                   2069:     }
                   2070:     if ($perm{'opa'}) {
                   2071:         $request->print(
                   2072:             &Apache::loncommon::pprmlink(
                   2073:                 &mt('Set/Change parameters'),
                   2074:                 $uname,$udom,$symb,'check'));
                   2075:     }
                   2076: 
                   2077:     # Show Problem
1.257     albertel 2078:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2079: 	my $mode;
1.257     albertel 2080: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2081: 	    $mode='both';
1.257     albertel 2082: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2083: 	    $mode='text';
1.257     albertel 2084: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2085: 	    $mode='answer';
                   2086: 	}
1.329     albertel 2087: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2088: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2089:     }
1.144     albertel 2090: 
1.257     albertel 2091:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2092:     my $res_error;
                   2093:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2094:     if ($res_error) {
                   2095:         $request->print(&navmap_errormsg());
                   2096:         return;
                   2097:     }
1.41      ng       2098: 
1.44      ng       2099:     # Display student info
1.41      ng       2100:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2101: 
                   2102:     my $result='<div class="LC_Box">'
                   2103:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2104:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2105:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2106: #    if ($env{'form.handgrade'} eq 'no') {
                   2107:     if (1) {
1.588     bisitz   2108:         $result.='<p class="LC_info">'
                   2109:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2110:                 ."</p>\n";
1.469     albertel 2111:     }
                   2112: 
1.118     ng       2113:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2114:     my $fullname;
                   2115:     my $col_fullnames = [];
1.624     www      2116: #    if ($env{'form.handgrade'} eq 'yes') {
                   2117:     if (1) {
1.464     albertel 2118: 	(my $sub_result,$fullname,$col_fullnames)=
                   2119: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2120: 				 $counter);
                   2121: 	$result.=$sub_result;
1.41      ng       2122:     }
1.44      ng       2123:     $request->print($result."\n");
1.588     bisitz   2124: 
1.44      ng       2125:     # print student answer/submission
1.588     bisitz   2126:     # Options are (1) Handgraded submission only
1.44      ng       2127:     #             (2) Last submission, includes submission that is not handgraded 
                   2128:     #                  (for multi-response type part)
                   2129:     #             (3) Last submission plus the parts info
                   2130:     #             (4) The whole record for this student
1.257     albertel 2131:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2132: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2133: 	
                   2134: 	my $lastsubonly;
                   2135: 
1.588     bisitz   2136:         if ($$timestamp eq '') {
                   2137:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2138:         } else {
1.592     bisitz   2139:             $lastsubonly =
                   2140:                 '<div class="LC_grade_submissions_body">'
                   2141:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2142: 
1.151     albertel 2143: 	    my %seenparts;
1.375     albertel 2144: 	    my @part_response_id = &flatten_responseType($responseType);
                   2145: 	    foreach my $part (@part_response_id) {
1.393     albertel 2146: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2147: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2148: 
1.375     albertel 2149: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2150: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2151: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2152: 		    if (exists($seenparts{$partid})) { next; }
                   2153: 		    $seenparts{$partid}=1;
1.207     albertel 2154: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2155: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2156: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2157: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2158: 			'\');" target="_self">'.
1.257     albertel 2159: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2160: 		    $request->print($submitby);
                   2161: 		    next;
                   2162: 		}
                   2163: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2164: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2165:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2166:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2167:                         ' <span class="LC_internal_info">'.
1.623     www      2168:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2169:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2170: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2171: 		    next;
                   2172: 		}
1.468     albertel 2173: 		foreach my $submission (@$string) {
                   2174: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2175: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2176: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2177: 		    # Similarity check
                   2178: 		    my $similar='';
1.640     raeburn  2179:                     my ($type,$trial,$rndseed);
                   2180:                     if ($hide eq 'rand') {
                   2181:                         $type = 'randomizetry';
                   2182:                         $trial = $record{"resource.$partid.tries"};
                   2183:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2184:                     }
1.257     albertel 2185: 		    if($env{'form.checkPlag'}){
1.151     albertel 2186: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2187: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2188: 			if ($osim) {
                   2189: 			    $osim=int($osim*100.0);
1.426     albertel 2190: 			    my %old_course_desc = 
                   2191: 				&Apache::lonnet::coursedescription($ocrsid,
                   2192: 								   {'one_time' => 1});
                   2193: 
1.640     raeburn  2194:                             if ($hide eq 'anon') {
1.596     raeburn  2195:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2196:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2197:                             } else {
                   2198: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2199: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2200: 				        $osim,
                   2201: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2202: 				        $old_course_desc{'description'},
                   2203: 				        $old_course_desc{'num'},
                   2204: 				        $old_course_desc{'domain'}).
                   2205: 				    '</span></h3><blockquote><i>'.
                   2206: 				    &keywords_highlight($oessay).
                   2207: 				    '</i></blockquote><hr />';
                   2208:                             }
1.151     albertel 2209: 			}
1.150     albertel 2210: 		    }
1.640     raeburn  2211: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2212:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2213: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2214: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2215: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2216: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2217:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2218:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2219:                             ' <span class="LC_internal_info">'.
1.623     www      2220:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2221:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2222: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2223: 			if (@$files) {
1.640     raeburn  2224:                             if ($hide eq 'anon') {
1.596     raeburn  2225:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2226:                             } else {
                   2227:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2228:                                 foreach my $file (@$files) {
                   2229:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2230:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2231:                                 }
                   2232:                             }
1.236     albertel 2233: 			    $lastsubonly.='<br />';
1.41      ng       2234: 			}
1.640     raeburn  2235:                         if ($hide eq 'anon') {
1.596     raeburn  2236:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2237:                         } else {
                   2238: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2239: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2240: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2241:                         }
1.151     albertel 2242: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2243: 			$lastsubonly.='</div>';
1.41      ng       2244: 		    }
                   2245: 		}
                   2246: 	    }
1.588     bisitz   2247: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2248: 	}
                   2249: 	$request->print($lastsubonly);
1.468     albertel 2250:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2251:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2252: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2253:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2254: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2255: 								 $env{'request.course.id'},
1.44      ng       2256: 								 $last,'.submission',
                   2257: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2258:     }
1.121     ng       2259:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2260: 	.$udom.'" />'."\n");
1.44      ng       2261:     # return if view submission with no grading option
1.618     www      2262:     if (!&canmodify($usec)) {
1.633     www      2263: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2264: 	return;
1.180     albertel 2265:     } else {
1.468     albertel 2266: 	$request->print('</div>'."\n");
1.41      ng       2267:     }
1.33      ng       2268: 
1.121     ng       2269:     # essay grading message center
1.624     www      2270: #    if ($env{'form.handgrade'} eq 'yes') {
                   2271:     if (1) {
1.468     albertel 2272: 	my $result='<div class="LC_grade_message_center">';
                   2273:     
                   2274: 	$result.='<div class="LC_grade_message_center_header">'.
                   2275: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2276: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2277: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2278: 	if (scalar(@$col_fullnames) > 0) {
                   2279: 	    my $lastone = pop(@$col_fullnames);
                   2280: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2281: 	}
                   2282: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2283: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2284: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2285: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2286: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2287: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2288: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2289: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2290: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2291: 	    '<br />&nbsp;('.
1.468     albertel 2292: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2293: 	$result.='</div></div>';
1.121     ng       2294: 	$request->print($result);
1.118     ng       2295:     }
1.41      ng       2296: 
                   2297:     my %seen = ();
                   2298:     my @partlist;
1.129     ng       2299:     my @gradePartRespid;
1.375     albertel 2300:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2301:     $request->print(
1.588     bisitz   2302:         '<div class="LC_Box">'
                   2303:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2304:     );
1.592     bisitz   2305:     $request->print(&gradeBox_start());
1.375     albertel 2306:     foreach my $part_response_id (@part_response_id) {
                   2307:     	my ($partid,$respid) = @{ $part_response_id };
                   2308: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2309: 	next if ($seen{$partid} > 0);
1.41      ng       2310: 	$seen{$partid}++;
1.393     albertel 2311: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2312: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2313: 	push(@partlist,$partid);
                   2314: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2315: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2316:     }
1.585     bisitz   2317:     $request->print(&gradeBox_end()); # </div>
                   2318:     $request->print('</div>');
1.468     albertel 2319: 
                   2320:     $request->print('<div class="LC_grade_info_links">');
                   2321:     $request->print('</div>');
                   2322: 
1.45      ng       2323:     $result='<input type="hidden" name="partlist'.$counter.
                   2324: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2325:     $result.='<input type="hidden" name="gradePartRespid'.
                   2326: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2327:     my $ctr = 0;
                   2328:     while ($ctr < scalar(@partlist)) {
                   2329: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2330: 	    $partlist[$ctr].'" />'."\n";
                   2331: 	$ctr++;
                   2332:     }
1.468     albertel 2333:     $request->print($result.''."\n");
1.41      ng       2334: 
1.441     www      2335: # Done with printing info for one student
                   2336: 
1.468     albertel 2337:     $request->print('</div>');#LC_grade_show_user
1.441     www      2338: 
                   2339: 
1.41      ng       2340:     # print end of form
                   2341:     if ($counter == $total) {
1.592     bisitz   2342:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2343: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2344: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2345: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2346: 	my $ntstu ='<select name="NTSTU">'.
                   2347: 	    '<option>1</option><option>2</option>'.
                   2348: 	    '<option>3</option><option>5</option>'.
                   2349: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2350: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2351: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2352:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2353: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2354: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2355: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2356: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2357:         $endform.='<span class="LC_warning">'.
                   2358:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2359:                   '</span>'."\n" ;
1.349     albertel 2360:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2361:             "' name='increment' />";
1.485     albertel 2362: 	$endform.='</td></tr></table></form>';
1.41      ng       2363: 	$request->print($endform);
                   2364:     }
                   2365:     return '';
1.38      ng       2366: }
                   2367: 
1.464     albertel 2368: sub check_collaborators {
                   2369:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2370:     my ($result,@col_fullnames);
                   2371:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2372:     foreach my $part (keys(%$handgrade)) {
                   2373: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2374: 					'.maxcollaborators',
                   2375: 					$symb,$udom,$uname);
                   2376: 	next if ($ncol <= 0);
                   2377: 	$part =~ s/\_/\./g;
                   2378: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2379: 	my (@good_collaborators, @bad_collaborators);
                   2380: 	foreach my $possible_collaborator
1.630     www      2381: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2382: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2383: 	    next if ($possible_collaborator eq '');
1.631     www      2384: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2385: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2386: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2387: 	    # Doing this grep allows 'fuzzy' specification
                   2388: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2389: 			       keys(%$classlist));
                   2390: 	    if (! scalar(@matches)) {
                   2391: 		push(@bad_collaborators, $possible_collaborator);
                   2392: 	    } else {
                   2393: 		push(@good_collaborators, @matches);
                   2394: 	    }
                   2395: 	}
                   2396: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2397: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2398: 	    foreach my $name (@good_collaborators) {
                   2399: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2400: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2401: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2402: 	    }
1.630     www      2403: 	    $result.='</ol><br />'."\n";
1.466     albertel 2404: 	    my ($part)=split(/\./,$part);
1.464     albertel 2405: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2406: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2407: 		"\n";
                   2408: 	}
                   2409: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2410: 	    $result.='<div class="LC_warning">';
1.464     albertel 2411: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2412: 	    $result .= '</div>';
                   2413: 	}         
                   2414: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2415: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2416: 	    $result .= &mt('This student has submitted too many '.
                   2417: 		'collaborators.  Maximum is [_1].',$ncol);
                   2418: 	    $result .= '</div>';
                   2419: 	}
                   2420:     }
                   2421:     return ($result,$fullname,\@col_fullnames);
                   2422: }
                   2423: 
1.44      ng       2424: #--- Retrieve the last submission for all the parts
1.38      ng       2425: sub get_last_submission {
1.119     ng       2426:     my ($returnhash)=@_;
1.596     raeburn  2427:     my (@string,$timestamp,%lasthidden);
1.119     ng       2428:     if ($$returnhash{'version'}) {
1.46      ng       2429: 	my %lasthash=();
                   2430: 	my ($version);
1.119     ng       2431: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2432: 	    foreach my $key (sort(split(/\:/,
                   2433: 					$$returnhash{$version.':keys'}))) {
                   2434: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2435: 		$timestamp = 
1.545     raeburn  2436: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2437: 	    }
                   2438: 	}
1.640     raeburn  2439:         my (%typeparts,%randombytry);
1.596     raeburn  2440:         my $showsurv = 
                   2441:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2442:         foreach my $key (sort(keys(%lasthash))) {
                   2443:             if ($key =~ /\.type$/) {
                   2444:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2445:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2446:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2447:                     my ($ign,@parts) = split(/\./,$key);
                   2448:                     pop(@parts);
1.641     raeburn  2449:                     my $id = join('.',@parts);
1.640     raeburn  2450:                     if ($lasthash{$key} eq 'randomizetry') {
                   2451:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2452:                     } else {
                   2453:                         unless ($showsurv) {
                   2454:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2455:                         }
1.596     raeburn  2456:                     }
                   2457:                     delete($lasthash{$key});
                   2458:                 }
                   2459:             }
                   2460:         }
                   2461:         my @hidden = keys(%typeparts);
1.640     raeburn  2462:         my @randomize = keys(%randombytry);
1.397     albertel 2463: 	foreach my $key (keys(%lasthash)) {
                   2464: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2465:             my $hide;
                   2466:             if (@hidden) {
                   2467:                 foreach my $id (@hidden) {
                   2468:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2469:                         $hide = 'anon';
1.596     raeburn  2470:                         last;
                   2471:                     }
                   2472:                 }
                   2473:             }
1.640     raeburn  2474:             unless ($hide) {
                   2475:                 if (@randomize) {
                   2476:                     foreach my $id (@hidden) {
                   2477:                         if ($key =~ /^\Q$id\E/) {
                   2478:                             $hide = 'rand';
                   2479:                             last;
                   2480:                         }
                   2481:                     }
                   2482:                 }
                   2483:             }
1.397     albertel 2484: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2485: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2486: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2487: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2488: 	}
                   2489:     }
1.397     albertel 2490:     if (!@string) {
                   2491: 	$string[0] =
1.539     riegler  2492: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2493:     }
                   2494:     return (\@string,\$timestamp);
1.38      ng       2495: }
1.35      ng       2496: 
1.44      ng       2497: #--- High light keywords, with style choosen by user.
1.38      ng       2498: sub keywords_highlight {
1.44      ng       2499:     my $string    = shift;
1.257     albertel 2500:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2501:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2502:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2503:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2504:     foreach my $keyword (@keylist) {
                   2505: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2506:     }
                   2507:     return $string;
1.38      ng       2508: }
1.36      ng       2509: 
1.44      ng       2510: #--- Called from submission routine
1.38      ng       2511: sub processHandGrade {
1.608     www      2512:     my ($request,$symb) = @_;
1.324     albertel 2513:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2514:     my $button = $env{'form.gradeOpt'};
                   2515:     my $ngrade = $env{'form.NCT'};
                   2516:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2517:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2518:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2519: 
1.44      ng       2520:     if ($button eq 'Save & Next') {
                   2521: 	my $ctr = 0;
                   2522: 	while ($ctr < $ngrade) {
1.257     albertel 2523: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2524: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2525: 	    if ($errorflag eq 'no_score') {
                   2526: 		$ctr++;
                   2527: 		next;
                   2528: 	    }
1.104     albertel 2529: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2530: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2531: 		$ctr++;
                   2532: 		next;
                   2533: 	    }
1.257     albertel 2534: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2535: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2536: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2537:             my ($feedurl,$showsymb) =
                   2538: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2539: 	    my $messagetail;
1.62      albertel 2540: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2541: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2542: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2543: 		$subject.=' ['.$restitle.']';
1.44      ng       2544: 		my (@msgnum) = split(/,/,$includemsg);
                   2545: 		foreach (@msgnum) {
1.257     albertel 2546: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2547: 		}
1.80      ng       2548: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2549: 		if ($env{'form.withgrades'.$ctr}) {
                   2550: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2551: 		    $messagetail = " for <a href=\"".
1.605     www      2552: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2553: 		}
                   2554: 		$msgstatus = 
                   2555:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2556: 						     $message.$messagetail,
1.418     albertel 2557:                                                      undef,$feedurl,undef,
1.386     raeburn  2558:                                                      undef,undef,$showsymb,
                   2559:                                                      $restitle);
1.574     bisitz   2560: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2561: 				$msgstatus.'<br />');
1.44      ng       2562: 	    }
1.257     albertel 2563: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2564: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2565: 		foreach my $collabstr (@collabstrs) {
                   2566: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2567: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2568: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2569: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2570: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2571: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2572: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2573: 			    next;
1.418     albertel 2574: 			} elsif ($message ne '') {
                   2575: 			    my ($baseurl,$showsymb) = 
                   2576: 				&get_feedurl_and_symb($symb,$collaborator,
                   2577: 						      $udom);
                   2578: 			    if ($env{'form.withgrades'.$ctr}) {
                   2579: 				$messagetail = " for <a href=\"".
1.605     www      2580:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2581: 			    }
1.418     albertel 2582: 			    $msgstatus = 
                   2583: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2584: 			}
1.44      ng       2585: 		    }
                   2586: 		}
                   2587: 	    }
                   2588: 	    $ctr++;
                   2589: 	}
                   2590:     }
                   2591: 
1.624     www      2592: #    if ($env{'form.handgrade'} eq 'yes') {
                   2593:     if (1) {
1.119     ng       2594: 	# Keywords sorted in alphabatical order
1.257     albertel 2595: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2596: 	my %keyhash = ();
1.257     albertel 2597: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2598: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2599: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2600: 	$env{'form.keywords'} = join(' ',@keywords);
                   2601: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2602: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2603: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2604: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2605: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2606: 
                   2607: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2608: 	# New messages are saved in env for the next student.
1.119     ng       2609: 	# All messages are saved in nohist_handgrade.db
                   2610: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2611: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2612: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2613: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2614: 		$idx++;
                   2615: 	    }
                   2616: 	    $ctr++;
1.41      ng       2617: 	}
1.119     ng       2618: 	$ctr = 0;
                   2619: 	while ($ctr < $ngrade) {
1.257     albertel 2620: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2621: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2622: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2623: 		$idx++;
                   2624: 	    }
                   2625: 	    $ctr++;
1.41      ng       2626: 	}
1.257     albertel 2627: 	$env{'form.savemsgN'} = --$idx;
                   2628: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2629: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2630: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2631:     }
1.44      ng       2632:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2633:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2634:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2635: 	my ($ctr,$total) = (0,0);
                   2636: 	while ($ctr < $ngrade) {
1.257     albertel 2637: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2638: 	    $ctr++;
                   2639: 	}
1.257     albertel 2640: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2641: 	$ctr = 0;
                   2642: 	while ($ctr < $total) {
1.257     albertel 2643: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2644: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2645: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2646: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2647: 	    $ctr++;
                   2648: 	}
                   2649: 	return '';
                   2650:     }
1.36      ng       2651: 
1.44      ng       2652:     # Get the next/previous one or group of students
1.257     albertel 2653:     my $firststu = $env{'form.unamedom0'};
                   2654:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2655:     my $ctr = 2;
1.41      ng       2656:     while ($laststu eq '') {
1.257     albertel 2657: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2658: 	$ctr++;
                   2659: 	$laststu = $firststu if ($ctr > $ngrade);
                   2660:     }
1.44      ng       2661: 
1.41      ng       2662:     my (@parsedlist,@nextlist);
                   2663:     my ($nextflg) = 0;
1.524     raeburn  2664:     foreach my $item (sort 
1.294     albertel 2665: 	     {
                   2666: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2667: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2668: 		 }
                   2669: 		 return $a cmp $b;
                   2670: 	     } (keys(%$fullname))) {
1.605     www      2671: # FIXME: this is fishy, looks like the button label
1.41      ng       2672: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2673: 	    push(@parsedlist,$item);
1.41      ng       2674: 	}
1.524     raeburn  2675: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2676: 	if ($button eq 'Previous') {
1.524     raeburn  2677: 	    last if ($item eq $firststu);
                   2678: 	    push(@parsedlist,$item);
1.41      ng       2679: 	}
                   2680:     }
                   2681:     $ctr = 0;
1.605     www      2682: # FIXME: this is fishy, looks like the button label
1.41      ng       2683:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2684:     my $res_error;
                   2685:     my ($partlist) = &response_type($symb,\$res_error);
                   2686:     if ($res_error) {
                   2687:         $request->print(&navmap_errormsg());
                   2688:         return;
                   2689:     }
1.41      ng       2690:     foreach my $student (@parsedlist) {
1.257     albertel 2691: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2692: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2693: 	
                   2694: 	if ($submitonly eq 'queued') {
                   2695: 	    my %queue_status = 
                   2696: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2697: 							$udom,$uname);
                   2698: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2699: 	}
                   2700: 
1.156     albertel 2701: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2702: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2703: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2704: 	    my $submitted = 0;
1.248     albertel 2705: 	    my $ungraded = 0;
                   2706: 	    my $incorrect = 0;
1.524     raeburn  2707: 	    foreach my $item (keys(%status)) {
                   2708: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2709: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2710: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2711: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2712: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2713: 		    $submitted = 0;
                   2714: 		}
1.41      ng       2715: 	    }
1.156     albertel 2716: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2717: 				     $submitonly eq 'incorrect' ||
                   2718: 				     $submitonly eq 'graded'));
1.248     albertel 2719: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2720: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2721: 	}
1.524     raeburn  2722: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2723: 	last if ($ctr == $ntstu);
1.41      ng       2724: 	$ctr++;
                   2725:     }
1.36      ng       2726: 
1.41      ng       2727:     $ctr = 0;
                   2728:     my $total = scalar(@nextlist)-1;
1.39      ng       2729: 
1.524     raeburn  2730:     foreach (sort(@nextlist)) {
1.41      ng       2731: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2732: 	$env{'form.student'}  = $uname;
                   2733: 	$env{'form.userdom'}  = $udom;
                   2734: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2735: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2736: 	$ctr++;
                   2737:     }
                   2738:     if ($total < 0) {
1.653     raeburn  2739: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2740: 	$request->print($the_end);
                   2741:     }
                   2742:     return '';
1.38      ng       2743: }
1.36      ng       2744: 
1.44      ng       2745: #---- Save the score and award for each student, if changed
1.38      ng       2746: sub saveHandGrade {
1.324     albertel 2747:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2748:     my @version_parts;
1.104     albertel 2749:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2750: 					   $env{'request.course.id'});
1.104     albertel 2751:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2752:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2753:     my @parts_graded;
1.77      ng       2754:     my %newrecord  = ();
                   2755:     my ($pts,$wgt) = ('','');
1.269     raeburn  2756:     my %aggregate = ();
                   2757:     my $aggregateflag = 0;
1.301     albertel 2758:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2759:     foreach my $new_part (@parts) {
1.337     banghart 2760: 	#collaborator ($submi may vary for different parts
1.259     banghart 2761: 	if ($submitter && $new_part ne $part) { next; }
                   2762: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2763: 	if ($dropMenu eq 'excused') {
1.259     banghart 2764: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2765: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2766: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2767: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2768: 		}
1.364     banghart 2769: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2770: 	    }
1.125     ng       2771: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2772: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2773: 	    foreach my $key (keys(%record)) {
1.259     banghart 2774: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2775: 	    }
1.259     banghart 2776: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2777: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2778:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2779: 
                   2780:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2781: 					       [$new_part]);
                   2782:             my $aggtries =$totaltries;
1.269     raeburn  2783:             if ($last_resets{$new_part}) {
1.270     albertel 2784:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2785: 					   $new_part);
1.269     raeburn  2786:             }
1.270     albertel 2787: 
                   2788:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2789:             if ($aggtries > 0) {
1.327     albertel 2790:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2791:                 $aggregateflag = 1;
                   2792:             }
1.125     ng       2793: 	} elsif ($dropMenu eq '') {
1.259     banghart 2794: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2795: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2796: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2797: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2798: 		next;
                   2799: 	    }
1.259     banghart 2800: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2801: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2802: 	    my $partial= $pts/$wgt;
1.259     banghart 2803: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2804: 		#do not update score for part if not changed.
1.346     banghart 2805:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2806: 		next;
1.251     banghart 2807: 	    } else {
1.524     raeburn  2808: 	        push(@parts_graded,$new_part);
1.153     albertel 2809: 	    }
1.259     banghart 2810: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2811: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2812: 	    }
1.259     banghart 2813: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2814: 	    if ($partial == 0) {
1.153     albertel 2815: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2816: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2817: 		}
1.41      ng       2818: 	    } else {
1.153     albertel 2819: 		if ($record{$reckey} ne 'correct_by_override') {
                   2820: 		    $newrecord{$reckey} = 'correct_by_override';
                   2821: 		}
                   2822: 	    }	    
                   2823: 	    if ($submitter && 
1.259     banghart 2824: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2825: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2826: 	    }
1.259     banghart 2827: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2828: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2829: 	}
1.259     banghart 2830: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2831: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2832: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2833: 	        $dropMenu eq 'reset status')
                   2834: 	   {
1.524     raeburn  2835: 	    push(@version_parts,$new_part);
1.259     banghart 2836: 	}
1.41      ng       2837:     }
1.301     albertel 2838:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2839:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2840: 
1.344     albertel 2841:     if (%newrecord) {
                   2842:         if (@version_parts) {
1.364     banghart 2843:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2844:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2845: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2846: 	    foreach my $new_part (@version_parts) {
                   2847: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2848: 				$new_part,\%newrecord);
                   2849: 	    }
1.259     banghart 2850:         }
1.44      ng       2851: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2852: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2853: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2854: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2855:     }
1.269     raeburn  2856:     if ($aggregateflag) {
                   2857:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2858: 			      $cdom,$cnum);
1.269     raeburn  2859:     }
1.301     albertel 2860:     return ('',$pts,$wgt);
1.36      ng       2861: }
1.322     albertel 2862: 
1.380     albertel 2863: sub check_and_remove_from_queue {
                   2864:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2865:     my @ungraded_parts;
                   2866:     foreach my $part (@{$parts}) {
                   2867: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2868: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2869: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2870: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2871: 		) {
                   2872: 	    push(@ungraded_parts, $part);
                   2873: 	}
                   2874:     }
                   2875:     if ( !@ungraded_parts ) {
                   2876: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2877: 					       $cnum,$domain,$stuname);
                   2878:     }
                   2879: }
                   2880: 
1.337     banghart 2881: sub handback_files {
                   2882:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2883:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2884:     my $res_error;
                   2885:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2886:     if ($res_error) {
                   2887:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2888:         return;
                   2889:     }
1.654     raeburn  2890:     my @handedback;
                   2891:     my $file_msg;
1.375     albertel 2892:     my @part_response_id = &flatten_responseType($responseType);
                   2893:     foreach my $part_response_id (@part_response_id) {
                   2894:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2895: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  2896:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   2897:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   2898:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   2899:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   2900:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 2901:                     my ($directory,$answer_file) = 
1.654     raeburn  2902:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 2903:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2904: 		        &file_name_version_ext($answer_file);
1.355     banghart 2905: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2906:                     my $getpropath = 1;
                   2907: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2908: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2909:                     # fix file name
                   2910:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2911:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  2912:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 2913:             	                                $save_file_name);
1.337     banghart 2914:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2915:                         $request->print('<br /><span class="LC_error">'.
                   2916:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  2917:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  2918:                                         '</span>');
1.356     banghart 2919:                     } else {
1.360     banghart 2920:                         # mark the file as read only
1.654     raeburn  2921:                         push(@handedback,$save_file_name);
1.367     albertel 2922: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2923: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2924: 			}
                   2925:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  2926: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 2927:                     }
1.654     raeburn  2928:                     $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 2929:                 }
                   2930:             }
                   2931:         }
1.654     raeburn  2932:     }
                   2933:     if (@handedback > 0) {
                   2934:         $request->print('<br />');
                   2935:         my @what = ($symb,$env{'request.course.id'},'handback');
                   2936:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   2937:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   2938:         my ($subject,$message);
                   2939:         if (scalar(@handedback) == 1) {
                   2940:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   2941:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   2942:         } else {
                   2943:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   2944:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   2945:         }
                   2946:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   2947:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   2948:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   2949:         my ($feedurl,$showsymb) =
                   2950:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   2951:         my $restitle = &Apache::lonnet::gettitle($symb);
                   2952:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   2953:         my $msgstatus =
                   2954:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   2955:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   2956:                  $restitle);
                   2957:         if ($msgstatus) {
                   2958:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   2959:         }
                   2960:     }
1.338     banghart 2961:     return;
1.337     banghart 2962: }
                   2963: 
1.418     albertel 2964: sub get_feedurl_and_symb {
                   2965:     my ($symb,$uname,$udom) = @_;
                   2966:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2967:     $url = &Apache::lonnet::clutter($url);
                   2968:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2969: 					$symb,$udom,$uname);
                   2970:     if ($encrypturl =~ /^yes$/i) {
                   2971: 	&Apache::lonenc::encrypted(\$url,1);
                   2972: 	&Apache::lonenc::encrypted(\$symb,1);
                   2973:     }
                   2974:     return ($url,$symb);
                   2975: }
                   2976: 
1.313     banghart 2977: sub get_submitted_files {
                   2978:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2979:     my @files;
                   2980:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2981:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2982:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2983:     	    push(@files,$file_url.$file);
                   2984:         }
                   2985:     }
                   2986:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2987:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2988:     }
                   2989:     return (\@files);
                   2990: }
1.322     albertel 2991: 
1.269     raeburn  2992: # ----------- Provides number of tries since last reset.
                   2993: sub get_num_tries {
                   2994:     my ($record,$last_reset,$part) = @_;
                   2995:     my $timestamp = '';
                   2996:     my $num_tries = 0;
                   2997:     if ($$record{'version'}) {
                   2998:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2999:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3000:                 $timestamp = $$record{$version.':timestamp'};
                   3001:                 if ($timestamp > $last_reset) {
                   3002:                     $num_tries ++;
                   3003:                 } else {
                   3004:                     last;
                   3005:                 }
                   3006:             }
                   3007:         }
                   3008:     }
                   3009:     return $num_tries;
                   3010: }
                   3011: 
                   3012: # ----------- Determine decrements required in aggregate totals 
                   3013: sub decrement_aggs {
                   3014:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3015:     my %decrement = (
                   3016:                         attempts => 0,
                   3017:                         users => 0,
                   3018:                         correct => 0
                   3019:                     );
                   3020:     $decrement{'attempts'} = $aggtries;
                   3021:     if ($solvedstatus =~ /^correct/) {
                   3022:         $decrement{'correct'} = 1;
                   3023:     }
                   3024:     if ($aggtries == $totaltries) {
                   3025:         $decrement{'users'} = 1;
                   3026:     }
1.524     raeburn  3027:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3028:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3029:     }
                   3030:     return;
                   3031: }
                   3032: 
                   3033: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3034: sub get_last_resets {
1.270     albertel 3035:     my ($symb,$courseid,$partids) =@_;
                   3036:     my %last_resets;
1.269     raeburn  3037:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3038:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3039:     my @keys;
                   3040:     foreach my $part (@{$partids}) {
                   3041: 	push(@keys,"$symb\0$part\0resettime");
                   3042:     }
                   3043:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3044: 				     $cdom,$cname);
                   3045:     foreach my $part (@{$partids}) {
                   3046: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3047:     }
1.270     albertel 3048:     return %last_resets;
1.269     raeburn  3049: }
                   3050: 
1.251     banghart 3051: # ----------- Handles creating versions for portfolio files as answers
                   3052: sub version_portfiles {
1.343     banghart 3053:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3054:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3055:     my @returned_keys;
1.255     banghart 3056:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3057:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3058:     foreach my $key (keys(%$record)) {
1.259     banghart 3059:         my $new_portfiles;
1.263     banghart 3060:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3061:             my @versioned_portfiles;
1.367     albertel 3062:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3063:             foreach my $file (@portfiles) {
1.306     banghart 3064:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3065:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3066: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3067: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3068:                 my $getpropath = 1;    
                   3069:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3070:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3071:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3072:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3073:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3074:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3075:                         [$directory.$new_answer],
1.306     banghart 3076:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3077:                 }
1.252     banghart 3078:             }
1.343     banghart 3079:             $$record{$key} = join(',',@versioned_portfiles);
                   3080:             push(@returned_keys,$key);
1.251     banghart 3081:         }
                   3082:     } 
1.343     banghart 3083:     return (@returned_keys);   
1.305     banghart 3084: }
                   3085: 
1.307     banghart 3086: sub get_next_version {
1.341     banghart 3087:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3088:     my $version;
                   3089:     foreach my $row (@$dir_list) {
                   3090:         my ($file) = split(/\&/,$row,2);
                   3091:         my ($file_name,$file_version,$file_ext) =
                   3092: 	    &file_name_version_ext($file);
                   3093:         if (($file_name eq $answer_name) && 
                   3094: 	    ($file_ext eq $answer_ext)) {
                   3095:                 # gets here if filename and extension match, regardless of version
                   3096:                 if ($file_version ne '') {
                   3097:                 # a versioned file is found  so save it for later
                   3098:                 if ($file_version > $version) {
                   3099: 		    $version = $file_version;
                   3100: 	        }
                   3101:             }
                   3102:         }
                   3103:     } 
                   3104:     $version ++;
                   3105:     return($version);
                   3106: }
                   3107: 
1.305     banghart 3108: sub version_selected_portfile {
1.306     banghart 3109:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3110:     my ($answer_name,$answer_ver,$answer_ext) =
                   3111:         &file_name_version_ext($file_name);
                   3112:     my $new_answer;
                   3113:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3114:     if($env{'form.copy'} eq '-1') {
                   3115:         $new_answer = 'problem getting file';
                   3116:     } else {
                   3117:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3118:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3119:                             $stu_name,$domain,'copy',
                   3120: 		        '/portfolio'.$directory.$new_answer);
                   3121:     }    
                   3122:     return ($new_answer);
1.251     banghart 3123: }
                   3124: 
1.304     albertel 3125: sub file_name_version_ext {
                   3126:     my ($file)=@_;
                   3127:     my @file_parts = split(/\./, $file);
                   3128:     my ($name,$version,$ext);
                   3129:     if (@file_parts > 1) {
                   3130: 	$ext=pop(@file_parts);
                   3131: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3132: 	    $version=pop(@file_parts);
                   3133: 	}
                   3134: 	$name=join('.',@file_parts);
                   3135:     } else {
                   3136: 	$name=join('.',@file_parts);
                   3137:     }
                   3138:     return($name,$version,$ext);
                   3139: }
                   3140: 
1.44      ng       3141: #--------------------------------------------------------------------------------------
                   3142: #
                   3143: #-------------------------- Next few routines handles grading by section or whole class
                   3144: #
                   3145: #--- Javascript to handle grading by section or whole class
1.42      ng       3146: sub viewgrades_js {
                   3147:     my ($request) = shift;
                   3148: 
1.539     riegler  3149:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3150:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3151:    function writePoint(partid,weight,point) {
1.125     ng       3152: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3153: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3154: 	if (point == "textval") {
1.125     ng       3155: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3156: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3157: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3158: 		var resetbox = false;
                   3159: 		for (var i=0; i<radioButton.length; i++) {
                   3160: 		    if (radioButton[i].checked) {
                   3161: 			textbox.value = i;
                   3162: 			resetbox = true;
                   3163: 		    }
                   3164: 		}
                   3165: 		if (!resetbox) {
                   3166: 		    textbox.value = "";
                   3167: 		}
                   3168: 		return;
                   3169: 	    }
1.109     matthew  3170: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3171: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3172: 				   ") greater than the weight for the part. Accept?");
                   3173: 		if (resp == false) {
                   3174: 		    textbox.value = "";
                   3175: 		    return;
                   3176: 		}
                   3177: 	    }
1.42      ng       3178: 	    for (var i=0; i<radioButton.length; i++) {
                   3179: 		radioButton[i].checked=false;
1.109     matthew  3180: 		if (parseFloat(point) == i) {
1.42      ng       3181: 		    radioButton[i].checked=true;
                   3182: 		}
                   3183: 	    }
1.41      ng       3184: 
1.42      ng       3185: 	} else {
1.125     ng       3186: 	    textbox.value = parseFloat(point);
1.42      ng       3187: 	}
1.41      ng       3188: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3189: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3190: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3191: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3192: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3193: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3194: 	    if (saveval != "correct") {
                   3195: 		scorename.value = point;
1.43      ng       3196: 		if (selname[0].selected != true) {
                   3197: 		    selname[0].selected = true;
                   3198: 		}
1.42      ng       3199: 	    }
                   3200: 	}
1.125     ng       3201: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3202:     }
                   3203: 
                   3204:     function writeRadText(partid,weight) {
1.125     ng       3205: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3206: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3207:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3208: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3209: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3210: 	    for (var i=0; i<radioButton.length; i++) {
                   3211: 		radioButton[i].checked=false;
                   3212: 
                   3213: 	    }
                   3214: 	    textbox.value = "";
                   3215: 
                   3216: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3217: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3218: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3219: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3220: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3221: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3222: 		if ((saveval != "correct") || override) {
1.42      ng       3223: 		    scorename.value = "";
1.125     ng       3224: 		    if (selval[1].selected) {
                   3225: 			selname[1].selected = true;
                   3226: 		    } else {
                   3227: 			selname[2].selected = true;
                   3228: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3229: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3230: 		    }
1.42      ng       3231: 		}
                   3232: 	    }
1.43      ng       3233: 	} else {
                   3234: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3235: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3236: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3237: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3238: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3239: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3240: 		if ((saveval != "correct") || override) {
1.125     ng       3241: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3242: 		    selname[0].selected = true;
                   3243: 		}
                   3244: 	    }
                   3245: 	}	    
1.42      ng       3246:     }
                   3247: 
                   3248:     function changeSelect(partid,user) {
1.125     ng       3249: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3250: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3251: 	var point  = textbox.value;
1.125     ng       3252: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3253: 
1.109     matthew  3254: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3255: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3256: 	    textbox.value = "";
                   3257: 	    return;
                   3258: 	}
1.109     matthew  3259: 	if (parseFloat(point) > parseFloat(weight)) {
                   3260: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3261: 			       ") greater than the weight of the part. Accept?");
                   3262: 	    if (resp == false) {
                   3263: 		textbox.value = "";
                   3264: 		return;
                   3265: 	    }
                   3266: 	}
1.42      ng       3267: 	selval[0].selected = true;
                   3268:     }
                   3269: 
                   3270:     function changeOneScore(partid,user) {
1.125     ng       3271: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3272: 	if (selval[1].selected || selval[2].selected) {
                   3273: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3274: 	    if (selval[2].selected) {
                   3275: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3276: 	    }
1.269     raeburn  3277:         }
1.42      ng       3278:     }
                   3279: 
                   3280:     function resetEntry(numpart) {
                   3281: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3282: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3283: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3284: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3285: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3286: 	    for (var i=0; i<radioButton.length; i++) {
                   3287: 		radioButton[i].checked=false;
                   3288: 
                   3289: 	    }
                   3290: 	    textbox.value = "";
                   3291: 	    selval[0].selected = true;
                   3292: 
                   3293: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3294: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3295: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3296: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3297: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3298: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3299: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3300: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3301: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3302: 		if (saveselval == "excused") {
1.43      ng       3303: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3304: 		} else {
1.43      ng       3305: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3306: 		}
                   3307: 	    }
1.41      ng       3308: 	}
1.42      ng       3309:     }
                   3310: 
1.41      ng       3311: VIEWJAVASCRIPT
1.42      ng       3312: }
                   3313: 
1.44      ng       3314: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3315: sub viewgrades {
1.608     www      3316:     my ($request,$symb) = @_;
1.42      ng       3317:     &viewgrades_js($request);
1.41      ng       3318: 
1.168     albertel 3319:     #need to make sure we have the correct data for later EXT calls, 
                   3320:     #thus invalidate the cache
                   3321:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3322:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3323:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3324:     &Apache::lonnet::clear_EXT_cache_status();
                   3325: 
1.398     albertel 3326:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3327: 
                   3328:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3329:     $result.=&jscriptNform($symb);
1.41      ng       3330: 
1.44      ng       3331:     #beginning of class grading form
1.442     banghart 3332:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3333:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3334: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3335: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3336: 	&build_section_inputs().
1.442     banghart 3337: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3338: 
1.560     raeburn  3339:     my ($common_header,$specific_header);
1.257     albertel 3340:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3341: 	$common_header = &mt('Assign Common Grade to Class');
                   3342:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3343:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3344:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3345: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3346:     } else {
1.560     raeburn  3347:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3348:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3349: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3350:     }
1.560     raeburn  3351:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3352:     #radio buttons/text box for assigning points for a section or class.
                   3353:     #handles different parts of a problem
1.582     raeburn  3354:     my $res_error;
                   3355:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3356:     if ($res_error) {
                   3357:         return &navmap_errormsg();
                   3358:     }
1.42      ng       3359:     my %weight = ();
                   3360:     my $ctsparts = 0;
1.45      ng       3361:     my %seen = ();
1.375     albertel 3362:     my @part_response_id = &flatten_responseType($responseType);
                   3363:     foreach my $part_response_id (@part_response_id) {
                   3364:     	my ($partid,$respid) = @{ $part_response_id };
                   3365: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3366: 	next if $seen{$partid};
                   3367: 	$seen{$partid}++;
1.375     albertel 3368: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3369: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3370: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3371: 
1.324     albertel 3372: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3373: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3374: 	my $ctr = 0;
1.42      ng       3375: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3376: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3377: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3378: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3379: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3380: 	    $ctr++;
                   3381: 	}
1.485     albertel 3382: 	$radio.='</tr></table>';
                   3383: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3384: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3385: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3386: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3387: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3388: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3389: 		$weight{$partid}.')"> '.
1.401     albertel 3390: 	    '<option selected="selected"> </option>'.
1.485     albertel 3391: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3392: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3393: 	    '</select></td>'.
                   3394:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3395: 	$line.='<input type="hidden" name="partid_'.
                   3396: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3397: 	$line.='<input type="hidden" name="weight_'.
                   3398: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3399: 
                   3400: 	$result.=
                   3401: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3402: 	    '<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 3403: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3404: 	$ctsparts++;
1.41      ng       3405:     }
1.474     albertel 3406:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3407: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3408:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3409: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3410: 
1.44      ng       3411:     #table listing all the students in a section/class
                   3412:     #header of table
1.560     raeburn  3413:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3414:               &Apache::loncommon::start_data_table().
                   3415: 	      &Apache::loncommon::start_data_table_header_row().
                   3416: 	      '<th>'.&mt('No.').'</th>'.
                   3417: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3418:     my $partserror;
                   3419:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3420:     if ($partserror) {
                   3421:         return &navmap_errormsg();
                   3422:     }
1.324     albertel 3423:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3424:     my @partids = ();
1.41      ng       3425:     foreach my $part (@parts) {
                   3426: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3427:         my $narrowtext = &mt('Tries');
                   3428: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3429: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3430: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3431:         push(@partids,$partid);
1.628     www      3432: #
                   3433: # FIXME: Looks like $display looks at English text
                   3434: #
1.324     albertel 3435: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3436: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3437: 	    $result.='<th>'.
                   3438: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3439: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3440: 	    next;
1.485     albertel 3441: 	    
1.207     albertel 3442: 	} else {
1.485     albertel 3443: 	    if ($display =~ /Problem Status/) {
                   3444: 		my $grade_status_mt = &mt('Grade Status');
                   3445: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3446: 	    }
                   3447: 	    my $part_mt = &mt('Part:');
                   3448: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3449: 	}
1.485     albertel 3450: 
1.474     albertel 3451: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3452:     }
1.474     albertel 3453:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3454: 
1.270     albertel 3455:     my %last_resets = 
                   3456: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3457: 
1.41      ng       3458:     #get info for each student
1.44      ng       3459:     #list all the students - with points and grade status
1.257     albertel 3460:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3461:     my $ctr = 0;
1.294     albertel 3462:     foreach (sort 
                   3463: 	     {
                   3464: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3465: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3466: 		 }
                   3467: 		 return $a cmp $b;
                   3468: 	     } (keys(%$fullname))) {
1.126     ng       3469: 	$ctr++;
1.324     albertel 3470: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3471: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3472:     }
1.474     albertel 3473:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3474:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3475:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3476: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3477:     if (scalar(%$fullname) eq 0) {
                   3478: 	my $colspan=3+scalar(@parts);
1.433     banghart 3479: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3480:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3481: 	$result='<span class="LC_warning">'.
1.485     albertel 3482: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3483: 	        $section_display, $stu_status).
1.433     banghart 3484: 	    '</span>';
1.96      albertel 3485:     }
1.41      ng       3486:     return $result;
                   3487: }
                   3488: 
1.44      ng       3489: #--- call by previous routine to display each student
1.41      ng       3490: sub viewstudentgrade {
1.324     albertel 3491:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3492:     my ($uname,$udom) = split(/:/,$student);
                   3493:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3494:     my %aggregates = (); 
1.474     albertel 3495:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3496: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3497: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3498: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3499: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3500: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3501:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3502:     foreach my $apart (@$parts) {
                   3503: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3504: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3505:         $result.='<td align="center">';
1.269     raeburn  3506:         my ($aggtries,$totaltries);
                   3507:         unless (exists($aggregates{$part})) {
1.270     albertel 3508: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3509: 
                   3510: 	    $aggtries = $totaltries;
1.269     raeburn  3511:             if ($$last_resets{$part}) {  
1.270     albertel 3512:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3513: 					   $part);
                   3514:             }
1.269     raeburn  3515:             $result.='<input type="hidden" name="'.
                   3516:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3517:             $result.='<input type="hidden" name="'.
                   3518:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3519:             $aggregates{$part} = 1;
                   3520:         }
1.41      ng       3521: 	if ($type eq 'awarded') {
1.320     albertel 3522: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3523: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3524: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3525: 	    $result.='<input type="text" name="'.
1.89      albertel 3526: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3527:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3528: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3529: 	} elsif ($type eq 'solved') {
                   3530: 	    my ($status,$foo)=split(/_/,$score,2);
                   3531: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3532: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3533: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3534: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3535: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3536:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3537: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3538: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3539: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3540: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3541: 	} else {
                   3542: 	    $result.='<input type="hidden" name="'.
                   3543: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3544: 		    "\n";
1.233     albertel 3545: 	    $result.='<input type="text" name="'.
1.122     ng       3546: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3547: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3548: 	}
                   3549:     }
1.474     albertel 3550:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3551:     return $result;
1.38      ng       3552: }
                   3553: 
1.44      ng       3554: #--- change scores for all the students in a section/class
                   3555: #    record does not get update if unchanged
1.38      ng       3556: sub editgrades {
1.608     www      3557:     my ($request,$symb) = @_;
1.41      ng       3558: 
1.433     banghart 3559:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3560:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3561:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3562: 
1.477     albertel 3563:     my $result= &Apache::loncommon::start_data_table().
                   3564: 	&Apache::loncommon::start_data_table_header_row().
                   3565: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3566: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3567:     my %scoreptr = (
                   3568: 		    'correct'  =>'correct_by_override',
                   3569: 		    'incorrect'=>'incorrect_by_override',
                   3570: 		    'excused'  =>'excused',
                   3571: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3572:                     'credited' =>'credit_attempted',
1.43      ng       3573: 		    'nothing'  => '',
                   3574: 		    );
1.257     albertel 3575:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3576: 
1.44      ng       3577:     my (@partid);
                   3578:     my %weight = ();
1.54      albertel 3579:     my %columns = ();
1.44      ng       3580:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3581: 
1.582     raeburn  3582:     my $partserror;
                   3583:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3584:     if ($partserror) {
                   3585:         return &navmap_errormsg();
                   3586:     }
1.54      albertel 3587:     my $header;
1.257     albertel 3588:     while ($ctr < $env{'form.totalparts'}) {
                   3589: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3590: 	push(@partid,$partid);
1.257     albertel 3591: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3592: 	$ctr++;
1.54      albertel 3593:     }
1.324     albertel 3594:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3595:     foreach my $partid (@partid) {
1.478     albertel 3596: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3597: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3598: 	$columns{$partid}=2;
                   3599: 	foreach my $stores (@parts) {
                   3600: 	    my ($part,$type) = &split_part_type($stores);
                   3601: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3602: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3603: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3604: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3605:             my $narrowtext = &mt('Tries');
                   3606: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3607: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3608: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3609: 	    $columns{$partid}+=2;
                   3610: 	}
                   3611:     }
                   3612:     foreach my $partid (@partid) {
1.324     albertel 3613: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3614: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3615: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3616: 	    '</th>';
1.54      albertel 3617: 
1.44      ng       3618:     }
1.477     albertel 3619:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3620: 	&Apache::loncommon::start_data_table_header_row().
                   3621: 	$header.
                   3622: 	&Apache::loncommon::end_data_table_header_row();
                   3623:     my @noupdate;
1.126     ng       3624:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3625:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3626: 	my $line;
1.257     albertel 3627: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3628: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3629: 	my %newrecord;
                   3630: 	my $updateflag = 0;
1.281     albertel 3631: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3632: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3633: 	if (!&canmodify($usec)) {
1.126     ng       3634: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3635: 	    push(@noupdate,
1.478     albertel 3636: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3637: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3638: 	    next;
                   3639: 	}
1.269     raeburn  3640:         my %aggregate = ();
                   3641:         my $aggregateflag = 0;
1.281     albertel 3642: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3643: 	foreach (@partid) {
1.257     albertel 3644: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3645: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3646: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3647: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3648: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3649: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3650: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3651: 	    my $score;
                   3652: 	    if ($partial eq '') {
1.257     albertel 3653: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3654: 	    } elsif ($partial > 0) {
                   3655: 		$score = 'correct_by_override';
                   3656: 	    } elsif ($partial == 0) {
                   3657: 		$score = 'incorrect_by_override';
                   3658: 	    }
1.257     albertel 3659: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3660: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3661: 
1.292     albertel 3662: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3663: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3664: 	    if ($dropMenu eq 'reset status' &&
                   3665: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3666: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3667: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3668: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3669: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3670: 		$updateflag = 1;
1.269     raeburn  3671:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3672:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3673:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3674:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3675:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3676:                     $aggregateflag = 1;
                   3677:                 }
1.139     albertel 3678: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3679: 		$updateflag = 1;
                   3680: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3681: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3682: 		$rec_update++;
1.125     ng       3683: 	    }
                   3684: 
1.93      albertel 3685: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3686: 		'<td align="center">'.$awarded.
                   3687: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3688: 
1.54      albertel 3689: 
                   3690: 	    my $partid=$_;
                   3691: 	    foreach my $stores (@parts) {
                   3692: 		my ($part,$type) = &split_part_type($stores);
                   3693: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3694: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3695: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3696: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3697: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3698: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3699: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3700: 		    $updateflag=1;
                   3701: 		}
1.93      albertel 3702: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3703: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3704: 	    }
1.44      ng       3705: 	}
1.477     albertel 3706: 	$line.="\n";
1.301     albertel 3707: 
                   3708: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3709: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3710: 
1.44      ng       3711: 	if ($updateflag) {
                   3712: 	    $count++;
1.257     albertel 3713: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3714: 				    $udom,$uname);
1.301     albertel 3715: 
                   3716: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3717: 					      $cnum,$udom,$uname)) {
                   3718: 		# need to figure out if should be in queue.
                   3719: 		my %record =  
                   3720: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3721: 					     $udom,$uname);
                   3722: 		my $all_graded = 1;
                   3723: 		my $none_graded = 1;
                   3724: 		foreach my $part (@parts) {
                   3725: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3726: 			$all_graded = 0;
                   3727: 		    } else {
                   3728: 			$none_graded = 0;
                   3729: 		    }
                   3730: 		}
                   3731: 
                   3732: 		if ($all_graded || $none_graded) {
                   3733: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3734: 							   $symb,$cdom,$cnum,
                   3735: 							   $udom,$uname);
                   3736: 		}
                   3737: 	    }
                   3738: 
1.477     albertel 3739: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3740: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3741: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3742: 	    $updateCtr++;
1.93      albertel 3743: 	} else {
1.477     albertel 3744: 	    push(@noupdate,
                   3745: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3746: 	    $noupdateCtr++;
1.44      ng       3747: 	}
1.269     raeburn  3748:         if ($aggregateflag) {
                   3749:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3750: 				  $cdom,$cnum);
1.269     raeburn  3751:         }
1.93      albertel 3752:     }
1.477     albertel 3753:     if (@noupdate) {
1.126     ng       3754: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3755: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3756: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3757: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3758: 	    &mt('No Changes Occurred For the Students Below').
                   3759: 	    '</td>'.
1.477     albertel 3760: 	    &Apache::loncommon::end_data_table_row();
                   3761: 	foreach my $line (@noupdate) {
                   3762: 	    $result.=
                   3763: 		&Apache::loncommon::start_data_table_row().
                   3764: 		$line.
                   3765: 		&Apache::loncommon::end_data_table_row();
                   3766: 	}
1.44      ng       3767:     }
1.614     www      3768:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3769:     my $msg = '<p><b>'.
                   3770: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3771: 	    $rec_update,$count).'</b><br />'.
                   3772: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3773: 	'</b></p>';
1.44      ng       3774:     return $title.$msg.$result;
1.5       albertel 3775: }
1.54      albertel 3776: 
                   3777: sub split_part_type {
                   3778:     my ($partstr) = @_;
                   3779:     my ($temp,@allparts)=split(/_/,$partstr);
                   3780:     my $type=pop(@allparts);
1.439     albertel 3781:     my $part=join('_',@allparts);
1.54      albertel 3782:     return ($part,$type);
                   3783: }
                   3784: 
1.44      ng       3785: #------------- end of section for handling grading by section/class ---------
                   3786: #
                   3787: #----------------------------------------------------------------------------
                   3788: 
1.5       albertel 3789: 
1.44      ng       3790: #----------------------------------------------------------------------------
                   3791: #
                   3792: #-------------------------- Next few routines handles grading by csv upload
                   3793: #
                   3794: #--- Javascript to handle csv upload
1.27      albertel 3795: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3796:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3797:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3798:   return(<<ENDPICK);
                   3799:   function verify(vf) {
                   3800:     var foundsomething=0;
                   3801:     var founduname=0;
1.243     albertel 3802:     var foundID=0;
1.27      albertel 3803:     for (i=0;i<=vf.nfields.value;i++) {
                   3804:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3805:       if (i==0 && tw!=0) { foundID=1; }
                   3806:       if (i==1 && tw!=0) { founduname=1; }
                   3807:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3808:     }
1.246     albertel 3809:     if (founduname==0 && foundID==0) {
                   3810: 	alert('$error1');
                   3811: 	return;
1.27      albertel 3812:     }
                   3813:     if (foundsomething==0) {
1.246     albertel 3814: 	alert('$error2');
                   3815: 	return;
1.27      albertel 3816:     }
                   3817:     vf.submit();
                   3818:   }
                   3819:   function flip(vf,tf) {
                   3820:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3821:     var i;
                   3822:     for (i=0;i<=vf.nfields.value;i++) {
                   3823:       //can not pick the same destination field for both name and domain
                   3824:       if (((i ==0)||(i ==1)) && 
                   3825:           ((tf==0)||(tf==1)) && 
                   3826:           (i!=tf) &&
                   3827:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3828:         eval('vf.f'+i+'.selectedIndex=0;')
                   3829:       }
                   3830:     }
                   3831:   }
                   3832: ENDPICK
                   3833: }
                   3834: 
                   3835: sub csvupload_javascript_forward_associate {
1.573     bisitz   3836:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3837:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3838:   return(<<ENDPICK);
                   3839:   function verify(vf) {
                   3840:     var foundsomething=0;
                   3841:     var founduname=0;
1.243     albertel 3842:     var foundID=0;
1.27      albertel 3843:     for (i=0;i<=vf.nfields.value;i++) {
                   3844:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3845:       if (tw==1) { foundID=1; }
                   3846:       if (tw==2) { founduname=1; }
                   3847:       if (tw>3) { foundsomething=1; }
1.27      albertel 3848:     }
1.246     albertel 3849:     if (founduname==0 && foundID==0) {
                   3850: 	alert('$error1');
                   3851: 	return;
1.27      albertel 3852:     }
                   3853:     if (foundsomething==0) {
1.246     albertel 3854: 	alert('$error2');
                   3855: 	return;
1.27      albertel 3856:     }
                   3857:     vf.submit();
                   3858:   }
                   3859:   function flip(vf,tf) {
                   3860:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3861:     var i;
                   3862:     //can not pick the same destination field twice
                   3863:     for (i=0;i<=vf.nfields.value;i++) {
                   3864:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3865:         eval('vf.f'+i+'.selectedIndex=0;')
                   3866:       }
                   3867:     }
                   3868:   }
                   3869: ENDPICK
                   3870: }
                   3871: 
1.26      albertel 3872: sub csvuploadmap_header {
1.324     albertel 3873:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3874:     my $javascript;
1.257     albertel 3875:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3876: 	$javascript=&csvupload_javascript_reverse_associate();
                   3877:     } else {
                   3878: 	$javascript=&csvupload_javascript_forward_associate();
                   3879:     }
1.45      ng       3880: 
1.418     albertel 3881:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3882:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3883:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3884:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3885:     my $reverse=&mt("Reverse Association");
1.41      ng       3886:     $request->print(<<ENDPICK);
1.632     www      3887: <br />
                   3888: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3889: <input type="hidden" name="associate"  value="" />
                   3890: <input type="hidden" name="phase"      value="three" />
                   3891: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3892: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3893: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3894: <input type="hidden" name="upfile_associate" 
1.257     albertel 3895:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3896: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3897: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3898: <hr />
                   3899: ENDPICK
1.597     wenzelju 3900:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3901:     return '';
1.26      albertel 3902: 
                   3903: }
                   3904: 
                   3905: sub csvupload_fields {
1.582     raeburn  3906:     my ($symb,$errorref) = @_;
                   3907:     my (@parts) = &getpartlist($symb,$errorref);
                   3908:     if (ref($errorref)) {
                   3909:         if ($$errorref) {
                   3910:             return;
                   3911:         }
                   3912:     }
                   3913: 
1.556     weissno  3914:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3915: 		['username','Student Username'],
                   3916: 		['domain','Student Domain']);
1.324     albertel 3917:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3918:     foreach my $part (sort(@parts)) {
                   3919: 	my @datum;
                   3920: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3921: 	my $name=$part;
                   3922: 	if  (!$display) { $display = $name; }
                   3923: 	@datum=($name,$display);
1.244     albertel 3924: 	if ($name=~/^stores_(.*)_awarded/) {
                   3925: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3926: 	}
1.41      ng       3927: 	push(@fields,\@datum);
                   3928:     }
                   3929:     return (@fields);
1.26      albertel 3930: }
                   3931: 
                   3932: sub csvuploadmap_footer {
1.41      ng       3933:     my ($request,$i,$keyfields) =@_;
                   3934:     $request->print(<<ENDPICK);
1.26      albertel 3935: </table>
                   3936: <input type="hidden" name="nfields" value="$i" />
                   3937: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3938: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3939: </form>
                   3940: ENDPICK
                   3941: }
                   3942: 
1.283     albertel 3943: sub checkforfile_js {
1.638     www      3944:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3945:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3946:     function checkUpload(formname) {
                   3947: 	if (formname.upfile.value == "") {
1.539     riegler  3948: 	    alert("$alertmsg");
1.86      ng       3949: 	    return false;
                   3950: 	}
                   3951: 	formname.submit();
                   3952:     }
                   3953: CSVFORMJS
1.283     albertel 3954:     return $result;
                   3955: }
                   3956: 
                   3957: sub upcsvScores_form {
1.608     www      3958:     my ($request,$symb) = @_;
1.283     albertel 3959:     if (!$symb) {return '';}
                   3960:     my $result=&checkforfile_js();
1.632     www      3961:     $result.=&Apache::loncommon::start_data_table().
                   3962:              &Apache::loncommon::start_data_table_header_row().
                   3963:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3964:              &Apache::loncommon::end_data_table_header_row().
                   3965:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3966:     my $upload=&mt("Upload Scores");
1.86      ng       3967:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3968:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3969:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3970:     $result.=<<ENDUPFORM;
1.106     albertel 3971: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3972: <input type="hidden" name="symb" value="$symb" />
                   3973: <input type="hidden" name="command" value="csvuploadmap" />
                   3974: $upfile_select
1.589     bisitz   3975: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3976: </form>
                   3977: ENDUPFORM
1.370     www      3978:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3979:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3980:              '</td>'.
                   3981:             &Apache::loncommon::end_data_table_row().
                   3982:             &Apache::loncommon::end_data_table();
1.86      ng       3983:     return $result;
                   3984: }
                   3985: 
                   3986: 
1.26      albertel 3987: sub csvuploadmap {
1.608     www      3988:     my ($request,$symb)= @_;
1.41      ng       3989:     if (!$symb) {return '';}
1.72      ng       3990: 
1.41      ng       3991:     my $datatoken;
1.257     albertel 3992:     if (!$env{'form.datatoken'}) {
1.41      ng       3993: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3994:     } else {
1.257     albertel 3995: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3996: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3997:     }
1.41      ng       3998:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3999:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4000:     my ($i,$keyfields);
                   4001:     if (@records) {
1.582     raeburn  4002:         my $fieldserror;
                   4003: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4004:         if ($fieldserror) {
                   4005:             $request->print(&navmap_errormsg());
                   4006:             return;
                   4007:         }
1.257     albertel 4008: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4009: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4010: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4011: 							  \@fields);
                   4012: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4013: 	    chop($keyfields);
                   4014: 	} else {
                   4015: 	    unshift(@fields,['none','']);
                   4016: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4017: 							    \@fields);
1.311     banghart 4018:             foreach my $rec (@records) {
                   4019:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4020:                 if (%temp) {
                   4021:                     $keyfields=join(',',sort(keys(%temp)));
                   4022:                     last;
                   4023:                 }
                   4024:             }
1.41      ng       4025: 	}
                   4026:     }
                   4027:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4028: 
1.41      ng       4029:     return '';
1.27      albertel 4030: }
                   4031: 
1.246     albertel 4032: sub csvuploadoptions {
1.608     www      4033:     my ($request,$symb)= @_;
1.632     www      4034:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4035:     $request->print(<<ENDPICK);
                   4036: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4037: <input type="hidden" name="command"    value="csvuploadassign" />
                   4038: <p>
                   4039: <label>
                   4040:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4041:    $overwrite
1.246     albertel 4042: </label>
                   4043: </p>
                   4044: ENDPICK
                   4045:     my %fields=&get_fields();
                   4046:     if (!defined($fields{'domain'})) {
1.257     albertel 4047: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4048: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4049:     }
1.257     albertel 4050:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4051: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4052: 	my $cleankey=$1;
                   4053: 	if ($cleankey eq 'command') { next; }
                   4054: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4055: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4056:     }
                   4057:     # FIXME do a check for any duplicated user ids...
                   4058:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4059:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4060: <hr /></form>'."\n");
1.246     albertel 4061:     return '';
                   4062: }
                   4063: 
                   4064: sub get_fields {
                   4065:     my %fields;
1.257     albertel 4066:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4067:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4068: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4069: 	    if ($env{'form.f'.$i} ne 'none') {
                   4070: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4071: 	    }
                   4072: 	} else {
1.257     albertel 4073: 	    if ($env{'form.f'.$i} ne 'none') {
                   4074: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4075: 	    }
                   4076: 	}
1.27      albertel 4077:     }
1.246     albertel 4078:     return %fields;
                   4079: }
                   4080: 
                   4081: sub csvuploadassign {
1.608     www      4082:     my ($request,$symb)= @_;
1.246     albertel 4083:     if (!$symb) {return '';}
1.345     bowersj2 4084:     my $error_msg = '';
1.246     albertel 4085:     &Apache::loncommon::load_tmp_file($request);
                   4086:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4087:     my %fields=&get_fields();
1.257     albertel 4088:     my $courseid=$env{'request.course.id'};
1.97      albertel 4089:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4090:     my @notallowed;
1.41      ng       4091:     my @skipped;
                   4092:     my $countdone=0;
                   4093:     foreach my $grade (@gradedata) {
                   4094: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4095: 	my $domain;
                   4096: 	if ($entries{$fields{'domain'}}) {
                   4097: 	    $domain=$entries{$fields{'domain'}};
                   4098: 	} else {
1.257     albertel 4099: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4100: 	}
1.243     albertel 4101: 	$domain=~s/\s//g;
1.41      ng       4102: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4103: 	$username=~s/\s//g;
1.243     albertel 4104: 	if (!$username) {
                   4105: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4106: 	    $id=~s/\s//g;
1.243     albertel 4107: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4108: 	    $username=$ids{$id};
                   4109: 	}
1.41      ng       4110: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4111: 	    my $id=$entries{$fields{'ID'}};
                   4112: 	    $id=~s/\s//g;
                   4113: 	    if ($id) {
                   4114: 		push(@skipped,"$id:$domain");
                   4115: 	    } else {
                   4116: 		push(@skipped,"$username:$domain");
                   4117: 	    }
1.41      ng       4118: 	    next;
                   4119: 	}
1.108     albertel 4120: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4121: 	if (!&canmodify($usec)) {
                   4122: 	    push(@notallowed,"$username:$domain");
                   4123: 	    next;
                   4124: 	}
1.244     albertel 4125: 	my %points;
1.41      ng       4126: 	my %grades;
                   4127: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4128: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4129: 		$dest eq 'domain') { next; }
                   4130: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4131: 	    if ($dest=~/stores_(.*)_points/) {
                   4132: 		my $part=$1;
                   4133: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4134: 					      $symb,$domain,$username);
1.345     bowersj2 4135:                 if ($wgt) {
                   4136:                     $entries{$fields{$dest}}=~s/\s//g;
                   4137:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4138:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4139:                                           : 'correct_by_override';
1.638     www      4140:                     if ($pcr>1) {
                   4141:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4142:                     }
1.345     bowersj2 4143:                     $grades{"resource.$part.awarded"}=$pcr;
                   4144:                     $grades{"resource.$part.solved"}=$award;
                   4145:                     $points{$part}=1;
                   4146:                 } else {
                   4147:                     $error_msg = "<br />" .
                   4148:                         &mt("Some point values were assigned"
                   4149:                             ." for problems with a weight "
                   4150:                             ."of zero. These values were "
                   4151:                             ."ignored.");
                   4152:                 }
1.244     albertel 4153: 	    } else {
                   4154: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4155: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4156: 		my $store_key=$dest;
                   4157: 		$store_key=~s/^stores/resource/;
                   4158: 		$store_key=~s/_/\./g;
                   4159: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4160: 	    }
1.41      ng       4161: 	}
1.508     www      4162: 	if (! %grades) { 
                   4163:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4164:         } else {
                   4165: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4166: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4167: 					   $env{'request.course.id'},
                   4168: 					   $domain,$username);
1.508     www      4169: 	   if ($result eq 'ok') {
1.627     www      4170: # Successfully stored
1.508     www      4171: 	      $request->print('.');
1.627     www      4172: # Remove from grading queue
                   4173:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4174:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4175:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4176:                                              $domain,$username);
                   4177:               $countdone++;
                   4178:            } else {
1.508     www      4179: 	      $request->print("<p><span class=\"LC_error\">".
                   4180:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4181:                                   "$username:$domain",$result)."</span></p>");
                   4182: 	   }
                   4183: 	   $request->rflush();
                   4184:         }
1.41      ng       4185:     }
1.570     www      4186:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4187:     if (@skipped) {
1.571     www      4188: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4189:         $request->print(join(', ',@skipped));
1.106     albertel 4190:     }
                   4191:     if (@notallowed) {
1.571     www      4192: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4193: 	$request->print(join(', ',@notallowed));
1.41      ng       4194:     }
1.106     albertel 4195:     $request->print("<br />\n");
1.345     bowersj2 4196:     return $error_msg;
1.26      albertel 4197: }
1.44      ng       4198: #------------- end of section for handling csv file upload ---------
                   4199: #
                   4200: #-------------------------------------------------------------------
                   4201: #
1.122     ng       4202: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4203: #
                   4204: #--- Select a page/sequence and a student to grade
1.68      ng       4205: sub pickStudentPage {
1.608     www      4206:     my ($request,$symb) = @_;
1.68      ng       4207: 
1.539     riegler  4208:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4209:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4210: 
                   4211: function checkPickOne(formname) {
1.76      ng       4212:     if (radioSelection(formname.student) == null) {
1.539     riegler  4213: 	alert("$alertmsg");
1.68      ng       4214: 	return;
                   4215:     }
1.125     ng       4216:     ptr = pullDownSelection(formname.selectpage);
                   4217:     formname.page.value = formname["page"+ptr].value;
                   4218:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4219:     formname.submit();
                   4220: }
                   4221: 
                   4222: LISTJAVASCRIPT
1.118     ng       4223:     &commonJSfunctions($request);
1.608     www      4224: 
1.257     albertel 4225:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4226:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4227:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4228: 
1.398     albertel 4229:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4230: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4231: 
1.80      ng       4232:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4233:     my $map_error;
                   4234:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4235:     if ($map_error) {
                   4236:         $request->print(&navmap_errormsg());
                   4237:         return; 
                   4238:     }
1.137     albertel 4239:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4240: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4241: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4242:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4243:     my $ctr=0;
1.68      ng       4244:     foreach (@$titles) {
                   4245: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4246: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4247: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4248: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4249: 	$ctr++;
1.68      ng       4250:     }
1.485     albertel 4251:     $select.= '</select>';
1.539     riegler  4252:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4253: 
1.70      ng       4254:     $ctr=0;
                   4255:     foreach (@$titles) {
                   4256: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4257: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4258: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4259: 	$ctr++;
                   4260:     }
1.72      ng       4261:     $result.='<input type="hidden" name="page" />'."\n".
                   4262: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4263: 
1.485     albertel 4264:     my $options =
                   4265: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4266: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4267:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4268: 
                   4269:     $options =
                   4270: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4271: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4272: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4273:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4274:     
                   4275:     $result.=&build_section_inputs();
1.442     banghart 4276:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4277:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4278: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4279: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4280: 
1.539     riegler  4281:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4282: 
1.80      ng       4283:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4284:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4285: 
1.68      ng       4286:     $request->print($result);
                   4287: 
1.485     albertel 4288:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4289: 	&Apache::loncommon::start_data_table().
                   4290: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4292: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4293: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4294: 	'<th>'.&nameUserString('header').'</th>'.
                   4295: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4296:  
1.76      ng       4297:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4298:     my $ptr = 1;
1.294     albertel 4299:     foreach my $student (sort 
                   4300: 			 {
                   4301: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4302: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4303: 			     }
                   4304: 			     return $a cmp $b;
                   4305: 			 } (keys(%$fullname))) {
1.68      ng       4306: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4307: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4308:                                   : '</td>');
1.126     ng       4309: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4310: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4311: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4312: 	$studentTable.=
                   4313: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4314:                          : '');
1.68      ng       4315: 	$ptr++;
                   4316:     }
1.484     albertel 4317:     if ($ptr%2 == 0) {
                   4318: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4319: 	    &Apache::loncommon::end_data_table_row();
                   4320:     }
                   4321:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4322:     $studentTable.='<input type="button" '.
1.589     bisitz   4323:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4324: 
                   4325:     $request->print($studentTable);
                   4326: 
                   4327:     return '';
                   4328: }
                   4329: 
                   4330: sub getSymbMap {
1.582     raeburn  4331:     my ($map_error) = @_;
1.132     bowersj2 4332:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4333:     unless (ref($navmap)) {
                   4334:         if (ref($map_error)) {
                   4335:             $$map_error = 'navmap';
                   4336:         }
                   4337:         return;
                   4338:     }
1.68      ng       4339:     my %symbx = ();
                   4340:     my @titles = ();
1.117     bowersj2 4341:     my $minder = 0;
                   4342: 
                   4343:     # Gather every sequence that has problems.
1.240     albertel 4344:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4345: 					       1,0,1);
1.117     bowersj2 4346:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4347: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4348: 	    my $title = $minder.'.'.
                   4349: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4350: 	    push(@titles, $title); # minder in case two titles are identical
                   4351: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4352: 	    $minder++;
1.241     albertel 4353: 	}
1.68      ng       4354:     }
                   4355:     return \@titles,\%symbx;
                   4356: }
                   4357: 
1.72      ng       4358: #
                   4359: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4360: sub displayPage {
1.608     www      4361:     my ($request,$symb) = @_;
1.257     albertel 4362:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4363:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4364:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4365:     my $pageTitle = $env{'form.page'};
1.103     albertel 4366:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4367:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4368:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4369: 
                   4370:     #need to make sure we have the correct data for later EXT calls, 
                   4371:     #thus invalidate the cache
                   4372:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4373:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4374:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4375:     &Apache::lonnet::clear_EXT_cache_status();
                   4376: 
1.103     albertel 4377:     if (!&canview($usec)) {
1.485     albertel 4378: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4379: 	return;
                   4380:     }
1.398     albertel 4381:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4382:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4383: 	'</h3>'."\n";
1.500     albertel 4384:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4385:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4386: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4387:     } else {
                   4388: 	delete($env{'form.CODE'});
                   4389:     }
1.71      ng       4390:     &sub_page_js($request);
                   4391:     $request->print($result);
                   4392: 
1.132     bowersj2 4393:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4394:     unless (ref($navmap)) {
                   4395:         $request->print(&navmap_errormsg());
                   4396:         return;
                   4397:     }
1.257     albertel 4398:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4399:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4400:     if (!$map) {
1.485     albertel 4401: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4402: 	return; 
                   4403:     }
1.68      ng       4404:     my $iterator = $navmap->getIterator($map->map_start(),
                   4405: 					$map->map_finish());
                   4406: 
1.71      ng       4407:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4408: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4409: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4410: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4411: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4412: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4413: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4414: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4415: 
1.382     albertel 4416:     if (defined($env{'form.CODE'})) {
                   4417: 	$studentTable.=
                   4418: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4419:     }
1.381     albertel 4420:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4421: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4422: 
1.594     bisitz   4423:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4424:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4425:         '</span>'."\n".
1.484     albertel 4426: 	&Apache::loncommon::start_data_table().
                   4427: 	&Apache::loncommon::start_data_table_header_row().
                   4428: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4429: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4430: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4431: 
1.329     albertel 4432:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4433:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4434:     $iterator->next(); # skip the first BEGIN_MAP
                   4435:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4436:     while ($depth > 0) {
1.68      ng       4437:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4438:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4439: 
1.385     albertel 4440:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4441: 	    my $parts = $curRes->parts();
1.68      ng       4442:             my $title = $curRes->compTitle();
1.71      ng       4443: 	    my $symbx = $curRes->symb();
1.484     albertel 4444: 	    $studentTable.=
                   4445: 		&Apache::loncommon::start_data_table_row().
                   4446: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4447: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4448: 		                        : '<br />('.&mt('[_1]parts)',
                   4449: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4450: 		 ).
                   4451: 		 '</td>';
1.71      ng       4452: 	    $studentTable.='<td valign="top">';
1.382     albertel 4453: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4454: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4455: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4456: 					     undef,'both',\%form);
1.71      ng       4457: 	    } else {
1.382     albertel 4458: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4459: 		$companswer =~ s|<form(.*?)>||g;
                   4460: 		$companswer =~ s|</form>||g;
1.71      ng       4461: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4462: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4463: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4464: #		}
1.116     ng       4465: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4466: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4467: 	    }
                   4468: 
1.257     albertel 4469: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4470: 
1.257     albertel 4471: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4472: 		if ($record{'version'} eq '') {
1.485     albertel 4473: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4474: 		} else {
1.116     ng       4475: 		    my %responseType = ();
                   4476: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4477: 			my @responseIds =$curRes->responseIds($partid);
                   4478: 			my @responseType =$curRes->responseType($partid);
                   4479: 			my %responseIds;
                   4480: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4481: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4482: 			}
                   4483: 			$responseType{$partid} = \%responseIds;
1.116     ng       4484: 		    }
1.148     albertel 4485: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4486: 
1.71      ng       4487: 		}
1.257     albertel 4488: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4489: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4490: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4491: 									$env{'request.course.id'},
1.71      ng       4492: 									'','.submission');
                   4493:  
                   4494: 	    }
1.103     albertel 4495: 	    if (&canmodify($usec)) {
1.585     bisitz   4496:             $studentTable.=&gradeBox_start();
1.103     albertel 4497: 		foreach my $partid (@{$parts}) {
                   4498: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4499: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4500: 		    $question++;
                   4501: 		}
1.585     bisitz   4502:             $studentTable.=&gradeBox_end();
1.196     albertel 4503: 		$prob++;
1.71      ng       4504: 	    }
                   4505: 	    $studentTable.='</td></tr>';
1.68      ng       4506: 
1.103     albertel 4507: 	}
1.68      ng       4508:         $curRes = $iterator->next();
                   4509:     }
                   4510: 
1.589     bisitz   4511:     $studentTable.=
                   4512:         '</table>'."\n".
                   4513:         '<input type="button" value="'.&mt('Save').'" '.
                   4514:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4515:         '</form>'."\n";
1.71      ng       4516:     $request->print($studentTable);
                   4517: 
                   4518:     return '';
1.119     ng       4519: }
                   4520: 
                   4521: sub displaySubByDates {
1.148     albertel 4522:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4523:     my $isCODE=0;
1.335     albertel 4524:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4525:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4526:     my $studentTable=&Apache::loncommon::start_data_table().
                   4527: 	&Apache::loncommon::start_data_table_header_row().
                   4528: 	'<th>'.&mt('Date/Time').'</th>'.
                   4529: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4530: 	'<th>'.&mt('Submission').'</th>'.
                   4531: 	'<th>'.&mt('Status').'</th>'.
                   4532: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4533:     my ($version);
                   4534:     my %mark;
1.148     albertel 4535:     my %orders;
1.119     ng       4536:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4537:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4538: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4539:     }
1.335     albertel 4540: 
                   4541:     my $interaction;
1.525     raeburn  4542:     my $no_increment = 1;
1.640     raeburn  4543:     my %lastrndseed;
1.119     ng       4544:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4545: 	my $timestamp = 
                   4546: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4547: 	if (exists($$record{$version.':resource.0.version'})) {
                   4548: 	    $interaction = $$record{$version.':resource.0.version'};
                   4549: 	}
                   4550: 
                   4551: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4552: 		             : "$version:resource");
1.467     albertel 4553: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4554: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4555: 	if ($isCODE) {
                   4556: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4557: 	}
1.119     ng       4558: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4559: 	my @displaySub = ();
                   4560: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4561:             my ($hidden,$type);
                   4562:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4563:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4564:                 $hidden = 1;
                   4565:             }
1.335     albertel 4566: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4567: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4568: 	    
1.122     ng       4569: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4570: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4571: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4572: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4573: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4574:                     
1.335     albertel 4575: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4576: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4577:                     $displaySub[0].='<span class="LC_nobreak"';
                   4578:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4579:                                    .' <span class="LC_internal_info">'
1.625     www      4580:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4581:                                    .'</span>'
                   4582:                                    .' <b>';
1.596     raeburn  4583:                     if ($hidden) {
                   4584:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4585:                     } else {
1.640     raeburn  4586:                         my ($trial,$rndseed,$newvariation);
                   4587:                         if ($type eq 'randomizetry') {
                   4588:                             $trial = $$record{"$where.$partid.tries"};
                   4589:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4590:                         }
1.596     raeburn  4591: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4592: 			    $displaySub[0].=&mt('Trial not counted');
                   4593: 		        } else {
                   4594: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4595: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4596:                             if ($rndseed || $lastrndseed{$partid}) {
                   4597:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4598:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4599:                                 }
                   4600:                             }
                   4601:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4602: 		        }
                   4603: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4604:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4605: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4606: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4607: 			    $orders{$partid}->{$responseId}=
                   4608: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4609:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4610: 		        }
1.640     raeburn  4611: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4612: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4613: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4614:                     }
1.147     albertel 4615: 		}
                   4616: 	    }
1.335     albertel 4617: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4618: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4619: 				    $$record{"$where.$partid.checkedin"},
                   4620: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4621: 					'<br />';
1.335     albertel 4622: 	    }
                   4623: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4624: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4625: 		    lc($$record{"$where.$partid.award"}).' '.
                   4626: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4627: 		    '<br />';
                   4628: 	    }
1.335     albertel 4629: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4630: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4631: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4632: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4633: 		$displaySub[2].=
                   4634: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4635: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4636: 	    }
                   4637: 	}
                   4638: 	# needed because old essay regrader has not parts info
                   4639: 	if (exists $$record{"$version:resource.regrader"}) {
                   4640: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4641: 	}
                   4642: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4643: 	if ($displaySub[2]) {
1.467     albertel 4644: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4645: 	}
1.467     albertel 4646: 	$studentTable.='&nbsp;</td>'.
                   4647: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4648:     }
1.467     albertel 4649:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4650:     return $studentTable;
1.71      ng       4651: }
                   4652: 
                   4653: sub updateGradeByPage {
1.608     www      4654:     my ($request,$symb) = @_;
1.71      ng       4655: 
1.257     albertel 4656:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4657:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4658:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4659:     my $pageTitle = $env{'form.page'};
1.103     albertel 4660:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4661:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4662:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4663:     if (!&canmodify($usec)) {
1.526     raeburn  4664: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4665: 	return;
                   4666:     }
1.398     albertel 4667:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4668:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4669: 	'</h3>'."\n";
1.70      ng       4670: 
1.68      ng       4671:     $request->print($result);
                   4672: 
1.582     raeburn  4673: 
1.132     bowersj2 4674:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4675:     unless (ref($navmap)) {
                   4676:         $request->print(&navmap_errormsg());
                   4677:         return;
                   4678:     }
1.257     albertel 4679:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4680:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4681:     if (!$map) {
1.527     raeburn  4682: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4683: 	return; 
                   4684:     }
1.71      ng       4685:     my $iterator = $navmap->getIterator($map->map_start(),
                   4686: 					$map->map_finish());
1.70      ng       4687: 
1.484     albertel 4688:     my $studentTable=
                   4689: 	&Apache::loncommon::start_data_table().
                   4690: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4691: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4692: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4693: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4694: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4695: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4696: 
                   4697:     $iterator->next(); # skip the first BEGIN_MAP
                   4698:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4699:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4700:     while ($depth > 0) {
1.71      ng       4701:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4702:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4703: 
1.385     albertel 4704:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4705: 	    my $parts = $curRes->parts();
1.71      ng       4706:             my $title = $curRes->compTitle();
                   4707: 	    my $symbx = $curRes->symb();
1.484     albertel 4708: 	    $studentTable.=
                   4709: 		&Apache::loncommon::start_data_table_row().
                   4710: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4711: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4712:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4713: 		.')').'</td>';
1.71      ng       4714: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4715: 
                   4716: 	    my %newrecord=();
                   4717: 	    my @displayPts=();
1.269     raeburn  4718:             my %aggregate = ();
                   4719:             my $aggregateflag = 0;
1.71      ng       4720: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4721: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4722: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4723: 
1.257     albertel 4724: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4725: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4726: 		my $partial = $newpts/$wgt;
                   4727: 		my $score;
                   4728: 		if ($partial > 0) {
                   4729: 		    $score = 'correct_by_override';
1.125     ng       4730: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4731: 		    $score = 'incorrect_by_override';
                   4732: 		}
1.257     albertel 4733: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4734: 		if ($dropMenu eq 'excused') {
1.71      ng       4735: 		    $partial = '';
                   4736: 		    $score = 'excused';
1.125     ng       4737: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4738: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4739: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4740: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4741: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4742: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4743: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4744: 		    $changeflag++;
                   4745: 		    $newpts = '';
1.269     raeburn  4746:                     
                   4747:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4748:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4749:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4750:                     if ($aggtries > 0) {
                   4751:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4752:                         $aggregateflag = 1;
                   4753:                     }
1.71      ng       4754: 		}
1.324     albertel 4755: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4756: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4757: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4758: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4759: 		    '&nbsp;<br />';
1.526     raeburn  4760: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4761: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4762: 		    '&nbsp;<br />';
1.71      ng       4763: 		$question++;
1.380     albertel 4764: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4765: 
1.71      ng       4766: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4767: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4768: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4769: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4770: 
                   4771: 		$changeflag++;
                   4772: 	    }
                   4773: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4774: 		my %record = 
                   4775: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4776: 					     $udom,$uname);
                   4777: 
                   4778: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4779: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4780: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4781: 		    $newrecord{'resource.CODE'} = '';
                   4782: 		}
1.257     albertel 4783: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4784: 					$udom,$uname);
1.382     albertel 4785: 		%record = &Apache::lonnet::restore($symbx,
                   4786: 						   $env{'request.course.id'},
                   4787: 						   $udom,$uname);
1.380     albertel 4788: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4789: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4790: 	    }
1.380     albertel 4791: 	    
1.269     raeburn  4792:             if ($aggregateflag) {
                   4793:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4794:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4795:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4796:             }
1.125     ng       4797: 
1.71      ng       4798: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4799: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4800: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4801: 
1.196     albertel 4802: 	    $prob++;
1.68      ng       4803: 	}
1.71      ng       4804:         $curRes = $iterator->next();
1.68      ng       4805:     }
1.98      albertel 4806: 
1.484     albertel 4807:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4808:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4809: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4810: 		  $changeflag));
1.76      ng       4811:     $request->print($grademsg.$studentTable);
1.68      ng       4812: 
1.70      ng       4813:     return '';
                   4814: }
                   4815: 
1.72      ng       4816: #-------- end of section for handling grading by page/sequence ---------
                   4817: #
                   4818: #-------------------------------------------------------------------
                   4819: 
1.581     www      4820: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4821: #
                   4822: #------ start of section for handling grading by page/sequence ---------
                   4823: 
1.423     albertel 4824: =pod
                   4825: 
                   4826: =head1 Bubble sheet grading routines
                   4827: 
1.424     albertel 4828:   For this documentation:
                   4829: 
                   4830:    'scanline' refers to the full line of characters
                   4831:    from the file that we are parsing that represents one entire sheet
                   4832: 
                   4833:    'bubble line' refers to the data
                   4834:    representing the line of bubbles that are on the physical bubble sheet
                   4835: 
                   4836: 
                   4837: The overall process is that a scanned in bubble sheet data is uploaded
                   4838: into a course. When a user wants to grade, they select a
                   4839: sequence/folder of resources, a file of bubble sheet info, and pick
                   4840: one of the predefined configurations for what each scanline looks
                   4841: like.
                   4842: 
                   4843: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4844: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4845: because too light bubbling), 'double bubble' (each bubble line should
                   4846: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4847: invalid student/employee ID
1.424     albertel 4848: 
                   4849: If the CODE option is used that determines the randomization of the
1.556     weissno  4850: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4851: username:domain.
                   4852: 
                   4853: During the validation phase the instructor can choose to skip scanlines. 
                   4854: 
1.435     foxr     4855: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4856: 
                   4857:   scantron_original_filename (unmodified original file)
                   4858:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4859:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4860: 
                   4861: Also there is a separate hash nohist_scantrondata that contains extra
                   4862: correction information that isn't representable in the bubble sheet
                   4863: file (see &scantron_getfile() for more information)
                   4864: 
                   4865: After all scanlines are either valid, marked as valid or skipped, then
                   4866: foreach line foreach problem in the picked sequence, an ssi request is
                   4867: made that simulates a user submitting their selected letter(s) against
                   4868: the homework problem.
1.423     albertel 4869: 
                   4870: =over 4
                   4871: 
                   4872: 
                   4873: 
                   4874: =item defaultFormData
                   4875: 
                   4876:   Returns html hidden inputs used to hold context/default values.
                   4877: 
                   4878:  Arguments:
                   4879:   $symb - $symb of the current resource 
                   4880: 
                   4881: =cut
1.422     foxr     4882: 
1.81      albertel 4883: sub defaultFormData {
1.324     albertel 4884:     my ($symb)=@_;
1.613     www      4885:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4886: }
                   4887: 
1.447     foxr     4888: 
1.423     albertel 4889: =pod 
                   4890: 
                   4891: =item getSequenceDropDown
                   4892: 
                   4893:    Return html dropdown of possible sequences to grade
                   4894:  
                   4895:  Arguments:
1.582     raeburn  4896:    $symb - $symb of the current resource
                   4897:    $map_error - ref to scalar which will container error if
                   4898:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4899: 
                   4900: =cut
1.422     foxr     4901: 
1.75      albertel 4902: sub getSequenceDropDown {
1.582     raeburn  4903:     my ($symb,$map_error)=@_;
1.75      albertel 4904:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4905:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4906:     if (ref($map_error)) {
                   4907:         return if ($$map_error);
                   4908:     }
1.137     albertel 4909:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4910:     my $ctr=0;
                   4911:     foreach (@$titles) {
                   4912: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4913: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4914: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4915: 	    '>'.$showtitle.'</option>'."\n";
                   4916: 	$ctr++;
                   4917:     }
                   4918:     $result.= '</select>';
                   4919:     return $result;
                   4920: }
                   4921: 
1.495     albertel 4922: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4923:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4924: 
                   4925: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4926: 
1.509     raeburn  4927: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4928:                                    # matchresponse or rankresponse, where 
                   4929:                                    # an individual response can have multiple 
                   4930:                                    # lines
1.503     raeburn  4931: 
                   4932: my %responsetype_per_response;     # responsetype for each response
                   4933: 
1.495     albertel 4934: # Save and restore the bubble lines array to the form env.
                   4935: 
                   4936: 
                   4937: sub save_bubble_lines {
                   4938:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4939: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4940: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4941: 	    $first_bubble_line{$line};
1.503     raeburn  4942:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4943:             $subdivided_bubble_lines{$line};
                   4944:         $env{"form.scantron.responsetype.$line"} =
                   4945:             $responsetype_per_response{$line};
1.495     albertel 4946:     }
                   4947: }
                   4948: 
                   4949: 
                   4950: sub restore_bubble_lines {
                   4951:     my $line = 0;
                   4952:     %bubble_lines_per_response = ();
                   4953:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4954: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4955: 	$bubble_lines_per_response{$line} = $value;
                   4956: 	$first_bubble_line{$line}  =
                   4957: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4958:         $subdivided_bubble_lines{$line} =
                   4959:             $env{"form.scantron.sub_bubblelines.$line"};
                   4960:         $responsetype_per_response{$line} =
                   4961:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4962: 	$line++;
                   4963:     }
                   4964: }
                   4965: 
                   4966: #  Given the parsed scanline, get the response for 
                   4967: #  'answer' number n:
                   4968: 
                   4969: sub get_response_bubbles {
                   4970:     my ($parsed_line, $response)  = @_;
                   4971: 
                   4972:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4973:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4974:     
                   4975:     my $selected = "";
                   4976: 
                   4977:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4978: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4979: 	$bubble_line++;
                   4980:     }
                   4981:     return $selected;
                   4982: }
1.423     albertel 4983: 
                   4984: =pod 
                   4985: 
                   4986: =item scantron_filenames
                   4987: 
                   4988:    Returns a list of the scantron files in the current course 
                   4989: 
                   4990: =cut
1.422     foxr     4991: 
1.202     albertel 4992: sub scantron_filenames {
1.257     albertel 4993:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4994:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4995:     my $getpropath = 1;
1.157     albertel 4996:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4997:                                        $getpropath);
1.202     albertel 4998:     my @possiblenames;
1.201     albertel 4999:     foreach my $filename (sort(@files)) {
1.157     albertel 5000: 	($filename)=split(/&/,$filename);
                   5001: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5002: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5003: 	push(@possiblenames,$filename);
                   5004:     }
                   5005:     return @possiblenames;
                   5006: }
                   5007: 
1.423     albertel 5008: =pod 
                   5009: 
                   5010: =item scantron_uploads
                   5011: 
                   5012:    Returns  html drop-down list of scantron files in current course.
                   5013: 
                   5014:  Arguments:
                   5015:    $file2grade - filename to set as selected in the dropdown
                   5016: 
                   5017: =cut
1.422     foxr     5018: 
1.202     albertel 5019: sub scantron_uploads {
1.209     ng       5020:     my ($file2grade) = @_;
1.202     albertel 5021:     my $result=	'<select name="scantron_selectfile">';
                   5022:     $result.="<option></option>";
                   5023:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5024: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5025:     }
                   5026:     $result.="</select>";
                   5027:     return $result;
                   5028: }
                   5029: 
1.423     albertel 5030: =pod 
                   5031: 
                   5032: =item scantron_scantab
                   5033: 
                   5034:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5035:   file.
                   5036: 
                   5037: =cut
1.422     foxr     5038: 
1.82      albertel 5039: sub scantron_scantab {
                   5040:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5041:     $result.='<option></option>'."\n";
1.518     raeburn  5042:     my @lines = &get_scantronformat_file();
                   5043:     if (@lines > 0) {
                   5044:         foreach my $line (@lines) {
                   5045:             next if (($line =~ /^\#/) || ($line eq ''));
                   5046: 	    my ($name,$descrip)=split(/:/,$line);
                   5047: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5048:         }
1.82      albertel 5049:     }
                   5050:     $result.='</select>'."\n";
1.518     raeburn  5051:     return $result;
                   5052: }
                   5053: 
                   5054: =pod
                   5055: 
                   5056: =item get_scantronformat_file
                   5057: 
                   5058:   Returns an array containing lines from the scantron format file for
                   5059:   the domain of the course.
                   5060: 
                   5061:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5062:   lines are from this file.
                   5063: 
                   5064:   Otherwise, if a default.tab has been published in RES space by the 
                   5065:   domainconfig user, lines are from this file.
                   5066: 
                   5067:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5068:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5069: 
1.518     raeburn  5070: =cut
                   5071: 
                   5072: sub get_scantronformat_file {
                   5073:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5074:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5075:     my $gottab = 0;
                   5076:     my @lines;
                   5077:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5078:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5079:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5080:             if ($formatfile ne '-1') {
                   5081:                 @lines = split("\n",$formatfile,-1);
                   5082:                 $gottab = 1;
                   5083:             }
                   5084:         }
                   5085:     }
                   5086:     if (!$gottab) {
                   5087:         my $confname = $cdom.'-domainconfig';
                   5088:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5089:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5090:         if ($formatfile ne '-1') {
                   5091:             @lines = split("\n",$formatfile,-1);
                   5092:             $gottab = 1;
                   5093:         }
                   5094:     }
                   5095:     if (!$gottab) {
1.519     raeburn  5096:         my @domains = &Apache::lonnet::current_machine_domains();
                   5097:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5098:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5099:             @lines = <$fh>;
                   5100:             close($fh);
                   5101:         } else {
                   5102:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5103:             @lines = <$fh>;
                   5104:             close($fh);
                   5105:         }
1.518     raeburn  5106:     }
                   5107:     return @lines;
1.82      albertel 5108: }
                   5109: 
1.423     albertel 5110: =pod 
                   5111: 
                   5112: =item scantron_CODElist
                   5113: 
                   5114:   Returns html drop down of the saved CODE lists from current course,
                   5115:   generated from earlier printings.
                   5116: 
                   5117: =cut
1.422     foxr     5118: 
1.186     albertel 5119: sub scantron_CODElist {
1.257     albertel 5120:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5121:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5122:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5123:     my $namechoice='<option></option>';
1.225     albertel 5124:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5125: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5126: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5127: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5128:     }
                   5129:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5130:     return $namechoice;
                   5131: }
                   5132: 
1.423     albertel 5133: =pod 
                   5134: 
                   5135: =item scantron_CODEunique
                   5136: 
                   5137:   Returns the html for "Each CODE to be used once" radio.
                   5138: 
                   5139: =cut
1.422     foxr     5140: 
1.186     albertel 5141: sub scantron_CODEunique {
1.532     bisitz   5142:     my $result='<span class="LC_nobreak">
1.272     albertel 5143:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5144:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5145:                 </span>
1.532     bisitz   5146:                 <span class="LC_nobreak">
1.272     albertel 5147:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5148:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5149:                 </span>';
1.186     albertel 5150:     return $result;
                   5151: }
1.423     albertel 5152: 
                   5153: =pod 
                   5154: 
                   5155: =item scantron_selectphase
                   5156: 
                   5157:   Generates the initial screen to start the bubble sheet process.
                   5158:   Allows for - starting a grading run.
1.424     albertel 5159:              - downloading existing scan data (original, corrected
1.423     albertel 5160:                                                 or skipped info)
                   5161: 
                   5162:              - uploading new scan data
                   5163: 
                   5164:  Arguments:
                   5165:   $r          - The Apache request object
                   5166:   $file2grade - name of the file that contain the scanned data to score
                   5167: 
                   5168: =cut
1.186     albertel 5169: 
1.75      albertel 5170: sub scantron_selectphase {
1.608     www      5171:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5172:     if (!$symb) {return '';}
1.582     raeburn  5173:     my $map_error;
                   5174:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5175:     if ($map_error) {
                   5176:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5177:         return;
                   5178:     }
1.324     albertel 5179:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5180:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5181:     my $format_selector=&scantron_scantab();
1.186     albertel 5182:     my $CODE_selector=&scantron_CODElist();
                   5183:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5184:     my $result;
1.422     foxr     5185: 
1.513     foxr     5186:     $ssi_error = 0;
                   5187: 
1.606     wenzelju 5188:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5189:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5190: 
                   5191: 	# Chunk of form to prompt for a scantron file upload.
                   5192: 
                   5193:         $r->print('
                   5194:     <br />
                   5195:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5196:        '.&Apache::loncommon::start_data_table_header_row().'
                   5197:             <th>
                   5198:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5199:             </th>
                   5200:        '.&Apache::loncommon::end_data_table_header_row().'
                   5201:        '.&Apache::loncommon::start_data_table_row().'
                   5202:             <td>
                   5203: ');
1.608     www      5204:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5205:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5206:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5207:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5208:     function checkUpload(formname) {
                   5209: 	if (formname.upfile.value == "") {
                   5210: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5211: 	    return false;
                   5212: 	}
                   5213: 	formname.submit();
                   5214:     }'));
                   5215:     $r->print('
                   5216:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5217:                 '.$default_form_data.'
                   5218:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5219:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5220:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5221:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5222:                 <br />
                   5223:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5224:               </form>
                   5225: ');
                   5226: 
                   5227:         $r->print('
                   5228:             </td>
                   5229:        '.&Apache::loncommon::end_data_table_row().'
                   5230:        '.&Apache::loncommon::end_data_table().'
                   5231: ');
                   5232:     }
                   5233: 
1.422     foxr     5234:     # Chunk of form to prompt for a file to grade and how:
                   5235: 
1.489     albertel 5236:     $result.= '
                   5237:     <br />
                   5238:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5239:     <input type="hidden" name="command" value="scantron_warning" />
                   5240:     '.$default_form_data.'
                   5241:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5242:        '.&Apache::loncommon::start_data_table_header_row().'
                   5243:             <th colspan="2">
1.492     albertel 5244:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5245:             </th>
                   5246:        '.&Apache::loncommon::end_data_table_header_row().'
                   5247:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5248:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5249:        '.&Apache::loncommon::end_data_table_row().'
                   5250:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5251:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5252:        '.&Apache::loncommon::end_data_table_row().'
                   5253:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5254:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5255:        '.&Apache::loncommon::end_data_table_row().'
                   5256:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5257:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5258:        '.&Apache::loncommon::end_data_table_row().'
                   5259:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5260:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5261:        '.&Apache::loncommon::end_data_table_row().'
                   5262:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5263: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5264:             <td>
1.492     albertel 5265: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5266:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5267:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5268: 	    </td>
1.489     albertel 5269:        '.&Apache::loncommon::end_data_table_row().'
                   5270:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5271:             <td colspan="2">
1.572     www      5272:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5273:             </td>
1.489     albertel 5274:        '.&Apache::loncommon::end_data_table_row().'
                   5275:     '.&Apache::loncommon::end_data_table().'
                   5276:     </form>
                   5277: ';
1.162     albertel 5278:    
                   5279:     $r->print($result);
                   5280: 
1.422     foxr     5281: 
                   5282: 
                   5283:     # Chunk of the form that prompts to view a scoring office file,
                   5284:     # corrected file, skipped records in a file.
                   5285: 
1.489     albertel 5286:     $r->print('
                   5287:    <br />
                   5288:    <form action="/adm/grades" name="scantron_download">
                   5289:      '.$default_form_data.'
                   5290:      <input type="hidden" name="command" value="scantron_download" />
                   5291:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5292:        '.&Apache::loncommon::start_data_table_header_row().'
                   5293:               <th>
1.492     albertel 5294:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5295:               </th>
                   5296:        '.&Apache::loncommon::end_data_table_header_row().'
                   5297:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5298:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5299:                 <br />
1.492     albertel 5300:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5301:        '.&Apache::loncommon::end_data_table_row().'
                   5302:      '.&Apache::loncommon::end_data_table().'
                   5303:    </form>
                   5304:    <br />
                   5305: ');
1.162     albertel 5306: 
1.457     banghart 5307:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5308: 
1.528     raeburn  5309:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5310:              $default_form_data."\n".
                   5311:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5312:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5313:              '<th colspan="2">
1.572     www      5314:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5315:              '</th>'."\n".
                   5316:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5317:               &Apache::loncommon::start_data_table_row()."\n".
                   5318:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5319:               '<td> '.$sequence_selector.' </td>'.
                   5320:               &Apache::loncommon::end_data_table_row()."\n".
                   5321:               &Apache::loncommon::start_data_table_row()."\n".
                   5322:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5323:               '<td> '.$file_selector.' </td>'."\n".
                   5324:               &Apache::loncommon::end_data_table_row()."\n".
                   5325:               &Apache::loncommon::start_data_table_row()."\n".
                   5326:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5327:               '<td> '.$format_selector.' </td>'."\n".
                   5328:               &Apache::loncommon::end_data_table_row()."\n".
                   5329:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5330:               '<td> '.&mt('Options').' </td>'."\n".
                   5331:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5332:               &Apache::loncommon::end_data_table_row()."\n".
                   5333:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5334:               '<td colspan="2">'."\n".
                   5335:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5336:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5337:               '</td>'."\n".
                   5338:               &Apache::loncommon::end_data_table_row()."\n".
                   5339:               &Apache::loncommon::end_data_table()."\n".
                   5340:               '</form><br />');
                   5341:     return;
1.75      albertel 5342: }
                   5343: 
1.423     albertel 5344: =pod
                   5345: 
                   5346: =item get_scantron_config
                   5347: 
                   5348:    Parse and return the scantron configuration line selected as a
                   5349:    hash of configuration file fields.
                   5350: 
                   5351:  Arguments:
                   5352:     which - the name of the configuration to parse from the file.
                   5353: 
                   5354: 
                   5355:  Returns:
                   5356:             If the named configuration is not in the file, an empty
                   5357:             hash is returned.
                   5358:     a hash with the fields
                   5359:       name         - internal name for the this configuration setup
                   5360:       description  - text to display to operator that describes this config
                   5361:       CODElocation - if 0 or the string 'none'
                   5362:                           - no CODE exists for this config
                   5363:                      if -1 || the string 'letter'
                   5364:                           - a CODE exists for this config and is
                   5365:                             a string of letters
                   5366:                      Unsupported value (but planned for future support)
                   5367:                           if a positive integer
                   5368:                                - The CODE exists as the first n items from
                   5369:                                  the question section of the form
                   5370:                           if the string 'number'
                   5371:                                - The CODE exists for this config and is
                   5372:                                  a string of numbers
                   5373:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5374:                      the CODE starts
                   5375:       CODElength  - length of the CODE
1.573     bisitz   5376:       IDstart     - column where the student/employee ID starts
1.556     weissno  5377:       IDlength    - length of the student/employee ID info
1.423     albertel 5378:       Qstart      - column where the information from the bubbled
                   5379:                     'questions' start
                   5380:       Qlength     - number of columns comprising a single bubble line from
                   5381:                     the sheet. (usually either 1 or 10)
1.424     albertel 5382:       Qon         - either a single character representing the character used
1.423     albertel 5383:                     to signal a bubble was chosen in the positional setup, or
                   5384:                     the string 'letter' if the letter of the chosen bubble is
                   5385:                     in the final, or 'number' if a number representing the
                   5386:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5387:       Qoff        - the character used to represent that a bubble was
                   5388:                     left blank
1.423     albertel 5389:       PaperID     - if the scanning process generates a unique number for each
                   5390:                     sheet scanned the column that this ID number starts in
                   5391:       PaperIDlength - number of columns that comprise the unique ID number
                   5392:                       for the sheet of paper
1.424     albertel 5393:       FirstName   - column that the first name starts in
1.423     albertel 5394:       FirstNameLength - number of columns that the first name spans
                   5395:  
                   5396:       LastName    - column that the last name starts in
                   5397:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5398:       BubblesPerRow - number of bubbles available in each row used to 
                   5399:                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5400: =cut
1.422     foxr     5401: 
1.82      albertel 5402: sub get_scantron_config {
                   5403:     my ($which) = @_;
1.518     raeburn  5404:     my @lines = &get_scantronformat_file();
1.82      albertel 5405:     my %config;
1.157     albertel 5406:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5407:     foreach my $line (@lines) {
1.82      albertel 5408: 	my ($name,$descrip)=split(/:/,$line);
                   5409: 	if ($name ne $which ) { next; }
                   5410: 	chomp($line);
                   5411: 	my @config=split(/:/,$line);
                   5412: 	$config{'name'}=$config[0];
                   5413: 	$config{'description'}=$config[1];
                   5414: 	$config{'CODElocation'}=$config[2];
                   5415: 	$config{'CODEstart'}=$config[3];
                   5416: 	$config{'CODElength'}=$config[4];
                   5417: 	$config{'IDstart'}=$config[5];
                   5418: 	$config{'IDlength'}=$config[6];
                   5419: 	$config{'Qstart'}=$config[7];
1.497     foxr     5420:  	$config{'Qlength'}=$config[8];
1.82      albertel 5421: 	$config{'Qoff'}=$config[9];
                   5422: 	$config{'Qon'}=$config[10];
1.157     albertel 5423: 	$config{'PaperID'}=$config[11];
                   5424: 	$config{'PaperIDlength'}=$config[12];
                   5425: 	$config{'FirstName'}=$config[13];
                   5426: 	$config{'FirstNamelength'}=$config[14];
                   5427: 	$config{'LastName'}=$config[15];
                   5428: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5429:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5430: 	last;
                   5431:     }
                   5432:     return %config;
                   5433: }
                   5434: 
1.423     albertel 5435: =pod 
                   5436: 
                   5437: =item username_to_idmap
                   5438: 
1.556     weissno  5439:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5440:     student username:domain.
                   5441: 
                   5442:   Arguments:
                   5443: 
                   5444:     $classlist - reference to the class list hash. This is a hash
                   5445:                  keyed by student name:domain  whose elements are references
1.424     albertel 5446:                  to arrays containing various chunks of information
1.423     albertel 5447:                  about the student. (See loncoursedata for more info).
                   5448: 
                   5449:   Returns
                   5450:     %idmap - the constructed hash
                   5451: 
                   5452: =cut
                   5453: 
1.82      albertel 5454: sub username_to_idmap {
                   5455:     my ($classlist)= @_;
                   5456:     my %idmap;
                   5457:     foreach my $student (keys(%$classlist)) {
                   5458: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5459: 	    $student;
                   5460:     }
                   5461:     return %idmap;
                   5462: }
1.423     albertel 5463: 
                   5464: =pod
                   5465: 
1.424     albertel 5466: =item scantron_fixup_scanline
1.423     albertel 5467: 
                   5468:    Process a requested correction to a scanline.
                   5469: 
                   5470:   Arguments:
                   5471:     $scantron_config   - hash from &get_scantron_config()
                   5472:     $scan_data         - hash of correction information 
                   5473:                           (see &scantron_getfile())
                   5474:     $line              - existing scanline
                   5475:     $whichline         - line number of the passed in scanline
                   5476:     $field             - type of change to process 
                   5477:                          (either 
1.573     bisitz   5478:                           'ID'     -> correct the student/employee ID
1.423     albertel 5479:                           'CODE'   -> correct the CODE
                   5480:                           'answer' -> fixup the submitted answers)
                   5481:     
                   5482:    $args               - hash of additional info,
                   5483:                           - 'ID' 
                   5484:                                'newid' -> studentID to use in replacement
1.424     albertel 5485:                                           of existing one
1.423     albertel 5486:                           - 'CODE' 
                   5487:                                'CODE_ignore_dup' - set to true if duplicates
                   5488:                                                    should be ignored.
                   5489: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5490:                                         if the existing unfound code should
1.423     albertel 5491:                                         be used as is
                   5492:                           - 'answer'
                   5493:                                'response' - new answer or 'none' if blank
                   5494:                                'question' - the bubble line to change
1.503     raeburn  5495:                                'questionnum' - the question identifier,
                   5496:                                                may include subquestion. 
1.423     albertel 5497: 
                   5498:   Returns:
                   5499:     $line - the modified scanline
                   5500: 
                   5501:   Side effects: 
                   5502:     $scan_data - may be updated
                   5503: 
                   5504: =cut
                   5505: 
1.82      albertel 5506: 
1.157     albertel 5507: sub scantron_fixup_scanline {
                   5508:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5509:     if ($field eq 'ID') {
                   5510: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5511: 	    return ($line,1,'New value too large');
1.157     albertel 5512: 	}
                   5513: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5514: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5515: 				     $args->{'newid'});
                   5516: 	}
                   5517: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5518: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5519: 	if ($args->{'newid'}=~/^\s*$/) {
                   5520: 	    &scan_data($scan_data,"$whichline.user",
                   5521: 		       $args->{'username'}.':'.$args->{'domain'});
                   5522: 	}
1.186     albertel 5523:     } elsif ($field eq 'CODE') {
1.192     albertel 5524: 	if ($args->{'CODE_ignore_dup'}) {
                   5525: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5526: 	}
                   5527: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5528: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5529: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5530: 		return ($line,1,'New CODE value too large');
                   5531: 	    }
                   5532: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5533: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5534: 	    }
                   5535: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5536: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5537: 	}
1.157     albertel 5538:     } elsif ($field eq 'answer') {
1.497     foxr     5539: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5540: 	my $off=$scantron_config->{'Qoff'};
                   5541: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5542: 	my $answer=${off}x$length;
                   5543: 	if ($args->{'response'} eq 'none') {
                   5544: 	    &scan_data($scan_data,
1.503     raeburn  5545: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5546: 	} else {
                   5547: 	    if ($on eq 'letter') {
                   5548: 		my @alphabet=('A'..'Z');
                   5549: 		$answer=$alphabet[$args->{'response'}];
                   5550: 	    } elsif ($on eq 'number') {
                   5551: 		$answer=$args->{'response'}+1;
                   5552: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5553: 	    } else {
1.497     foxr     5554: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5555: 	    }
1.497     foxr     5556: 	    &scan_data($scan_data,
1.503     raeburn  5557: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5558: 	}
1.497     foxr     5559: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5560: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5561:     }
                   5562:     return $line;
                   5563: }
1.423     albertel 5564: 
                   5565: =pod
                   5566: 
                   5567: =item scan_data
                   5568: 
                   5569:     Edit or look up  an item in the scan_data hash.
                   5570: 
                   5571:   Arguments:
                   5572:     $scan_data  - The hash (see scantron_getfile)
                   5573:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5574:                   scantronfilename_key).
1.423     albertel 5575:     $data        - New value of the hash entry.
                   5576:     $delete      - If true, the entry is removed from the hash.
                   5577: 
                   5578:   Returns:
                   5579:     The new value of the hash table field (undefined if deleted).
                   5580: 
                   5581: =cut
                   5582: 
                   5583: 
1.157     albertel 5584: sub scan_data {
                   5585:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5586:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5587:     if (defined($value)) {
                   5588: 	$scan_data->{$filename.'_'.$key} = $value;
                   5589:     }
                   5590:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5591:     return $scan_data->{$filename.'_'.$key};
                   5592: }
1.423     albertel 5593: 
1.495     albertel 5594: # ----- These first few routines are general use routines.----
                   5595: 
                   5596: # Return the number of occurences of a pattern in a string.
                   5597: 
                   5598: sub occurence_count {
                   5599:     my ($string, $pattern) = @_;
                   5600: 
                   5601:     my @matches = ($string =~ /$pattern/g);
                   5602: 
                   5603:     return scalar(@matches);
                   5604: }
                   5605: 
                   5606: 
                   5607: # Take a string known to have digits and convert all the
                   5608: # digits into letters in the range J,A..I.
                   5609: 
                   5610: sub digits_to_letters {
                   5611:     my ($input) = @_;
                   5612: 
                   5613:     my @alphabet = ('J', 'A'..'I');
                   5614: 
                   5615:     my @input    = split(//, $input);
                   5616:     my $output ='';
                   5617:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5618: 	if ($input[$i] =~ /\d/) {
                   5619: 	    $output .= $alphabet[$input[$i]];
                   5620: 	} else {
                   5621: 	    $output .= $input[$i];
                   5622: 	}
                   5623:     }
                   5624:     return $output;
                   5625: }
                   5626: 
1.423     albertel 5627: =pod 
                   5628: 
                   5629: =item scantron_parse_scanline
                   5630: 
                   5631:   Decodes a scanline from the selected scantron file
                   5632: 
                   5633:  Arguments:
                   5634:     line             - The text of the scantron file line to process
                   5635:     whichline        - Line number
                   5636:     scantron_config  - Hash describing the format of the scantron lines.
                   5637:     scan_data        - Hash of extra information about the scanline
                   5638:                        (see scantron_getfile for more information)
                   5639:     just_header      - True if should not process question answers but only
                   5640:                        the stuff to the left of the answers.
                   5641:  Returns:
                   5642:    Hash containing the result of parsing the scanline
                   5643: 
                   5644:    Keys are all proceeded by the string 'scantron.'
                   5645: 
                   5646:        CODE    - the CODE in use for this scanline
                   5647:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5648:                  by the operator
                   5649:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5650:                             CODEs were selected, but the usage has been
                   5651:                             forced by the operator
1.556     weissno  5652:        ID  - student/employee ID
1.423     albertel 5653:        PaperID - if used, the ID number printed on the sheet when the 
                   5654:                  paper was scanned
                   5655:        FirstName - first name from the sheet
                   5656:        LastName  - last name from the sheet
                   5657: 
                   5658:      if just_header was not true these key may also exist
                   5659: 
1.447     foxr     5660:        missingerror - a list of bubble ranges that are considered to be answers
                   5661:                       to a single question that don't have any bubbles filled in.
                   5662:                       Of the form questionnumber:firstbubblenumber:count.
                   5663:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5664:                       to a single question that have more than one bubble filled in.
                   5665:                       Of the form questionnumber::firstbubblenumber:count
                   5666:    
                   5667:                 In the above, count is the number of bubble responses in the
                   5668:                 input line needed to represent the possible answers to the question.
                   5669:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5670:                 per line would have count = 2.
                   5671: 
1.423     albertel 5672:        maxquest     - the number of the last bubble line that was parsed
                   5673: 
                   5674:        (<number> starts at 1)
                   5675:        <number>.answer - zero or more letters representing the selected
                   5676:                          letters from the scanline for the bubble line 
                   5677:                          <number>.
                   5678:                          if blank there was either no bubble or there where
                   5679:                          multiple bubbles, (consult the keys missingerror and
                   5680:                          doubleerror if this is an error condition)
                   5681: 
                   5682: =cut
                   5683: 
1.82      albertel 5684: sub scantron_parse_scanline {
1.423     albertel 5685:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5686: 
1.82      albertel 5687:     my %record;
1.550     raeburn  5688:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5689:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5690:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5691:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5692: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5693: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5694: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5695: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5696: 	    $record{'scantron.CODE'}=substr($data,
                   5697: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5698: 					    $$scantron_config{'CODElength'});
1.191     albertel 5699: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5700: 		$record{'scantron.useCODE'}=1;
                   5701: 	    }
1.192     albertel 5702: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5703: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5704: 	    }
1.82      albertel 5705: 	} else {
                   5706: 	    #FIXME interpret first N questions
                   5707: 	}
                   5708:     }
1.83      albertel 5709:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5710: 				  $$scantron_config{'IDlength'});
1.157     albertel 5711:     $record{'scantron.PaperID'}=
                   5712: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5713: 	       $$scantron_config{'PaperIDlength'});
                   5714:     $record{'scantron.FirstName'}=
                   5715: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5716: 	       $$scantron_config{'FirstNamelength'});
                   5717:     $record{'scantron.LastName'}=
                   5718: 	substr($data,$$scantron_config{'LastName'}-1,
                   5719: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5720:     if ($just_header) { return \%record; }
1.194     albertel 5721: 
1.82      albertel 5722:     my @alphabet=('A'..'Z');
                   5723:     my $questnum=0;
1.447     foxr     5724:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5725: 
1.470     foxr     5726:     chomp($questions);		# Get rid of any trailing \n.
                   5727:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5728:     while (length($questions)) {
1.447     foxr     5729: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5730:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5731:                              || 1;
                   5732:         $questnum++;
                   5733:         my $quest_id = $questnum;
                   5734:         my $currentquest = substr($questions,0,$answer_length);
                   5735:         $questions       = substr($questions,$answer_length);
                   5736:         if (length($currentquest) < $answer_length) { next; }
                   5737: 
                   5738:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5739:             my $subquestnum = 1;
                   5740:             my $subquestions = $currentquest;
                   5741:             my @subanswers_needed = 
                   5742:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5743:             foreach my $subans (@subanswers_needed) {
                   5744:                 my $subans_length =
                   5745:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5746:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5747:                 $subquestions   = substr($subquestions,$subans_length);
                   5748:                 $quest_id = "$questnum.$subquestnum";
                   5749:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5750:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5751:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5752:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5753:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5754:                 } else {
                   5755:                     $ansnum = &scantron_validator_positional($ansnum,
                   5756:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5757:                 }
                   5758:                 $subquestnum ++;
                   5759:             }
                   5760:         } else {
                   5761:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5762:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5763:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5764:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5765:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5766:             } else {
                   5767:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5768:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5769:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5770:             }
                   5771:         }
                   5772:     }
                   5773:     $record{'scantron.maxquest'}=$questnum;
                   5774:     return \%record;
                   5775: }
1.447     foxr     5776: 
1.503     raeburn  5777: sub scantron_validator_lettnum {
                   5778:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5779:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5780: 
                   5781:     # Qon 'letter' implies for each slot in currquest we have:
                   5782:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5783:     #    about anything else (esp. a value of Qoff) for missing
                   5784:     #    bubbles.
                   5785:     #
                   5786:     # Qon 'number' implies each slot gives a digit that indexes the
                   5787:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5788:     #    and * or ? for double bubbles on a single line.
                   5789:     #
1.447     foxr     5790: 
1.503     raeburn  5791:     my $matchon;
                   5792:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5793:         $matchon = '[A-Z]';
                   5794:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5795:         $matchon = '\d';
                   5796:     }
                   5797:     my $occurrences = 0;
                   5798:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5799:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5800:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5801:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5802:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5803:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5804:         my @singlelines = split('',$currquest);
                   5805:         foreach my $entry (@singlelines) {
                   5806:             $occurrences = &occurence_count($entry,$matchon);
                   5807:             if ($occurrences > 1) {
                   5808:                 last;
                   5809:             }
                   5810:         } 
                   5811:     } else {
                   5812:         $occurrences = &occurence_count($currquest,$matchon); 
                   5813:     }
                   5814:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5815:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5816:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5817:             my $bubble = substr($currquest,$ans,1);
                   5818:             if ($bubble =~ /$matchon/ ) {
                   5819:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5820:                     if ($bubble == 0) {
                   5821:                         $bubble = 10; 
                   5822:                     }
                   5823:                     $record->{"scantron.$ansnum.answer"} = 
                   5824:                         $alphabet->[$bubble-1];
                   5825:                 } else {
                   5826:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5827:                 }
                   5828:             } else {
                   5829:                 $record->{"scantron.$ansnum.answer"}='';
                   5830:             }
                   5831:             $ansnum++;
                   5832:         }
                   5833:     } elsif (!defined($currquest)
                   5834:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5835:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5836:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5837:             $record->{"scantron.$ansnum.answer"}='';
                   5838:             $ansnum++;
                   5839:         }
                   5840:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5841:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5842:         }
                   5843:     } else {
                   5844:         if ($$scantron_config{'Qon'} eq 'number') {
                   5845:             $currquest = &digits_to_letters($currquest);            
                   5846:         }
                   5847:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5848:             my $bubble = substr($currquest,$ans,1);
                   5849:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5850:             $ansnum++;
                   5851:         }
                   5852:     }
                   5853:     return $ansnum;
                   5854: }
1.447     foxr     5855: 
1.503     raeburn  5856: sub scantron_validator_positional {
                   5857:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5858:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5859: 
1.503     raeburn  5860:     # Otherwise there's a positional notation;
                   5861:     # each bubble line requires Qlength items, and there are filled in
                   5862:     # bubbles for each case where there 'Qon' characters.
                   5863:     #
1.447     foxr     5864: 
1.503     raeburn  5865:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5866: 
1.503     raeburn  5867:     # If the split only gives us one element.. the full length of the
                   5868:     # answer string, no bubbles are filled in:
1.447     foxr     5869: 
1.507     raeburn  5870:     if ($answers_needed eq '') {
                   5871:         return;
                   5872:     }
                   5873: 
1.503     raeburn  5874:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5875:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5876:             $record->{"scantron.$ansnum.answer"}='';
                   5877:             $ansnum++;
                   5878:         }
                   5879:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5880:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5881:         }
                   5882:     } elsif (scalar(@array) == 2) {
                   5883:         my $location = length($array[0]);
                   5884:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5885:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5886:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5887:             if ($ans eq $line_num) {
                   5888:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5889:             } else {
                   5890:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5891:             }
                   5892:             $ansnum++;
                   5893:          }
                   5894:     } else {
                   5895:         #  If there's more than one instance of a bubble character
                   5896:         #  That's a double bubble; with positional notation we can
                   5897:         #  record all the bubbles filled in as well as the
                   5898:         #  fact this response consists of multiple bubbles.
                   5899:         #
                   5900:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5901:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5902:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5903:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5904:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5905:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5906:             my $doubleerror = 0;
                   5907:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5908:                    (!$doubleerror)) {
                   5909:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5910:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5911:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5912:                if (length(@currarray) > 2) {
                   5913:                    $doubleerror = 1;
                   5914:                } 
                   5915:             }
                   5916:             if ($doubleerror) {
                   5917:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5918:             }
                   5919:         } else {
                   5920:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5921:         }
                   5922:         my $item = $ansnum;
                   5923:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5924:             $record->{"scantron.$item.answer"} = '';
                   5925:             $item ++;
                   5926:         }
1.447     foxr     5927: 
1.503     raeburn  5928:         my @ans=@array;
                   5929:         my $i=0;
                   5930:         my $increment = 0;
                   5931:         while ($#ans) {
                   5932:             $i+=length($ans[0]) + $increment;
                   5933:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5934:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5935:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5936:             shift(@ans);
                   5937:             $increment = 1;
                   5938:         }
                   5939:         $ansnum += $answers_needed;
1.82      albertel 5940:     }
1.503     raeburn  5941:     return $ansnum;
1.82      albertel 5942: }
                   5943: 
1.423     albertel 5944: =pod
                   5945: 
                   5946: =item scantron_add_delay
                   5947: 
                   5948:    Adds an error message that occurred during the grading phase to a
                   5949:    queue of messages to be shown after grading pass is complete
                   5950: 
                   5951:  Arguments:
1.424     albertel 5952:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5953:    $scanline    - the scanline that caused the error
                   5954:    $errormesage - the error message
                   5955:    $errorcode   - a numeric code for the error
                   5956: 
                   5957:  Side Effects:
1.424     albertel 5958:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5959: 
                   5960: =cut
                   5961: 
1.82      albertel 5962: sub scantron_add_delay {
1.140     albertel 5963:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5964:     push(@$delayqueue,
                   5965: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5966: 	  'ecode' => $errorcode }
                   5967: 	 );
1.82      albertel 5968: }
                   5969: 
1.423     albertel 5970: =pod
                   5971: 
                   5972: =item scantron_find_student
                   5973: 
1.424     albertel 5974:    Finds the username for the current scanline
                   5975: 
                   5976:   Arguments:
                   5977:    $scantron_record - hash result from scantron_parse_scanline
                   5978:    $scan_data       - hash of correction information 
                   5979:                       (see &scantron_getfile() form more information)
                   5980:    $idmap           - hash from &username_to_idmap()
                   5981:    $line            - number of current scanline
                   5982:  
                   5983:   Returns:
                   5984:    Either 'username:domain' or undef if unknown
                   5985: 
1.423     albertel 5986: =cut
                   5987: 
1.82      albertel 5988: sub scantron_find_student {
1.157     albertel 5989:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5990:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5991:     if ($scanID =~ /^\s*$/) {
                   5992:  	return &scan_data($scan_data,"$line.user");
                   5993:     }
1.83      albertel 5994:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5995:  	if (lc($id) eq lc($scanID)) {
                   5996:  	    return $$idmap{$id};
                   5997:  	}
1.83      albertel 5998:     }
                   5999:     return undef;
                   6000: }
                   6001: 
1.423     albertel 6002: =pod
                   6003: 
                   6004: =item scantron_filter
                   6005: 
1.424     albertel 6006:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6007:    hidden resources was selected
                   6008: 
1.423     albertel 6009: =cut
                   6010: 
1.83      albertel 6011: sub scantron_filter {
                   6012:     my ($curres)=@_;
1.331     albertel 6013: 
                   6014:     if (ref($curres) && $curres->is_problem()) {
                   6015: 	# if the user has asked to not have either hidden
                   6016: 	# or 'randomout' controlled resources to be graded
                   6017: 	# don't include them
                   6018: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6019: 	    && $curres->randomout) {
                   6020: 	    return 0;
                   6021: 	}
1.83      albertel 6022: 	return 1;
                   6023:     }
                   6024:     return 0;
1.82      albertel 6025: }
                   6026: 
1.423     albertel 6027: =pod
                   6028: 
                   6029: =item scantron_process_corrections
                   6030: 
1.424     albertel 6031:    Gets correction information out of submitted form data and corrects
                   6032:    the scanline
                   6033: 
1.423     albertel 6034: =cut
                   6035: 
1.157     albertel 6036: sub scantron_process_corrections {
                   6037:     my ($r) = @_;
1.257     albertel 6038:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6039:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6040:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6041:     my $which=$env{'form.scantron_line'};
1.200     albertel 6042:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6043:     my ($skip,$err,$errmsg);
1.257     albertel 6044:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6045: 	$skip=1;
1.257     albertel 6046:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6047: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6048: 	    $env{'form.scantron_domain'};
1.157     albertel 6049: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6050: 	($line,$err,$errmsg)=
                   6051: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6052: 				     'ID',{'newid'=>$newid,
1.257     albertel 6053: 				    'username'=>$env{'form.scantron_username'},
                   6054: 				    'domain'=>$env{'form.scantron_domain'}});
                   6055:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6056: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6057: 	my $newCODE;
1.192     albertel 6058: 	my %args;
1.190     albertel 6059: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6060: 	    $newCODE='use_unfound';
1.190     albertel 6061: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6062: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6063: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6064: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6065: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6066: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6067: 	}
1.257     albertel 6068: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6069: 	    $args{'CODE_ignore_dup'}=1;
                   6070: 	}
                   6071: 	$args{'CODE'}=$newCODE;
1.186     albertel 6072: 	($line,$err,$errmsg)=
                   6073: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6074: 				     'CODE',\%args);
1.257     albertel 6075:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6076: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6077: 	    ($line,$err,$errmsg)=
                   6078: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6079: 					 $which,'answer',
                   6080: 					 { 'question'=>$question,
1.503     raeburn  6081: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6082:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6083: 	    if ($err) { last; }
                   6084: 	}
                   6085:     }
                   6086:     if ($err) {
1.398     albertel 6087: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6088:     } else {
1.200     albertel 6089: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6090: 	&scantron_putfile($scanlines,$scan_data);
                   6091:     }
                   6092: }
                   6093: 
1.423     albertel 6094: =pod
                   6095: 
                   6096: =item reset_skipping_status
                   6097: 
1.424     albertel 6098:    Forgets the current set of remember skipped scanlines (and thus
                   6099:    reverts back to considering all lines in the
                   6100:    scantron_skipped_<filename> file)
                   6101: 
1.423     albertel 6102: =cut
                   6103: 
1.200     albertel 6104: sub reset_skipping_status {
                   6105:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6106:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6107:     &scantron_putfile(undef,$scan_data);
                   6108: }
                   6109: 
1.423     albertel 6110: =pod
                   6111: 
                   6112: =item start_skipping
                   6113: 
1.424     albertel 6114:    Marks a scanline to be skipped. 
                   6115: 
1.423     albertel 6116: =cut
                   6117: 
1.376     albertel 6118: sub start_skipping {
1.200     albertel 6119:     my ($scan_data,$i)=@_;
                   6120:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6121:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6122: 	$remembered{$i}=2;
                   6123:     } else {
                   6124: 	$remembered{$i}=1;
                   6125:     }
1.200     albertel 6126:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item should_be_skipped
                   6132: 
1.424     albertel 6133:    Checks whether a scanline should be skipped.
                   6134: 
1.423     albertel 6135: =cut
                   6136: 
1.200     albertel 6137: sub should_be_skipped {
1.376     albertel 6138:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6139:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6140: 	# not redoing old skips
1.376     albertel 6141: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6142: 	return 0;
                   6143:     }
                   6144:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6145: 
                   6146:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6147: 	return 0;
                   6148:     }
1.200     albertel 6149:     return 1;
                   6150: }
                   6151: 
1.423     albertel 6152: =pod
                   6153: 
                   6154: =item remember_current_skipped
                   6155: 
1.424     albertel 6156:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6157:    file and remembers them into scan_data for later use.
                   6158: 
1.423     albertel 6159: =cut
                   6160: 
1.200     albertel 6161: sub remember_current_skipped {
                   6162:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6163:     my %to_remember;
                   6164:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6165: 	if ($scanlines->{'skipped'}[$i]) {
                   6166: 	    $to_remember{$i}=1;
                   6167: 	}
                   6168:     }
1.376     albertel 6169: 
1.200     albertel 6170:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6171:     &scantron_putfile(undef,$scan_data);
                   6172: }
                   6173: 
1.423     albertel 6174: =pod
                   6175: 
                   6176: =item check_for_error
                   6177: 
1.424     albertel 6178:     Checks if there was an error when attempting to remove a specific
                   6179:     scantron_.. bubble sheet data file. Prints out an error if
                   6180:     something went wrong.
                   6181: 
1.423     albertel 6182: =cut
                   6183: 
1.200     albertel 6184: sub check_for_error {
                   6185:     my ($r,$result)=@_;
                   6186:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6187: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6188:     }
                   6189: }
1.157     albertel 6190: 
1.423     albertel 6191: =pod
                   6192: 
                   6193: =item scantron_warning_screen
                   6194: 
1.424     albertel 6195:    Interstitial screen to make sure the operator has selected the
                   6196:    correct options before we start the validation phase.
                   6197: 
1.423     albertel 6198: =cut
                   6199: 
1.203     albertel 6200: sub scantron_warning_screen {
1.650     raeburn  6201:     my ($button_text,$symb)=@_;
1.257     albertel 6202:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6204:     my $CODElist;
1.284     albertel 6205:     if ($scantron_config{'CODElocation'} &&
                   6206: 	$scantron_config{'CODEstart'} &&
                   6207: 	$scantron_config{'CODElength'}) {
                   6208: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6209: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6210: 	$CODElist=
1.492     albertel 6211: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6212: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6213:     }
1.492     albertel 6214:     return ('
1.203     albertel 6215: <p>
1.492     albertel 6216: <span class="LC_warning">
                   6217: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6218: </p>
                   6219: <table>
1.492     albertel 6220: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6221: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6222: '.$CODElist.'
1.203     albertel 6223: </table>
1.650     raeburn  6224: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6225: '.&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 6226: 
                   6227: <br />
1.492     albertel 6228: ');
1.203     albertel 6229: }
                   6230: 
1.423     albertel 6231: =pod
                   6232: 
                   6233: =item scantron_do_warning
                   6234: 
1.424     albertel 6235:    Check if the operator has picked something for all required
                   6236:    fields. Error out if something is missing.
                   6237: 
1.423     albertel 6238: =cut
                   6239: 
1.203     albertel 6240: sub scantron_do_warning {
1.608     www      6241:     my ($r,$symb)=@_;
1.203     albertel 6242:     if (!$symb) {return '';}
1.324     albertel 6243:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6244:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6245:     if ( $env{'form.selectpage'} eq '' ||
                   6246: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6247: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6248: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6249: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6250: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6251: 	} 
1.257     albertel 6252: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6253: 	    $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 6254: 	} 
1.257     albertel 6255: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6256: 	    $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 6257: 	} 
                   6258:     } else {
1.650     raeburn  6259: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.492     albertel 6260: 	$r->print('
                   6261: '.$warning.'
                   6262: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6263: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6264: ');
1.237     albertel 6265:     }
1.614     www      6266:     $r->print("</form><br />");
1.203     albertel 6267:     return '';
                   6268: }
                   6269: 
1.423     albertel 6270: =pod
                   6271: 
                   6272: =item scantron_form_start
                   6273: 
1.424     albertel 6274:     html hidden input for remembering all selected grading options
                   6275: 
1.423     albertel 6276: =cut
                   6277: 
1.203     albertel 6278: sub scantron_form_start {
                   6279:     my ($max_bubble)=@_;
                   6280:     my $result= <<SCANTRONFORM;
                   6281: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6282:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6283:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6284:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6285:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6286:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6287:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6288:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6289:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6290:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6291: SCANTRONFORM
1.447     foxr     6292: 
                   6293:   my $line = 0;
                   6294:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6295:        my $chunk =
                   6296: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6297:        $chunk .=
                   6298: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6299:        $chunk .= 
                   6300:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6301:        $chunk .=
                   6302:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6303:        $result .= $chunk;
                   6304:        $line++;
                   6305:    }
1.203     albertel 6306:     return $result;
                   6307: }
                   6308: 
1.423     albertel 6309: =pod
                   6310: 
                   6311: =item scantron_validate_file
                   6312: 
1.424     albertel 6313:     Dispatch routine for doing validation of a bubble sheet data file.
                   6314: 
                   6315:     Also processes any necessary information resets that need to
                   6316:     occur before validation begins (ignore previous corrections,
                   6317:     restarting the skipped records processing)
                   6318: 
1.423     albertel 6319: =cut
                   6320: 
1.157     albertel 6321: sub scantron_validate_file {
1.608     www      6322:     my ($r,$symb) = @_;
1.157     albertel 6323:     if (!$symb) {return '';}
1.324     albertel 6324:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6325:     
                   6326:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6327:     # them when doing the corrections reset
1.257     albertel 6328:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6329: 	&reset_skipping_status();
                   6330:     }
1.257     albertel 6331:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6332: 	&remember_current_skipped();
1.257     albertel 6333: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6334:     }
                   6335: 
1.257     albertel 6336:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6337: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6338: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6339: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6340: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6341:     }
1.200     albertel 6342: 
1.257     albertel 6343:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6344: 	&scantron_process_corrections($r);
                   6345:     }
1.503     raeburn  6346:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6347:     #get the student pick code ready
                   6348:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6349:     my $nav_error;
1.649     raeburn  6350:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6351:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6352:     if ($nav_error) {
                   6353:         $r->print(&navmap_errormsg());
                   6354:         return '';
                   6355:     }
1.203     albertel 6356:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6357:     $r->print($result);
                   6358:     
1.334     albertel 6359:     my @validate_phases=( 'sequence',
                   6360: 			  'ID',
1.157     albertel 6361: 			  'CODE',
                   6362: 			  'doublebubble',
                   6363: 			  'missingbubbles');
1.257     albertel 6364:     if (!$env{'form.validatepass'}) {
                   6365: 	$env{'form.validatepass'} = 0;
1.157     albertel 6366:     }
1.257     albertel 6367:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6368: 
1.448     foxr     6369: 
1.157     albertel 6370:     my $stop=0;
                   6371:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6372: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6373: 	$r->rflush();
                   6374: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6375: 	{
                   6376: 	    no strict 'refs';
                   6377: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6378: 	}
                   6379:     }
                   6380:     if (!$stop) {
1.650     raeburn  6381: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6382: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6383:                   $warning.
                   6384:                   &mt('Perform verification for each student after storage of submissions?').
                   6385:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6386:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6387:                   ('&nbsp;'x3).'<label>'.
                   6388:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6389:                   '</label></span><br />'.
                   6390:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6391:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6392:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6393:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6394:     } else {
                   6395: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6396: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6397:     }
                   6398:     if ($stop) {
1.334     albertel 6399: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6400: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6401: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6402: 
1.650     raeburn  6403: 	    $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 6404: 	} else {
1.503     raeburn  6405:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6406: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6407:             } else {
1.539     riegler  6408:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6409:             }
1.492     albertel 6410: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6411: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6412: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6413: 	}
1.157     albertel 6414:     }
1.614     www      6415:     $r->print(" </form><br />");
1.157     albertel 6416:     return '';
                   6417: }
                   6418: 
1.423     albertel 6419: 
                   6420: =pod
                   6421: 
                   6422: =item scantron_remove_file
                   6423: 
1.424     albertel 6424:    Removes the requested bubble sheet data file, makes sure that
                   6425:    scantron_original_<filename> is never removed
                   6426: 
                   6427: 
1.423     albertel 6428: =cut
                   6429: 
1.200     albertel 6430: sub scantron_remove_file {
1.192     albertel 6431:     my ($which)=@_;
1.257     albertel 6432:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6433:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6434:     my $file='scantron_';
1.200     albertel 6435:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6436: 	$file.=$which.'_';
1.192     albertel 6437:     } else {
                   6438: 	return 'refused';
                   6439:     }
1.257     albertel 6440:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6441:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6442: }
                   6443: 
1.423     albertel 6444: 
                   6445: =pod
                   6446: 
                   6447: =item scantron_remove_scan_data
                   6448: 
1.424     albertel 6449:    Removes all scan_data correction for the requested bubble sheet
                   6450:    data file.  (In the case that both the are doing skipped records we need
                   6451:    to remember the old skipped lines for the time being so that element
                   6452:    persists for a while.)
                   6453: 
1.423     albertel 6454: =cut
                   6455: 
1.200     albertel 6456: sub scantron_remove_scan_data {
1.257     albertel 6457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6459:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6460:     my @todelete;
1.257     albertel 6461:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6462:     foreach my $key (@keys) {
                   6463: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6464: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6465: 		$key=~/remember_skipping/) {
                   6466: 		next;
                   6467: 	    }
1.192     albertel 6468: 	    push(@todelete,$key);
                   6469: 	}
                   6470:     }
1.200     albertel 6471:     my $result;
1.192     albertel 6472:     if (@todelete) {
1.491     albertel 6473: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6474: 				       \@todelete,$cdom,$cname);
                   6475:     } else {
                   6476: 	$result = 'ok';
1.192     albertel 6477:     }
                   6478:     return $result;
                   6479: }
                   6480: 
1.423     albertel 6481: 
                   6482: =pod
                   6483: 
                   6484: =item scantron_getfile
                   6485: 
1.424     albertel 6486:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6487:     the scan_data hash
                   6488:   
                   6489:   Arguments:
                   6490:     None
                   6491: 
                   6492:   Returns:
                   6493:     2 hash references
                   6494: 
                   6495:      - first one has 
                   6496:          orig      -
                   6497:          corrected -
                   6498:          skipped   -  each of which points to an array ref of the specified
                   6499:                       file broken up into individual lines
                   6500:          count     - number of scanlines
                   6501:  
                   6502:      - second is the scan_data hash possible keys are
1.425     albertel 6503:        ($number refers to scanline numbered $number and thus the key affects
                   6504:         only that scanline
                   6505:         $bubline refers to the specific bubble line element and the aspects
                   6506:         refers to that specific bubble line element)
                   6507: 
                   6508:        $number.user - username:domain to use
                   6509:        $number.CODE_ignore_dup 
                   6510:                     - ignore the duplicate CODE error 
                   6511:        $number.useCODE
                   6512:                     - use the CODE in the scanline as is
                   6513:        $number.no_bubble.$bubline
                   6514:                     - it is valid that there is no bubbled in bubble
                   6515:                       at $number $bubline
                   6516:        remember_skipping
                   6517:                     - a frozen hash containing keys of $number and values
                   6518:                       of either 
                   6519:                         1 - we are on a 'do skipped records pass' and plan
                   6520:                             on processing this line
                   6521:                         2 - we are on a 'do skipped records pass' and this
                   6522:                             scanline has been marked to skip yet again
1.424     albertel 6523: 
1.423     albertel 6524: =cut
                   6525: 
1.157     albertel 6526: sub scantron_getfile {
1.200     albertel 6527:     #FIXME really would prefer a scantron directory
1.257     albertel 6528:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6530:     my $lines;
                   6531:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6532: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6533:     my %scanlines;
                   6534:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6535:     my $temp=$scanlines{'orig'};
                   6536:     $scanlines{'count'}=$#$temp;
                   6537: 
                   6538:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6539: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6540:     if ($lines eq '-1') {
                   6541: 	$scanlines{'corrected'}=[];
                   6542:     } else {
                   6543: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6544:     }
                   6545:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6546: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6547:     if ($lines eq '-1') {
                   6548: 	$scanlines{'skipped'}=[];
                   6549:     } else {
                   6550: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6551:     }
1.175     albertel 6552:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6553:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6554:     my %scan_data = @tmp;
                   6555:     return (\%scanlines,\%scan_data);
                   6556: }
                   6557: 
1.423     albertel 6558: =pod
                   6559: 
                   6560: =item lonnet_putfile
                   6561: 
1.424     albertel 6562:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6563: 
                   6564:  Arguments:
                   6565:    $contents - data to store
                   6566:    $filename - filename to store $contents into
                   6567: 
                   6568:  Returns:
                   6569:    result value from &Apache::lonnet::finishuserfileupload
                   6570: 
1.423     albertel 6571: =cut
                   6572: 
1.157     albertel 6573: sub lonnet_putfile {
                   6574:     my ($contents,$filename)=@_;
1.257     albertel 6575:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6576:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6577:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6578:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6579: 
                   6580: }
                   6581: 
1.423     albertel 6582: =pod
                   6583: 
                   6584: =item scantron_putfile
                   6585: 
1.424     albertel 6586:     Stores the current version of the bubble sheet data files, and the
                   6587:     scan_data hash. (Does not modify the original version only the
                   6588:     corrected and skipped versions.
                   6589: 
                   6590:  Arguments:
                   6591:     $scanlines - hash ref that looks like the first return value from
                   6592:                  &scantron_getfile()
                   6593:     $scan_data - hash ref that looks like the second return value from
                   6594:                  &scantron_getfile()
                   6595: 
1.423     albertel 6596: =cut
                   6597: 
1.157     albertel 6598: sub scantron_putfile {
                   6599:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6600:     #FIXME really would prefer a scantron directory
1.257     albertel 6601:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6602:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6603:     if ($scanlines) {
                   6604: 	my $prefix='scantron_';
1.157     albertel 6605: # no need to update orig, shouldn't change
                   6606: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6607: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6608: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6609: 			$prefix.'corrected_'.
1.257     albertel 6610: 			$env{'form.scantron_selectfile'});
1.200     albertel 6611: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6612: 			$prefix.'skipped_'.
1.257     albertel 6613: 			$env{'form.scantron_selectfile'});
1.200     albertel 6614:     }
1.175     albertel 6615:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6616: }
                   6617: 
1.423     albertel 6618: =pod
                   6619: 
                   6620: =item scantron_get_line
                   6621: 
1.424     albertel 6622:    Returns the correct version of the scanline
                   6623: 
                   6624:  Arguments:
                   6625:     $scanlines - hash ref that looks like the first return value from
                   6626:                  &scantron_getfile()
                   6627:     $scan_data - hash ref that looks like the second return value from
                   6628:                  &scantron_getfile()
                   6629:     $i         - number of the requested line (starts at 0)
                   6630: 
                   6631:  Returns:
                   6632:    A scanline, (either the original or the corrected one if it
                   6633:    exists), or undef if the requested scanline should be
                   6634:    skipped. (Either because it's an skipped scanline, or it's an
                   6635:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6636:    pass.
                   6637: 
1.423     albertel 6638: =cut
                   6639: 
1.157     albertel 6640: sub scantron_get_line {
1.200     albertel 6641:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6642:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6643:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6644:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6645:     return $scanlines->{'orig'}[$i]; 
                   6646: }
                   6647: 
1.423     albertel 6648: =pod
                   6649: 
                   6650: =item scantron_todo_count
                   6651: 
1.424     albertel 6652:     Counts the number of scanlines that need processing.
                   6653: 
                   6654:  Arguments:
                   6655:     $scanlines - hash ref that looks like the first return value from
                   6656:                  &scantron_getfile()
                   6657:     $scan_data - hash ref that looks like the second return value from
                   6658:                  &scantron_getfile()
                   6659: 
                   6660:  Returns:
                   6661:     $count - number of scanlines to process
                   6662: 
1.423     albertel 6663: =cut
                   6664: 
1.200     albertel 6665: sub get_todo_count {
                   6666:     my ($scanlines,$scan_data)=@_;
                   6667:     my $count=0;
                   6668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6670: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6671: 	$count++;
                   6672:     }
                   6673:     return $count;
                   6674: }
                   6675: 
1.423     albertel 6676: =pod
                   6677: 
                   6678: =item scantron_put_line
                   6679: 
1.424     albertel 6680:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6681:     data file.
                   6682: 
                   6683:  Arguments:
                   6684:     $scanlines - hash ref that looks like the first return value from
                   6685:                  &scantron_getfile()
                   6686:     $scan_data - hash ref that looks like the second return value from
                   6687:                  &scantron_getfile()
                   6688:     $i         - line number to update
                   6689:     $newline   - contents of the updated scanline
                   6690:     $skip      - if true make the line for skipping and update the
                   6691:                  'skipped' file
                   6692: 
1.423     albertel 6693: =cut
                   6694: 
1.157     albertel 6695: sub scantron_put_line {
1.200     albertel 6696:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6697:     if ($skip) {
                   6698: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6699: 	&start_skipping($scan_data,$i);
1.157     albertel 6700: 	return;
                   6701:     }
                   6702:     $scanlines->{'corrected'}[$i]=$newline;
                   6703: }
                   6704: 
1.423     albertel 6705: =pod
                   6706: 
                   6707: =item scantron_clear_skip
                   6708: 
1.424     albertel 6709:    Remove a line from the 'skipped' file
                   6710: 
                   6711:  Arguments:
                   6712:     $scanlines - hash ref that looks like the first return value from
                   6713:                  &scantron_getfile()
                   6714:     $scan_data - hash ref that looks like the second return value from
                   6715:                  &scantron_getfile()
                   6716:     $i         - line number to update
                   6717: 
1.423     albertel 6718: =cut
                   6719: 
1.376     albertel 6720: sub scantron_clear_skip {
                   6721:     my ($scanlines,$scan_data,$i)=@_;
                   6722:     if (exists($scanlines->{'skipped'}[$i])) {
                   6723: 	undef($scanlines->{'skipped'}[$i]);
                   6724: 	return 1;
                   6725:     }
                   6726:     return 0;
                   6727: }
                   6728: 
1.423     albertel 6729: =pod
                   6730: 
                   6731: =item scantron_filter_not_exam
                   6732: 
1.424     albertel 6733:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6734:    filter out resources that are not marked as 'exam' mode
                   6735: 
1.423     albertel 6736: =cut
                   6737: 
1.334     albertel 6738: sub scantron_filter_not_exam {
                   6739:     my ($curres)=@_;
                   6740:     
                   6741:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6742: 	# if the user has asked to not have either hidden
                   6743: 	# or 'randomout' controlled resources to be graded
                   6744: 	# don't include them
                   6745: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6746: 	    && $curres->randomout) {
                   6747: 	    return 0;
                   6748: 	}
                   6749: 	return 1;
                   6750:     }
                   6751:     return 0;
                   6752: }
                   6753: 
1.423     albertel 6754: =pod
                   6755: 
                   6756: =item scantron_validate_sequence
                   6757: 
1.424     albertel 6758:     Validates the selected sequence, checking for resource that are
                   6759:     not set to exam mode.
                   6760: 
1.423     albertel 6761: =cut
                   6762: 
1.334     albertel 6763: sub scantron_validate_sequence {
                   6764:     my ($r,$currentphase) = @_;
                   6765: 
                   6766:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6767:     unless (ref($navmap)) {
                   6768:         $r->print(&navmap_errormsg());
                   6769:         return (1,$currentphase);
                   6770:     }
1.334     albertel 6771:     my (undef,undef,$sequence)=
                   6772: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6773: 
                   6774:     my $map=$navmap->getResourceByUrl($sequence);
                   6775: 
                   6776:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6777:                                     value="ignore" />');
                   6778:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6779: 	my @resources=
                   6780: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6781: 	if (@resources) {
1.357     banghart 6782: 	    $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 6783: 	    return (1,$currentphase);
                   6784: 	}
                   6785:     }
                   6786: 
                   6787:     return (0,$currentphase+1);
                   6788: }
                   6789: 
1.423     albertel 6790: 
                   6791: 
1.157     albertel 6792: sub scantron_validate_ID {
                   6793:     my ($r,$currentphase) = @_;
                   6794:     
                   6795:     #get student info
                   6796:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6797:     my %idmap=&username_to_idmap($classlist);
                   6798: 
                   6799:     #get scantron line setup
1.257     albertel 6800:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6801:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6802: 
                   6803:     my $nav_error;
1.649     raeburn  6804:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6805:     if ($nav_error) {
                   6806:         $r->print(&navmap_errormsg());
                   6807:         return(1,$currentphase);
                   6808:     }
1.157     albertel 6809: 
                   6810:     my %found=('ids'=>{},'usernames'=>{});
                   6811:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6812: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6813: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6814: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6815: 						 $scan_data);
                   6816: 	my $id=$$scan_record{'scantron.ID'};
                   6817: 	my $found;
                   6818: 	foreach my $checkid (keys(%idmap)) {
                   6819: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6820: 	}
                   6821: 	if ($found) {
                   6822: 	    my $username=$idmap{$found};
                   6823: 	    if ($found{'ids'}{$found}) {
                   6824: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6825: 					 $line,'duplicateID',$found);
1.194     albertel 6826: 		return(1,$currentphase);
1.157     albertel 6827: 	    } elsif ($found{'usernames'}{$username}) {
                   6828: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6829: 					 $line,'duplicateID',$username);
1.194     albertel 6830: 		return(1,$currentphase);
1.157     albertel 6831: 	    }
1.186     albertel 6832: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6833: 	    $found{'ids'}{$found}++;
                   6834: 	    $found{'usernames'}{$username}++;
                   6835: 	} else {
                   6836: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6837: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6838: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6839: 		    &scantron_get_correction($r,$i,$scan_record,
                   6840: 					     \%scantron_config,
                   6841: 					     $line,'duplicateID',$username);
1.194     albertel 6842: 		    return(1,$currentphase);
1.157     albertel 6843: 		} elsif (!defined($username)) {
                   6844: 		    &scantron_get_correction($r,$i,$scan_record,
                   6845: 					     \%scantron_config,
                   6846: 					     $line,'incorrectID');
1.194     albertel 6847: 		    return(1,$currentphase);
1.157     albertel 6848: 		}
                   6849: 		$found{'usernames'}{$username}++;
                   6850: 	    } else {
                   6851: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6852: 					 $line,'incorrectID');
1.194     albertel 6853: 		return(1,$currentphase);
1.157     albertel 6854: 	    }
                   6855: 	}
                   6856:     }
                   6857: 
                   6858:     return (0,$currentphase+1);
                   6859: }
                   6860: 
1.423     albertel 6861: 
1.157     albertel 6862: sub scantron_get_correction {
                   6863:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6864: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6865: #to show both the current line and the previous one and allow skipping
                   6866: #the previous one or the current one
                   6867: 
1.333     albertel 6868:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6869: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6870: 			    " for PaperID <tt>[_1]</tt>",
                   6871: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6872:     } else {
1.492     albertel 6873: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6874: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6875: 			    $i,$line)."</p> \n");
                   6876:     }
                   6877:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6878: 			  "The name on the paper is [_2],[_3]",
                   6879: 			  $$scan_record{'scantron.ID'},
                   6880: 			  $$scan_record{'scantron.LastName'},
                   6881: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6882: 
1.157     albertel 6883:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6884:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6885:                            # Array populated for doublebubble or
                   6886:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6887:                            # to validate radio button checking   
                   6888: 
1.157     albertel 6889:     if ($error =~ /ID$/) {
1.186     albertel 6890: 	if ($error eq 'incorrectID') {
1.492     albertel 6891: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6892: 		      "</p>\n");
1.157     albertel 6893: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6894: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6895: 	}
1.242     albertel 6896: 	$r->print($message);
1.492     albertel 6897: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6898: 	$r->print("\n<ul><li> ");
                   6899: 	#FIXME it would be nice if this sent back the user ID and
                   6900: 	#could do partial userID matches
                   6901: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6902: 				       'scantron_username','scantron_domain'));
                   6903: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6904: 	$r->print("\n@".
1.257     albertel 6905: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6906: 
                   6907: 	$r->print('</li>');
1.186     albertel 6908:     } elsif ($error =~ /CODE$/) {
                   6909: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6910: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6911: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6912: 	    $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 6913: 	}
1.492     albertel 6914: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6915: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6916: 	$r->print($message);
1.492     albertel 6917: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6918: 	$r->print("\n<br /> ");
1.194     albertel 6919: 	my $i=0;
1.273     albertel 6920: 	if ($error eq 'incorrectCODE' 
                   6921: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6922: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6923: 	    if ($closest > 0) {
                   6924: 		foreach my $testcode (@{$closest}) {
                   6925: 		    my $checked='';
1.569     bisitz   6926: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6927: 		    $r->print("
                   6928:    <label>
1.569     bisitz   6929:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6930:        ".&mt("Use the similar CODE [_1] instead.",
                   6931: 	    "<b><tt>".$testcode."</tt></b>")."
                   6932:     </label>
                   6933:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6934: 		    $r->print("\n<br />");
                   6935: 		    $i++;
                   6936: 		}
1.194     albertel 6937: 	    }
                   6938: 	}
1.273     albertel 6939: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6940: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6941: 	    $r->print("
                   6942:     <label>
1.569     bisitz   6943:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6944:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6945: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6946:     </label>");
1.273     albertel 6947: 	    $r->print("\n<br />");
                   6948: 	}
1.194     albertel 6949: 
1.597     wenzelju 6950: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6951: function change_radio(field) {
1.190     albertel 6952:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6953:     var i;
                   6954:     for (i=0;i<slct.length;i++) {
                   6955:         if (slct[i].value==field) { slct[i].checked=true; }
                   6956:     }
                   6957: }
                   6958: ENDSCRIPT
1.187     albertel 6959: 	my $href="/adm/pickcode?".
1.359     www      6960: 	   "form=".&escape("scantronupload").
                   6961: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6962: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6963: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6964: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6965: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6966: 	    $r->print("
                   6967:     <label>
                   6968:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6969:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6970: 	     "<a target='_blank' href='$href'>","</a>")."
                   6971:     </label> 
1.558     bisitz   6972:     ".&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 6973: 	    $r->print("\n<br />");
                   6974: 	}
1.492     albertel 6975: 	$r->print("
                   6976:     <label>
                   6977:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6978:        ".&mt("Use [_1] as the CODE.",
                   6979: 	     "</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 6980: 	$r->print("\n<br /><br />");
1.157     albertel 6981:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6982: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6983: 
                   6984: 	# The form field scantron_questions is acutally a list of line numbers.
                   6985: 	# represented by this form so:
                   6986: 
                   6987: 	my $line_list = &questions_to_line_list($arg);
                   6988: 
1.157     albertel 6989: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6990: 		  $line_list.'" />');
1.242     albertel 6991: 	$r->print($message);
1.492     albertel 6992: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6993: 	foreach my $question (@{$arg}) {
1.503     raeburn  6994: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6995:                                                    $scan_record, $error);
1.524     raeburn  6996:             push(@lines_to_correct,@linenums);
1.157     albertel 6997: 	}
1.503     raeburn  6998:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6999:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7000: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7001: 	$r->print($message);
1.492     albertel 7002: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7003: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7004: 
1.503     raeburn  7005: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7006: 	# a list of question numbers. Therefore:
                   7007: 	#
                   7008: 	
                   7009: 	my $line_list = &questions_to_line_list($arg);
                   7010: 
1.157     albertel 7011: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7012: 		  $line_list.'" />');
1.157     albertel 7013: 	foreach my $question (@{$arg}) {
1.503     raeburn  7014: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7015:                                                    $scan_record, $error);
1.524     raeburn  7016:             push(@lines_to_correct,@linenums);
1.157     albertel 7017: 	}
1.503     raeburn  7018:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7019:     } else {
                   7020: 	$r->print("\n<ul>");
                   7021:     }
                   7022:     $r->print("\n</li></ul>");
1.497     foxr     7023: }
                   7024: 
1.503     raeburn  7025: sub verify_bubbles_checked {
                   7026:     my (@ansnums) = @_;
                   7027:     my $ansnumstr = join('","',@ansnums);
                   7028:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7029:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7030: function verify_bubble_radio(form) {
                   7031:     var ansnumArray = new Array ("$ansnumstr");
                   7032:     var need_bubble_count = 0;
                   7033:     for (var i=0; i<ansnumArray.length; i++) {
                   7034:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7035:             var bubble_picked = 0; 
                   7036:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7037:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7038:                     bubble_picked = 1;
                   7039:                 }
                   7040:             }
                   7041:             if (bubble_picked == 0) {
                   7042:                 need_bubble_count ++;
                   7043:             }
                   7044:         }
                   7045:     }
                   7046:     if (need_bubble_count) {
                   7047:         alert("$warning");
                   7048:         return;
                   7049:     }
                   7050:     form.submit(); 
                   7051: }
                   7052: ENDSCRIPT
                   7053:     return $output;
                   7054: }
                   7055: 
1.497     foxr     7056: =pod
                   7057: 
                   7058: =item  questions_to_line_list
1.157     albertel 7059: 
1.497     foxr     7060: Converts a list of questions into a string of comma separated
                   7061: line numbers in the answer sheet used by the questions.  This is
                   7062: used to fill in the scantron_questions form field.
                   7063: 
                   7064:   Arguments:
                   7065:      questions    - Reference to an array of questions.
                   7066: 
                   7067: =cut
                   7068: 
                   7069: 
                   7070: sub questions_to_line_list {
                   7071:     my ($questions) = @_;
                   7072:     my @lines;
                   7073: 
1.503     raeburn  7074:     foreach my $item (@{$questions}) {
                   7075:         my $question = $item;
                   7076:         my ($first,$count,$last);
                   7077:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7078:             $question = $1;
                   7079:             my $subquestion = $2;
                   7080:             $first = $first_bubble_line{$question-1} + 1;
                   7081:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7082:             my $subcount = 1;
                   7083:             while ($subcount<$subquestion) {
                   7084:                 $first += $subans[$subcount-1];
                   7085:                 $subcount ++;
                   7086:             }
                   7087:             $count = $subans[$subquestion-1];
                   7088:         } else {
                   7089: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7090: 	    $count   = $bubble_lines_per_response{$question-1};
                   7091:         }
1.506     raeburn  7092:         $last = $first+$count-1;
1.503     raeburn  7093:         push(@lines, ($first..$last));
1.497     foxr     7094:     }
                   7095:     return join(',', @lines);
                   7096: }
                   7097: 
                   7098: =pod 
                   7099: 
                   7100: =item prompt_for_corrections
                   7101: 
                   7102: Prompts for a potentially multiline correction to the
                   7103: user's bubbling (factors out common code from scantron_get_correction
                   7104: for multi and missing bubble cases).
                   7105: 
                   7106:  Arguments:
                   7107:    $r           - Apache request object.
                   7108:    $question    - The question number to prompt for.
                   7109:    $scan_config - The scantron file configuration hash.
                   7110:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7111:    $error       - Type of error
1.497     foxr     7112: 
                   7113:  Implicit inputs:
                   7114:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7115:                                   Numbered from 0 (but question numbers are from
                   7116:                                   1.
                   7117:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7118:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7119:                                   type problems render as separate sub-questions, 
1.503     raeburn  7120:                                   in exam mode. This hash contains a 
                   7121:                                   comma-separated list of the lines per 
                   7122:                                   sub-question.
1.510     raeburn  7123:    %responsetype_per_response   - essayresponse, formularesponse,
                   7124:                                   stringresponse, imageresponse, reactionresponse,
                   7125:                                   and organicresponse type problem parts can have
1.503     raeburn  7126:                                   multiple lines per response if the weight
                   7127:                                   assigned exceeds 10.  In this case, only
                   7128:                                   one bubble per line is permitted, but more 
                   7129:                                   than one line might contain bubbles, e.g.
                   7130:                                   bubbling of: line 1 - J, line 2 - J, 
                   7131:                                   line 3 - B would assign 22 points.  
1.497     foxr     7132: 
                   7133: =cut
                   7134: 
                   7135: sub prompt_for_corrections {
1.503     raeburn  7136:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7137:     my ($current_line,$lines);
                   7138:     my @linenums;
                   7139:     my $questionnum = $question;
                   7140:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7141:         $question = $1;
                   7142:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7143:         my $subquestion = $2;
                   7144:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7145:         my $subcount = 1;
                   7146:         while ($subcount<$subquestion) {
                   7147:             $current_line += $subans[$subcount-1];
                   7148:             $subcount ++;
                   7149:         }
                   7150:         $lines = $subans[$subquestion-1];
                   7151:     } else {
                   7152:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7153:         $lines        = $bubble_lines_per_response{$question-1};
                   7154:     }
1.497     foxr     7155:     if ($lines > 1) {
1.503     raeburn  7156:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7157:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7158:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7159:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7160:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7161:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7162:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7163:             $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  7164:         } else {
                   7165:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7166:         }
1.497     foxr     7167:     }
                   7168:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7169:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7170: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7171: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7172:         push(@linenums,$current_line);
1.497     foxr     7173: 	$current_line++;
                   7174:     }
                   7175:     if ($lines > 1) {
                   7176: 	$r->print("<hr /><br />");
                   7177:     }
1.503     raeburn  7178:     return @linenums;
1.157     albertel 7179: }
1.423     albertel 7180: 
                   7181: =pod
                   7182: 
                   7183: =item scantron_bubble_selector
                   7184:   
                   7185:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7186:    possibly showing the existing the selected bubbles if known
1.423     albertel 7187: 
                   7188:  Arguments:
                   7189:     $r           - Apache request object
                   7190:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7191:     $line        - Number of the line being displayed.
1.503     raeburn  7192:     $questionnum - Question number (may include subquestion)
                   7193:     $error       - Type of error.
1.497     foxr     7194:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7195: 
                   7196: =cut
                   7197: 
1.157     albertel 7198: sub scantron_bubble_selector {
1.503     raeburn  7199:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7200:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7201: 
                   7202:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7203:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7204:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7205:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7206:             $max=$$scan_config{'BubblesPerRow'};
                   7207:             if (($scmode eq 'number') && ($max > 10)) {
                   7208:                 $max = 10;
                   7209:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7210:                 $max = 26;
                   7211:             }
                   7212:         } else {
                   7213:             $max = 10;
                   7214:         }
                   7215:     }
1.274     albertel 7216: 
1.157     albertel 7217:     my @alphabet=('A'..'Z');
1.503     raeburn  7218:     $r->print(&Apache::loncommon::start_data_table().
                   7219:               &Apache::loncommon::start_data_table_row());
                   7220:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7221:     for (my $i=0;$i<$max+1;$i++) {
                   7222: 	$r->print("\n".'<td align="center">');
                   7223: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7224: 	else { $r->print('&nbsp;'); }
                   7225: 	$r->print('</td>');
                   7226:     }
1.503     raeburn  7227:     $r->print(&Apache::loncommon::end_data_table_row().
                   7228:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7229:     for (my $i=0;$i<$max;$i++) {
                   7230: 	$r->print("\n".
                   7231: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7232: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7233:     }
1.503     raeburn  7234:     my $nobub_checked = ' ';
                   7235:     if ($error eq 'missingbubble') {
                   7236:         $nobub_checked = ' checked = "checked" ';
                   7237:     }
                   7238:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7239: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7240:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7241:               $line.'" value="'.$questionnum.'" /></td>');
                   7242:     $r->print(&Apache::loncommon::end_data_table_row().
                   7243:               &Apache::loncommon::end_data_table());
1.157     albertel 7244: }
                   7245: 
1.423     albertel 7246: =pod
                   7247: 
                   7248: =item num_matches
                   7249: 
1.424     albertel 7250:    Counts the number of characters that are the same between the two arguments.
                   7251: 
                   7252:  Arguments:
                   7253:    $orig - CODE from the scanline
                   7254:    $code - CODE to match against
                   7255: 
                   7256:  Returns:
                   7257:    $count - integer count of the number of same characters between the
                   7258:             two arguments
                   7259: 
1.423     albertel 7260: =cut
                   7261: 
1.194     albertel 7262: sub num_matches {
                   7263:     my ($orig,$code) = @_;
                   7264:     my @code=split(//,$code);
                   7265:     my @orig=split(//,$orig);
                   7266:     my $same=0;
                   7267:     for (my $i=0;$i<scalar(@code);$i++) {
                   7268: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7269:     }
                   7270:     return $same;
                   7271: }
                   7272: 
1.423     albertel 7273: =pod
                   7274: 
                   7275: =item scantron_get_closely_matching_CODEs
                   7276: 
1.424     albertel 7277:    Cycles through all CODEs and finds the set that has the greatest
                   7278:    number of same characters as the provided CODE
                   7279: 
                   7280:  Arguments:
                   7281:    $allcodes - hash ref returned by &get_codes()
                   7282:    $CODE     - CODE from the current scanline
                   7283: 
                   7284:  Returns:
                   7285:    2 element list
                   7286:     - first elements is number of how closely matching the best fit is 
                   7287:       (5 means best set has 5 matching characters)
                   7288:     - second element is an arrary ref containing the set of valid CODEs
                   7289:       that best fit the passed in CODE
                   7290: 
1.423     albertel 7291: =cut
                   7292: 
1.194     albertel 7293: sub scantron_get_closely_matching_CODEs {
                   7294:     my ($allcodes,$CODE)=@_;
                   7295:     my @CODEs;
                   7296:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7297: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7298:     }
                   7299: 
                   7300:     return ($#CODEs,$CODEs[-1]);
                   7301: }
                   7302: 
1.423     albertel 7303: =pod
                   7304: 
                   7305: =item get_codes
                   7306: 
1.424     albertel 7307:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7308:    set of remembered CODEs.
                   7309: 
                   7310:  Arguments:
                   7311:   $old_name - name of the set of remembered CODEs
                   7312:   $cdom     - domain of the course
                   7313:   $cnum     - internal course name
                   7314: 
                   7315:  Returns:
                   7316:   %allcodes - keys are the valid CODEs, values are all 1
                   7317: 
1.423     albertel 7318: =cut
                   7319: 
1.194     albertel 7320: sub get_codes {
1.280     foxr     7321:     my ($old_name, $cdom, $cnum) = @_;
                   7322:     if (!$old_name) {
                   7323: 	$old_name=$env{'form.scantron_CODElist'};
                   7324:     }
                   7325:     if (!$cdom) {
                   7326: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7327:     }
                   7328:     if (!$cnum) {
                   7329: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7330:     }
1.278     albertel 7331:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7332: 				    $cdom,$cnum);
                   7333:     my %allcodes;
                   7334:     if ($result{"type\0$old_name"} eq 'number') {
                   7335: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7336:     } else {
                   7337: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7338:     }
1.194     albertel 7339:     return %allcodes;
                   7340: }
                   7341: 
1.423     albertel 7342: =pod
                   7343: 
                   7344: =item scantron_validate_CODE
                   7345: 
1.424     albertel 7346:    Validates all scanlines in the selected file to not have any
                   7347:    invalid or underspecified CODEs and that none of the codes are
                   7348:    duplicated if this was requested.
                   7349: 
1.423     albertel 7350: =cut
                   7351: 
1.157     albertel 7352: sub scantron_validate_CODE {
                   7353:     my ($r,$currentphase) = @_;
1.257     albertel 7354:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7355:     if ($scantron_config{'CODElocation'} &&
                   7356: 	$scantron_config{'CODEstart'} &&
                   7357: 	$scantron_config{'CODElength'}) {
1.257     albertel 7358: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7359: 	    &FIXME_blow_up()
                   7360: 	}
                   7361:     } else {
                   7362: 	return (0,$currentphase+1);
                   7363:     }
                   7364:     
                   7365:     my %usedCODEs;
                   7366: 
1.194     albertel 7367:     my %allcodes=&get_codes();
1.186     albertel 7368: 
1.582     raeburn  7369:     my $nav_error;
1.649     raeburn  7370:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7371:     if ($nav_error) {
                   7372:         $r->print(&navmap_errormsg());
                   7373:         return(1,$currentphase);
                   7374:     }
1.447     foxr     7375: 
1.186     albertel 7376:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7377:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7378: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7379: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7380: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7381: 						 $scan_data);
                   7382: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7383: 	my $error=0;
1.224     albertel 7384: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7385: 	    &scantron_get_correction($r,$i,$scan_record,
                   7386: 				     \%scantron_config,
                   7387: 				     $line,'incorrectCODE',\%allcodes);
                   7388: 	    return(1,$currentphase);
                   7389: 	}
1.221     albertel 7390: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7391: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7392: 	    &scantron_get_correction($r,$i,$scan_record,
                   7393: 				     \%scantron_config,
1.194     albertel 7394: 				     $line,'incorrectCODE',\%allcodes);
                   7395: 	    return(1,$currentphase);
1.186     albertel 7396: 	}
1.214     albertel 7397: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7398: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7399: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7400: 	    &scantron_get_correction($r,$i,$scan_record,
                   7401: 				     \%scantron_config,
1.194     albertel 7402: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7403: 	    return(1,$currentphase);
1.186     albertel 7404: 	}
1.524     raeburn  7405: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7406:     }
1.157     albertel 7407:     return (0,$currentphase+1);
                   7408: }
                   7409: 
1.423     albertel 7410: =pod
                   7411: 
                   7412: =item scantron_validate_doublebubble
                   7413: 
1.424     albertel 7414:    Validates all scanlines in the selected file to not have any
                   7415:    bubble lines with multiple bubbles marked.
                   7416: 
1.423     albertel 7417: =cut
                   7418: 
1.157     albertel 7419: sub scantron_validate_doublebubble {
                   7420:     my ($r,$currentphase) = @_;
                   7421:     #get student info
                   7422:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7423:     my %idmap=&username_to_idmap($classlist);
                   7424: 
                   7425:     #get scantron line setup
1.257     albertel 7426:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7427:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7428:     my $nav_error;
1.649     raeburn  7429:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7430:     if ($nav_error) {
                   7431:         $r->print(&navmap_errormsg());
                   7432:         return(1,$currentphase);
                   7433:     }
1.447     foxr     7434: 
1.157     albertel 7435:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7436: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7437: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7438: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7439: 						 $scan_data);
                   7440: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7441: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7442: 				 'doublebubble',
                   7443: 				 $$scan_record{'scantron.doubleerror'});
                   7444:     	return (1,$currentphase);
                   7445:     }
                   7446:     return (0,$currentphase+1);
                   7447: }
                   7448: 
1.423     albertel 7449: 
1.503     raeburn  7450: sub scantron_get_maxbubble {
1.649     raeburn  7451:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7452:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7453: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7454: 	&restore_bubble_lines();
1.257     albertel 7455: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7456:     }
1.330     albertel 7457: 
1.447     foxr     7458:     my (undef, undef, $sequence) =
1.257     albertel 7459: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7460: 
1.447     foxr     7461:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7462:     unless (ref($navmap)) {
                   7463:         if (ref($nav_error)) {
                   7464:             $$nav_error = 1;
                   7465:         }
1.591     raeburn  7466:         return;
1.582     raeburn  7467:     }
1.191     albertel 7468:     my $map=$navmap->getResourceByUrl($sequence);
                   7469:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7470:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7471: 
                   7472:     &Apache::lonxml::clear_problem_counter();
                   7473: 
1.557     raeburn  7474:     my $uname       = $env{'user.name'};
                   7475:     my $udom        = $env{'user.domain'};
1.435     foxr     7476:     my $cid         = $env{'request.course.id'};
                   7477:     my $total_lines = 0;
                   7478:     %bubble_lines_per_response = ();
1.447     foxr     7479:     %first_bubble_line         = ();
1.503     raeburn  7480:     %subdivided_bubble_lines   = ();
                   7481:     %responsetype_per_response = ();
1.554     raeburn  7482: 
1.447     foxr     7483:     my $response_number = 0;
                   7484:     my $bubble_line     = 0;
1.191     albertel 7485:     foreach my $resource (@resources) {
1.649     raeburn  7486:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
1.542     raeburn  7487:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7488: 	    foreach my $part_id (@{$parts}) {
                   7489:                 my $lines;
                   7490: 
                   7491: 	        # TODO - make this a persistent hash not an array.
                   7492: 
                   7493:                 # optionresponse, matchresponse and rankresponse type items 
                   7494:                 # render as separate sub-questions in exam mode.
                   7495:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7496:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7497:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7498:                     my ($numbub,$numshown);
                   7499:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7500:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7501:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7502:                         }
                   7503:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7504:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7505:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7506:                         }
                   7507:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7508:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7509:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7510:                         }
                   7511:                     }
                   7512:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7513:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7514:                     }
1.649     raeburn  7515:                     my $bubbles_per_row =
                   7516:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7517:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7518:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7519:                         $inner_bubble_lines++;
                   7520:                     }
                   7521:                     for (my $i=0; $i<$numshown; $i++) {
                   7522:                         $subdivided_bubble_lines{$response_number} .= 
                   7523:                             $inner_bubble_lines.',';
                   7524:                     }
                   7525:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7526:                     $lines = $numshown * $inner_bubble_lines;
                   7527:                 } else {
                   7528:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7529:                 }
1.542     raeburn  7530: 
                   7531:                 $first_bubble_line{$response_number} = $bubble_line;
                   7532: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7533:                 $responsetype_per_response{$response_number} = 
                   7534:                     $analysis->{$part_id.'.type'};
                   7535: 	        $response_number++;
                   7536: 
                   7537: 	        $bubble_line +=  $lines;
                   7538: 	        $total_lines +=  $lines;
                   7539: 	    }
                   7540:         }
                   7541:     }
1.552     raeburn  7542:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7543: 
                   7544:     &save_bubble_lines();
                   7545:     $env{'form.scantron_maxbubble'} =
                   7546: 	$total_lines;
                   7547:     return $env{'form.scantron_maxbubble'};
                   7548: }
1.523     raeburn  7549: 
1.649     raeburn  7550: sub bubblesheet_bubbles_per_row {
                   7551:     my ($scantron_config) = @_;
                   7552:     my $bubbles_per_row;
                   7553:     if (ref($scantron_config) eq 'HASH') {
                   7554:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7555:     }
                   7556:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7557:         $bubbles_per_row = 10;
                   7558:     }
                   7559:     return $bubbles_per_row;
                   7560: }
                   7561: 
1.157     albertel 7562: sub scantron_validate_missingbubbles {
                   7563:     my ($r,$currentphase) = @_;
                   7564:     #get student info
                   7565:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7566:     my %idmap=&username_to_idmap($classlist);
                   7567: 
                   7568:     #get scantron line setup
1.257     albertel 7569:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7570:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7571:     my $nav_error;
1.649     raeburn  7572:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7573:     if ($nav_error) {
                   7574:         return(1,$currentphase);
                   7575:     }
1.157     albertel 7576:     if (!$max_bubble) { $max_bubble=2**31; }
                   7577:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7578: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7579: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7580: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7581: 						 $scan_data);
                   7582: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7583: 	my @to_correct;
1.470     foxr     7584: 	
                   7585: 	# Probably here's where the error is...
                   7586: 
1.157     albertel 7587: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7588:             my $lastbubble;
                   7589:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7590:                my $question = $1;
                   7591:                my $subquestion = $2;
                   7592:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7593:                my $first = $first_bubble_line{$question-1};
                   7594:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7595:                my $subcount = 1;
                   7596:                while ($subcount<$subquestion) {
                   7597:                    $first += $subans[$subcount-1];
                   7598:                    $subcount ++;
                   7599:                }
                   7600:                my $count = $subans[$subquestion-1];
                   7601:                $lastbubble = $first + $count;
                   7602:             } else {
                   7603:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7604:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7605:             }
                   7606:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7607: 	    push(@to_correct,$missing);
                   7608: 	}
                   7609: 	if (@to_correct) {
                   7610: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7611: 				     $line,'missingbubble',\@to_correct);
                   7612: 	    return (1,$currentphase);
                   7613: 	}
                   7614: 
                   7615:     }
                   7616:     return (0,$currentphase+1);
                   7617: }
                   7618: 
1.423     albertel 7619: 
1.82      albertel 7620: sub scantron_process_students {
1.608     www      7621:     my ($r,$symb) = @_;
1.513     foxr     7622: 
1.257     albertel 7623:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7624:     if (!$symb) {
                   7625: 	return '';
                   7626:     }
1.324     albertel 7627:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7628: 
1.257     albertel 7629:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7630:     my $bubbles_per_row =
                   7631:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7632:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7633:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7634:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7635:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7636:     unless (ref($navmap)) {
                   7637:         $r->print(&navmap_errormsg());
                   7638:         return '';
                   7639:     }  
1.83      albertel 7640:     my $map=$navmap->getResourceByUrl($sequence);
                   7641:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7642:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7643:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7644:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7645:     my $resource_error;
1.557     raeburn  7646:     foreach my $resource (@resources) {
1.586     raeburn  7647:         my $ressymb;
                   7648:         if (ref($resource)) {
                   7649:             $ressymb = $resource->symb();
                   7650:         } else {
                   7651:             $resource_error = 1;
                   7652:             last;
                   7653:         }
1.557     raeburn  7654:         my ($analysis,$parts) =
                   7655:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7656:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7657:         $grader_partids_by_symb{$ressymb} = $parts;
                   7658:         if (ref($analysis) eq 'HASH') {
                   7659:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7660:                 $grader_randomlists_by_symb{$ressymb} = 
                   7661:                     $analysis->{'parts_withrandomlist'};
                   7662:             }
                   7663:         }
                   7664:     }
1.586     raeburn  7665:     if ($resource_error) {
                   7666:         $r->print(&navmap_errormsg());
                   7667:         return '';
                   7668:     }
1.557     raeburn  7669: 
1.554     raeburn  7670:     my ($uname,$udom);
1.82      albertel 7671:     my $result= <<SCANTRONFORM;
1.81      albertel 7672: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7673:   <input type="hidden" name="command" value="scantron_configphase" />
                   7674:   $default_form_data
                   7675: SCANTRONFORM
1.82      albertel 7676:     $r->print($result);
                   7677: 
                   7678:     my @delayqueue;
1.542     raeburn  7679:     my (%completedstudents,%scandata);
1.140     albertel 7680:     
1.520     www      7681:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7682:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7683:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7684:  				    'Bubblesheet Progress',$count,
1.195     albertel 7685: 				    'inline',undef,'scantronupload');
1.140     albertel 7686:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7687: 					  'Processing first student');
1.542     raeburn  7688:     $r->print('<br />');
1.140     albertel 7689:     my $start=&Time::HiRes::time();
1.158     albertel 7690:     my $i=-1;
1.542     raeburn  7691:     my $started;
1.447     foxr     7692: 
1.582     raeburn  7693:     my $nav_error;
1.649     raeburn  7694:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7695:     if ($nav_error) {
                   7696:         $r->print(&navmap_errormsg());
                   7697:         return '';
                   7698:     }
                   7699: 
1.513     foxr     7700:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7701:     # the user and return.
                   7702: 
                   7703:     if ($ssi_error) {
                   7704: 	$r->print("</form>");
                   7705: 	&ssi_print_error($r);
1.520     www      7706:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7707: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7708:     }
1.447     foxr     7709: 
1.542     raeburn  7710:     my %lettdig = &letter_to_digits();
                   7711:     my $numletts = scalar(keys(%lettdig));
                   7712: 
1.157     albertel 7713:     while ($i<$scanlines->{'count'}) {
                   7714:  	($uname,$udom)=('','');
                   7715:  	$i++;
1.200     albertel 7716:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7717:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7718: 	if ($started) {
                   7719: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7720: 						     'last student');
                   7721: 	}
                   7722: 	$started=1;
1.157     albertel 7723:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7724:  						 $scan_data);
                   7725:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7726:  					      \%idmap,$i)) {
                   7727:   	    &scantron_add_delay(\@delayqueue,$line,
                   7728:  				'Unable to find a student that matches',1);
                   7729:  	    next;
                   7730:   	}
                   7731:  	if (exists $completedstudents{$uname}) {
                   7732:  	    &scantron_add_delay(\@delayqueue,$line,
                   7733:  				'Student '.$uname.' has multiple sheets',2);
                   7734:  	    next;
                   7735:  	}
                   7736:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7737: 
1.586     raeburn  7738:         my (%partids_by_symb,$res_error);
1.554     raeburn  7739:         foreach my $resource (@resources) {
1.586     raeburn  7740:             my $ressymb;
                   7741:             if (ref($resource)) {
                   7742:                 $ressymb = $resource->symb();
                   7743:             } else {
                   7744:                 $res_error = 1;
                   7745:                 last;
                   7746:             }
1.557     raeburn  7747:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7748:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7749:                 my ($analysis,$parts) =
1.649     raeburn  7750:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7751:                 $partids_by_symb{$ressymb} = $parts;
                   7752:             } else {
                   7753:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7754:             }
1.554     raeburn  7755:         }
                   7756: 
1.586     raeburn  7757:         if ($res_error) {
                   7758:             &scantron_add_delay(\@delayqueue,$line,
                   7759:                                 'An error occurred while grading student '.$uname,2);
                   7760:             next;
                   7761:         }
                   7762: 
1.330     albertel 7763: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7764:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7765: 
                   7766: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7767: 	    &scantron_putfile($scanlines,$scan_data);
                   7768: 	}
1.161     albertel 7769: 	
1.542     raeburn  7770:         my $scancode;
                   7771:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7772:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7773:             $scancode = $scan_record->{'scantron.CODE'};
                   7774:         } else {
                   7775:             $scancode = '';
                   7776:         }
                   7777: 
                   7778:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7779:                                    \@resources,\%partids_by_symb,
                   7780:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  7781:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7782:             $r->print("</form>");
                   7783:             &ssi_print_error($r);
                   7784:             &Apache::lonnet::remove_lock($lock);
                   7785:             return '';      # Why return ''?  Beats me.
                   7786:         }
1.513     foxr     7787: 
1.140     albertel 7788: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7789:         if ($env{'form.verifyrecord'}) {
                   7790:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7791:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7792:             chomp($studentdata);
                   7793:             $studentdata =~ s/\r$//;
                   7794:             my $studentrecord = '';
                   7795:             my $counter = -1;
                   7796:             foreach my $resource (@resources) {
1.554     raeburn  7797:                 my $ressymb = $resource->symb();
1.542     raeburn  7798:                 ($counter,my $recording) =
                   7799:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7800:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7801:                                              \%scantron_config,\%lettdig,$numletts);
                   7802:                 $studentrecord .= $recording;
                   7803:             }
                   7804:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7805:                 &Apache::lonxml::clear_problem_counter();
                   7806:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7807:                                            \@resources,\%partids_by_symb,
                   7808:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  7809:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7810:                     $r->print("</form>");
                   7811:                     &ssi_print_error($r);
                   7812:                     &Apache::lonnet::remove_lock($lock);
                   7813:                     delete($completedstudents{$uname});
                   7814:                     return '';
                   7815:                 }
1.542     raeburn  7816:                 $counter = -1;
                   7817:                 $studentrecord = '';
                   7818:                 foreach my $resource (@resources) {
1.554     raeburn  7819:                     my $ressymb = $resource->symb();
1.542     raeburn  7820:                     ($counter,my $recording) =
                   7821:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7822:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7823:                                                  \%scantron_config,\%lettdig,$numletts);
                   7824:                     $studentrecord .= $recording;
                   7825:                 }
                   7826:                 if ($studentrecord ne $studentdata) {
                   7827:                     $r->print('<p><span class="LC_error">');
                   7828:                     if ($scancode eq '') {
                   7829:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7830:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7831:                     } else {
                   7832:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7833:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7834:                     }
                   7835:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7836:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7837:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7838:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7839:                               &Apache::loncommon::start_data_table_row().
                   7840:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7841:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7842:                               &Apache::loncommon::end_data_table_row().
                   7843:                               &Apache::loncommon::start_data_table_row().
                   7844:                               '<td>Stored submissions</td>'.
                   7845:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7846:                               &Apache::loncommon::end_data_table_row().
                   7847:                               &Apache::loncommon::end_data_table().'</p>');
                   7848:                 } else {
                   7849:                     $r->print('<br /><span class="LC_warning">'.
                   7850:                              &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 />'.
                   7851:                              &mt("As a consequence, this user's submission history records two tries.").
                   7852:                                  '</span><br />');
                   7853:                 }
                   7854:             }
                   7855:         }
1.543     raeburn  7856:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7857:     } continue {
1.330     albertel 7858: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7859: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7860:     }
1.140     albertel 7861:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7862:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7863: #    my $lasttime = &Time::HiRes::time()-$start;
                   7864: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7865: 
1.200     albertel 7866:     $r->print("</form>");
1.157     albertel 7867:     return '';
1.75      albertel 7868: }
1.157     albertel 7869: 
1.557     raeburn  7870: sub graders_resources_pass {
1.649     raeburn  7871:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   7872:         $bubbles_per_row) = @_;
1.557     raeburn  7873:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7874:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7875:         foreach my $resource (@{$resources}) {
                   7876:             my $ressymb = $resource->symb();
                   7877:             my ($analysis,$parts) =
                   7878:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7879:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7880:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7881:             if (ref($analysis) eq 'HASH') {
                   7882:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7883:                     $grader_randomlists_by_symb->{$ressymb} =
                   7884:                         $analysis->{'parts_withrandomlist'};
                   7885:                 }
                   7886:             }
                   7887:         }
                   7888:     }
                   7889:     return;
                   7890: }
                   7891: 
1.542     raeburn  7892: sub grade_student_bubbles {
1.649     raeburn  7893:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   7894: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  7895:     if (ref($resources) eq 'ARRAY') {
                   7896:         my $count = 0;
                   7897:         foreach my $resource (@{$resources}) {
                   7898:             my $ressymb = $resource->symb();
                   7899:             my %form = ('submitted'      => 'scantron',
                   7900:                         'grade_target'   => 'grade',
                   7901:                         'grade_username' => $uname,
                   7902:                         'grade_domain'   => $udom,
                   7903:                         'grade_courseid' => $env{'request.course.id'},
                   7904:                         'grade_symb'     => $ressymb,
                   7905:                         'CODE'           => $scancode
                   7906:                        );
1.649     raeburn  7907:             if ($bubbles_per_row ne '') {
                   7908:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   7909:             }
1.554     raeburn  7910:             if (ref($parts) eq 'HASH') {
                   7911:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7912:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7913:                         $form{'scantron_questnum_start.'.$part} =
                   7914:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7915:                         $count++;
                   7916:                     }
                   7917:                 }
                   7918:             }
                   7919:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7920:             return 'ssi_error' if ($ssi_error);
                   7921:             last if (&Apache::loncommon::connection_aborted($r));
                   7922:         }
1.542     raeburn  7923:     }
                   7924:     return;
                   7925: }
                   7926: 
1.157     albertel 7927: sub scantron_upload_scantron_data {
1.608     www      7928:     my ($r,$symb)=@_;
1.565     raeburn  7929:     my $dom = $env{'request.role.domain'};
                   7930:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7931:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7932:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7933: 							  'domainid',
1.565     raeburn  7934: 							  'coursename',$dom);
                   7935:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7936:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7937:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7938:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7939:     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 7940:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7941:     function checkUpload(formname) {
                   7942: 	if (formname.upfile.value == "") {
1.579     raeburn  7943: 	    alert("'.$nofile_alert.'");
1.157     albertel 7944: 	    return false;
                   7945: 	}
1.565     raeburn  7946:         if (formname.courseid.value == "") {
1.579     raeburn  7947:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7948:             return false;
                   7949:         }
1.157     albertel 7950: 	formname.submit();
                   7951:     }
1.565     raeburn  7952: 
                   7953:     function ToSyllabus() {
                   7954:         var cdom = '."'$dom'".';
                   7955:         var cnum = document.rules.courseid.value;
                   7956:         if (cdom == "" || cdom == null) {
                   7957:             return;
                   7958:         }
                   7959:         if (cnum == "" || cnum == null) {
                   7960:            return;
                   7961:         }
                   7962:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7963:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7964:         return;
                   7965:     }
                   7966: 
1.597     wenzelju 7967: '));
                   7968:     $r->print('
1.648     bisitz   7969: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  7970: 
1.492     albertel 7971: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7972: '.$default_form_data.
                   7973:   &Apache::lonhtmlcommon::start_pick_box().
                   7974:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7975:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7976:   &Apache::lonhtmlcommon::row_closure().
                   7977:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7978:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7979:   &Apache::lonhtmlcommon::row_closure().
                   7980:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7981:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7982:   &Apache::lonhtmlcommon::row_closure().
                   7983:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7984:   '<input type="file" name="upfile" size="50" />'.
                   7985:   &Apache::lonhtmlcommon::row_closure(1).
                   7986:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7987: 
1.492     albertel 7988: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7989: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7990: </form>
1.492     albertel 7991: ');
1.157     albertel 7992:     return '';
                   7993: }
                   7994: 
1.423     albertel 7995: 
1.157     albertel 7996: sub scantron_upload_scantron_data_save {
1.608     www      7997:     my($r,$symb)=@_;
1.182     albertel 7998:     my $doanotherupload=
                   7999: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8000: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8001: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8002: 	'</form>'."\n";
1.257     albertel 8003:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8004: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8005: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8006: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8007: 	unless ($symb) {
1.182     albertel 8008: 	    $r->print($doanotherupload);
                   8009: 	}
1.162     albertel 8010: 	return '';
                   8011:     }
1.257     albertel 8012:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8013:     my $uploadedfile;
1.567     raeburn  8014:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8015:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8016:         $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 8017:     } else {
1.568     raeburn  8018:         my $result = 
                   8019:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8020:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8021: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8022: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8023:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8024: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8025:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8026:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8027:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8028: 	} else {
1.567     raeburn  8029: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8030:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8031: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8032: 	}
                   8033:     }
1.174     albertel 8034:     if ($symb) {
1.612     www      8035: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8036:     } else {
1.182     albertel 8037: 	$r->print($doanotherupload);
1.174     albertel 8038:     }
1.157     albertel 8039:     return '';
                   8040: }
                   8041: 
1.567     raeburn  8042: sub validate_uploaded_scantron_file {
                   8043:     my ($cdom,$cname,$fname) = @_;
                   8044:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8045:     my @lines;
                   8046:     if ($scanlines ne '-1') {
                   8047:         @lines=split("\n",$scanlines,-1);
                   8048:     }
                   8049:     my $output;
                   8050:     if (@lines) {
                   8051:         my (%counts,$max_match_format);
                   8052:         my ($max_match_count,$max_match_pct) = (0,0);
                   8053:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8054:         my %idmap = &username_to_idmap($classlist);
                   8055:         foreach my $key (keys(%idmap)) {
                   8056:             my $lckey = lc($key);
                   8057:             $idmap{$lckey} = $idmap{$key};
                   8058:         }
                   8059:         my %unique_formats;
                   8060:         my @formatlines = &get_scantronformat_file();
                   8061:         foreach my $line (@formatlines) {
                   8062:             chomp($line);
                   8063:             my @config = split(/:/,$line);
                   8064:             my $idstart = $config[5];
                   8065:             my $idlength = $config[6];
                   8066:             if (($idstart ne '') && ($idlength > 0)) {
                   8067:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8068:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8069:                 } else {
                   8070:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8071:                 }
                   8072:             }
                   8073:         }
                   8074:         foreach my $key (keys(%unique_formats)) {
                   8075:             my ($idstart,$idlength) = split(':',$key);
                   8076:             %{$counts{$key}} = (
                   8077:                                'found'   => 0,
                   8078:                                'total'   => 0,
                   8079:                               );
                   8080:             foreach my $line (@lines) {
                   8081:                 next if ($line =~ /^#/);
                   8082:                 next if ($line =~ /^[\s\cz]*$/);
                   8083:                 my $id = substr($line,$idstart-1,$idlength);
                   8084:                 $id = lc($id);
                   8085:                 if (exists($idmap{$id})) {
                   8086:                     $counts{$key}{'found'} ++;
                   8087:                 }
                   8088:                 $counts{$key}{'total'} ++;
                   8089:             }
                   8090:             if ($counts{$key}{'total'}) {
                   8091:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8092:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8093:                     $max_match_pct = $percent_match;
                   8094:                     $max_match_format = $key;
                   8095:                     $max_match_count = $counts{$key}{'total'};
                   8096:                 }
                   8097:             }
                   8098:         }
                   8099:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8100:             my $format_descs;
                   8101:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8102:             for (my $i=0; $i<$numwithformat; $i++) {
                   8103:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8104:                 if ($i<$numwithformat-2) {
                   8105:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8106:                 } elsif ($i==$numwithformat-2) {
                   8107:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8108:                 } elsif ($i==$numwithformat-1) {
                   8109:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8110:                 }
                   8111:             }
                   8112:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8113:             $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).
                   8114:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8115:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8116:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8117:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8118:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8119:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8120:                        '</ul>';
                   8121:         }
                   8122:     } else {
                   8123:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8124:     }
                   8125:     return $output;
                   8126: }
                   8127: 
1.202     albertel 8128: sub valid_file {
                   8129:     my ($requested_file)=@_;
                   8130:     foreach my $filename (sort(&scantron_filenames())) {
                   8131: 	if ($requested_file eq $filename) { return 1; }
                   8132:     }
                   8133:     return 0;
                   8134: }
                   8135: 
                   8136: sub scantron_download_scantron_data {
1.608     www      8137:     my ($r,$symb)=@_;
                   8138:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8139:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8140:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8141:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8142:     if (! &valid_file($file)) {
1.492     albertel 8143: 	$r->print('
1.202     albertel 8144: 	<p>
1.492     albertel 8145: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8146:         </p>
1.492     albertel 8147: ');
1.202     albertel 8148: 	return;
                   8149:     }
                   8150:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8151:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8152:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8153:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8154:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8155:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8156:     $r->print('
1.202     albertel 8157:     <p>
1.492     albertel 8158: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8159: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8160:     </p>
                   8161:     <p>
1.492     albertel 8162: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8163: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8164:     </p>
                   8165:     <p>
1.492     albertel 8166: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8167: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8168:     </p>
1.492     albertel 8169: ');
1.202     albertel 8170:     return '';
                   8171: }
1.157     albertel 8172: 
1.523     raeburn  8173: sub checkscantron_results {
1.608     www      8174:     my ($r,$symb) = @_;
1.523     raeburn  8175:     if (!$symb) {return '';}
                   8176:     my $cid = $env{'request.course.id'};
1.542     raeburn  8177:     my %lettdig = &letter_to_digits();
1.523     raeburn  8178:     my $numletts = scalar(keys(%lettdig));
                   8179:     my $cnum = $env{'course.'.$cid.'.num'};
                   8180:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8181:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8182:     my %record;
                   8183:     my %scantron_config =
                   8184:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8185:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8186:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8187:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8188:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8189:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8190:     unless (ref($navmap)) {
                   8191:         $r->print(&navmap_errormsg());
                   8192:         return '';
                   8193:     }
1.523     raeburn  8194:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8195:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8196:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8197:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8198: 
1.554     raeburn  8199:     my ($uname,$udom);
1.523     raeburn  8200:     my (%scandata,%lastname,%bylast);
                   8201:     $r->print('
                   8202: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8203: 
                   8204:     my @delayqueue;
                   8205:     my %completedstudents;
                   8206: 
                   8207:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8208:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8209:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8210:                                     'inline',undef,'checkscantron');
1.546     raeburn  8211:     my ($username,$domain,$started);
1.582     raeburn  8212:     my $nav_error;
1.649     raeburn  8213:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8214:     if ($nav_error) {
                   8215:         $r->print(&navmap_errormsg());
                   8216:         return '';
                   8217:     }
1.523     raeburn  8218: 
                   8219:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8220:                                           'Processing first student');
                   8221:     my $start=&Time::HiRes::time();
                   8222:     my $i=-1;
                   8223: 
                   8224:     while ($i<$scanlines->{'count'}) {
                   8225:         ($username,$domain,$uname)=('','','');
                   8226:         $i++;
                   8227:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8228:         if ($line=~/^[\s\cz]*$/) { next; }
                   8229:         if ($started) {
                   8230:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8231:                                                      'last student');
                   8232:         }
                   8233:         $started=1;
                   8234:         my $scan_record=
                   8235:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8236:                                                      $scan_data);
                   8237:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8238:                                                               \%idmap,$i)) {
                   8239:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8240:                                 'Unable to find a student that matches',1);
                   8241:             next;
                   8242:         }
                   8243:         if (exists $completedstudents{$uname}) {
                   8244:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8245:                                 'Student '.$uname.' has multiple sheets',2);
                   8246:             next;
                   8247:         }
                   8248:         my $pid = $scan_record->{'scantron.ID'};
                   8249:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8250:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8251:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8252:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8253:         chomp($scandata{$pid});
                   8254:         $scandata{$pid} =~ s/\r$//;
                   8255:         ($username,$domain)=split(/:/,$uname);
                   8256:         my $counter = -1;
                   8257:         foreach my $resource (@resources) {
1.557     raeburn  8258:             my $parts;
1.554     raeburn  8259:             my $ressymb = $resource->symb();
1.557     raeburn  8260:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8261:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8262:                 (my $analysis,$parts) =
1.649     raeburn  8263:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
1.557     raeburn  8264:             } else {
                   8265:                 $parts = $grader_partids_by_symb{$ressymb};
                   8266:             }
1.542     raeburn  8267:             ($counter,my $recording) =
                   8268:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8269:                                          $scandata{$pid},$parts,
1.542     raeburn  8270:                                          \%scantron_config,\%lettdig,$numletts);
                   8271:             $record{$pid} .= $recording;
1.523     raeburn  8272:         }
                   8273:     }
                   8274:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8275:     $r->print('<br />');
                   8276:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8277:     $passed = 0;
                   8278:     $failed = 0;
                   8279:     $numstudents = 0;
                   8280:     foreach my $last (sort(keys(%bylast))) {
                   8281:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8282:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8283:                 my $showscandata = $scandata{$pid};
                   8284:                 my $showrecord = $record{$pid};
                   8285:                 $showscandata =~ s/\s/&nbsp;/g;
                   8286:                 $showrecord =~ s/\s/&nbsp;/g;
                   8287:                 if ($scandata{$pid} eq $record{$pid}) {
                   8288:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8289:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8290: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8291: '</tr>'."\n".
                   8292: '<tr class="'.$css_class.'">'."\n".
                   8293: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8294:                     $passed ++;
                   8295:                 } else {
                   8296:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8297:                     $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  8298: '</tr>'."\n".
                   8299: '<tr class="'.$css_class.'">'."\n".
                   8300: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8301: '</tr>'."\n";
                   8302:                     $failed ++;
                   8303:                 }
                   8304:                 $numstudents ++;
                   8305:             }
                   8306:         }
                   8307:     }
1.648     bisitz   8308:     $r->print(
                   8309:         '<p>'
                   8310:        .&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).',
                   8311:             '<b>',
                   8312:             $numstudents,
                   8313:             '</b>',
                   8314:             $env{'form.scantron_maxbubble'})
                   8315:        .'</p>'
                   8316:     );
1.523     raeburn  8317:     $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>');
                   8318:     if ($passed) {
1.572     www      8319:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8320:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8321:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8322:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8323:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8324:                  $okstudents."\n".
                   8325:                  &Apache::loncommon::end_data_table().'<br />');
                   8326:     }
                   8327:     if ($failed) {
1.572     www      8328:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8329:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8330:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8331:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8332:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8333:                  $badstudents."\n".
                   8334:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8335:                  &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  8336:     }
1.614     www      8337:     $r->print('</form><br />');
1.523     raeburn  8338:     return;
                   8339: }
                   8340: 
1.542     raeburn  8341: sub verify_scantron_grading {
1.554     raeburn  8342:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8343:         $scantron_config,$lettdig,$numletts) = @_;
                   8344:     my ($record,%expected,%startpos);
                   8345:     return ($counter,$record) if (!ref($resource));
                   8346:     return ($counter,$record) if (!$resource->is_problem());
                   8347:     my $symb = $resource->symb();
1.554     raeburn  8348:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8349:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8350:         $counter ++;
                   8351:         $expected{$part_id} = 0;
                   8352:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8353:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8354:             foreach my $item (@sub_lines) {
                   8355:                 $expected{$part_id} += $item;
                   8356:             }
                   8357:         } else {
                   8358:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8359:         }
                   8360:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8361:     }
                   8362:     if ($symb) {
                   8363:         my %recorded;
                   8364:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8365:         if ($returnhash{'version'}) {
                   8366:             my %lasthash=();
                   8367:             my $version;
                   8368:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8369:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8370:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8371:                 }
                   8372:             }
                   8373:             foreach my $key (keys(%lasthash)) {
                   8374:                 if ($key =~ /\.scantron$/) {
                   8375:                     my $value = &unescape($lasthash{$key});
                   8376:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8377:                     if ($value eq '') {
                   8378:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8379:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8380:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8381:                             }
                   8382:                         }
                   8383:                     } else {
                   8384:                         my @tocheck;
                   8385:                         my @items = split(//,$value);
                   8386:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8387:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8388:                             if (@items < $expected{$part_id}) {
                   8389:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8390:                                 my @singles = split(//,$fragment);
                   8391:                                 foreach my $pos (@singles) {
                   8392:                                     if ($pos eq ' ') {
                   8393:                                         push(@tocheck,$pos);
                   8394:                                     } else {
                   8395:                                         my $next = shift(@items);
                   8396:                                         push(@tocheck,$next);
                   8397:                                     }
                   8398:                                 }
                   8399:                             } else {
                   8400:                                 @tocheck = @items;
                   8401:                             }
                   8402:                             foreach my $letter (@tocheck) {
                   8403:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8404:                                     if ($letter !~ /^[A-J]$/) {
                   8405:                                         $letter = $scantron_config->{'Qoff'};
                   8406:                                     }
                   8407:                                     $recorded{$part_id} .= $letter;
                   8408:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8409:                                     my $digit;
                   8410:                                     if ($letter !~ /^[A-J]$/) {
                   8411:                                         $digit = $scantron_config->{'Qoff'};
                   8412:                                     } else {
                   8413:                                         $digit = $lettdig->{$letter};
                   8414:                                     }
                   8415:                                     $recorded{$part_id} .= $digit;
                   8416:                                 }
                   8417:                             }
                   8418:                         } else {
                   8419:                             @tocheck = @items;
                   8420:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8421:                                 my $curr_sub = shift(@tocheck);
                   8422:                                 my $digit;
                   8423:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8424:                                     $digit = $lettdig->{$curr_sub}-1;
                   8425:                                 }
                   8426:                                 if ($curr_sub eq 'J') {
                   8427:                                     $digit += scalar($numletts);
                   8428:                                 }
                   8429:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8430:                                     if ($j == $digit) {
                   8431:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8432:                                     } else {
                   8433:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8434:                                     }
                   8435:                                 }
                   8436:                             }
                   8437:                         }
                   8438:                     }
                   8439:                 }
                   8440:             }
                   8441:         }
1.554     raeburn  8442:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8443:             if ($recorded{$part_id} eq '') {
                   8444:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8445:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8446:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8447:                     }
                   8448:                 }
                   8449:             }
                   8450:             $record .= $recorded{$part_id};
                   8451:         }
                   8452:     }
                   8453:     return ($counter,$record);
                   8454: }
                   8455: 
                   8456: sub letter_to_digits { 
                   8457:     my %lettdig = (
                   8458:                     A => 1,
                   8459:                     B => 2,
                   8460:                     C => 3,
                   8461:                     D => 4,
                   8462:                     E => 5,
                   8463:                     F => 6,
                   8464:                     G => 7,
                   8465:                     H => 8,
                   8466:                     I => 9,
                   8467:                     J => 0,
                   8468:                   );
                   8469:     return %lettdig;
                   8470: }
                   8471: 
1.423     albertel 8472: 
1.75      albertel 8473: #-------- end of section for handling grading scantron forms -------
                   8474: #
                   8475: #-------------------------------------------------------------------
                   8476: 
1.72      ng       8477: #-------------------------- Menu interface -------------------------
                   8478: #
1.614     www      8479: #--- Href with symb and command ---
                   8480: 
                   8481: sub href_symb_cmd {
                   8482:     my ($symb,$cmd)=@_;
                   8483:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8484: }
                   8485: 
1.443     banghart 8486: sub grading_menu {
1.608     www      8487:     my ($request,$symb) = @_;
1.443     banghart 8488:     if (!$symb) {return '';}
                   8489: 
                   8490:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8491:                   'command'=>'individual');
1.538     schulted 8492:     
1.598     www      8493:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8494: 
                   8495:     $fields{'command'}='ungraded';
                   8496:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8497: 
                   8498:     $fields{'command'}='table';
                   8499:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8500: 
                   8501:     $fields{'command'}='all_for_one';
                   8502:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8503: 
1.621     www      8504:     $fields{'command'}='downloadfilesselect';
                   8505:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8506: 
1.443     banghart 8507:     $fields{'command'} = 'csvform';
1.538     schulted 8508:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8509:     
1.443     banghart 8510:     $fields{'command'} = 'processclicker';
1.538     schulted 8511:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8512:     
1.443     banghart 8513:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8514:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8515: 
                   8516:     $fields{'command'} = 'initialverifyreceipt';
                   8517:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8518:     
1.598     www      8519:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8520:             items =>[
1.598     www      8521:                         {	linktext => 'Select individual students to grade',
                   8522:                     		url => $url1a,
1.538     schulted 8523:                     		permission => 'F',
1.636     wenzelju 8524:                     		icon => 'grade_students.png',
1.598     www      8525:                     		linktitle => 'Grade current resource for a selection of students.'
                   8526:                         }, 
                   8527:                         {       linktext => 'Grade ungraded submissions.',
                   8528:                                 url => $url1b,
                   8529:                                 permission => 'F',
1.636     wenzelju 8530:                                 icon => 'ungrade_sub.png',
1.598     www      8531:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8532:                         },
1.598     www      8533: 
                   8534:                         {       linktext => 'Grading table',
                   8535:                                 url => $url1c,
                   8536:                                 permission => 'F',
1.636     wenzelju 8537:                                 icon => 'grading_table.png',
1.598     www      8538:                                 linktitle => 'Grade current resource for all students.'
                   8539:                         },
1.615     www      8540:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8541:                                 url => $url1d,
                   8542:                                 permission => 'F',
1.636     wenzelju 8543:                                 icon => 'grade_PageFolder.png',
1.598     www      8544:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8545:                         },
                   8546:                         {       linktext => 'Download submissions',
                   8547:                                 url => $url1e,
                   8548:                                 permission => 'F',
1.636     wenzelju 8549:                                 icon => 'download_sub.png',
1.621     www      8550:                                 linktitle => 'Download all students submissions.'
1.598     www      8551:                         }]},
                   8552:                          { categorytitle=>'Automated Grading',
                   8553:                items =>[
                   8554: 
1.538     schulted 8555:                 	    {	linktext => 'Upload Scores',
                   8556:                     		url => $url2,
                   8557:                     		permission => 'F',
                   8558:                     		icon => 'uploadscores.png',
                   8559:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8560:                 	    },
                   8561:                 	    {	linktext => 'Process Clicker',
                   8562:                     		url => $url3,
                   8563:                     		permission => 'F',
                   8564:                     		icon => 'addClickerInfoFile.png',
                   8565:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8566:                 	    },
1.587     raeburn  8567:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8568:                     		url => $url4,
                   8569:                     		permission => 'F',
1.636     wenzelju 8570:                     		icon => 'bubblesheet.png',
1.648     bisitz   8571:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8572:                 	    },
1.616     www      8573:                             {   linktext => 'Verify Receipt Number',
1.602     www      8574:                                 url => $url5,
                   8575:                                 permission => 'F',
1.636     wenzelju 8576:                                 icon => 'receipt_number.png',
1.602     www      8577:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8578:                             }
                   8579: 
1.538     schulted 8580:                     ]
                   8581:             });
                   8582: 
1.443     banghart 8583:     # Create the menu
                   8584:     my $Str;
1.445     banghart 8585:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8586:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8587:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8588: 
1.602     www      8589:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8590:     return $Str;    
                   8591: }
                   8592: 
1.598     www      8593: 
                   8594: sub ungraded {
                   8595:     my ($request)=@_;
                   8596:     &submit_options($request);
                   8597: }
                   8598: 
1.599     www      8599: sub submit_options_sequence {
1.608     www      8600:     my ($request,$symb) = @_;
1.599     www      8601:     if (!$symb) {return '';}
1.600     www      8602:     &commonJSfunctions($request);
                   8603:     my $result;
1.599     www      8604: 
1.600     www      8605:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8606:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8607:     $result.=&selectfield(0).
1.601     www      8608:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8609:             <div>
                   8610:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8611:             </div>
                   8612:         </div>
                   8613:   </form>';
                   8614:     return $result;
                   8615: }
                   8616: 
                   8617: sub submit_options_table {
1.608     www      8618:     my ($request,$symb) = @_;
1.600     www      8619:     if (!$symb) {return '';}
1.599     www      8620:     &commonJSfunctions($request);
                   8621:     my $result;
                   8622: 
                   8623:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8624:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8625: 
1.632     www      8626:     $result.=&selectfield(0).
1.601     www      8627:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8628:             <div>
                   8629:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8630:             </div>
                   8631:         </div>
                   8632:   </form>';
                   8633:     return $result;
                   8634: }
1.443     banghart 8635: 
1.621     www      8636: sub submit_options_download {
                   8637:     my ($request,$symb) = @_;
                   8638:     if (!$symb) {return '';}
                   8639: 
                   8640:     &commonJSfunctions($request);
                   8641: 
                   8642:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8643:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8644:     $result.='
                   8645: <h2>
                   8646:   '.&mt('Select Students for Which to Download Submissions').'
                   8647: </h2>'.&selectfield(1).'
                   8648:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8649:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8650:             </div>
                   8651:           </div>
1.600     www      8652: 
                   8653: 
1.621     www      8654:   </form>';
                   8655:     return $result;
                   8656: }
                   8657: 
1.443     banghart 8658: #--- Displays the submissions first page -------
                   8659: sub submit_options {
1.608     www      8660:     my ($request,$symb) = @_;
1.72      ng       8661:     if (!$symb) {return '';}
                   8662: 
1.118     ng       8663:     &commonJSfunctions($request);
1.473     albertel 8664:     my $result;
1.533     bisitz   8665: 
1.72      ng       8666:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8667: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8668:     $result.=&selectfield(1).'
1.601     www      8669:                 <input type="hidden" name="command" value="submission" /> 
                   8670: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8671:             </div>
                   8672:           </div>
                   8673: 
                   8674: 
                   8675:   </form>';
                   8676:     return $result;
                   8677: }
1.533     bisitz   8678: 
1.601     www      8679: sub selectfield {
                   8680:    my ($full)=@_;
1.635     raeburn  8681:    my %options = 
                   8682:           (&Apache::lonlocal::texthash(
                   8683:              'yes'       => 'with submissions',
                   8684:              'queued'    => 'in grading queue',
                   8685:              'graded'    => 'with ungraded submissions',
                   8686:              'incorrect' => 'with incorrect submissions',
                   8687:              'all'       => 'with any status'),
                   8688:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8689:    my $result='<div class="LC_columnSection">
1.537     harmsja  8690:   
1.533     bisitz   8691:     <fieldset>
                   8692:       <legend>
                   8693:        '.&mt('Sections').'
                   8694:       </legend>
1.601     www      8695:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8696:     </fieldset>
1.537     harmsja  8697:   
1.533     bisitz   8698:     <fieldset>
                   8699:       <legend>
                   8700:         '.&mt('Groups').'
                   8701:       </legend>
                   8702:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8703:     </fieldset>
1.537     harmsja  8704:   
1.533     bisitz   8705:     <fieldset>
                   8706:       <legend>
                   8707:         '.&mt('Access Status').'
                   8708:       </legend>
1.601     www      8709:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8710:     </fieldset>';
                   8711:     if ($full) {
                   8712:        $result.='
1.533     bisitz   8713:     <fieldset>
                   8714:       <legend>
                   8715:         '.&mt('Submission Status').'
1.601     www      8716:       </legend>'.
1.635     raeburn  8717:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8718:    '</fieldset>';
                   8719:     }
                   8720:     $result.='</div><br />';
1.44      ng       8721:     return $result;
1.2       albertel 8722: }
                   8723: 
1.285     albertel 8724: sub reset_perm {
                   8725:     undef(%perm);
                   8726: }
                   8727: 
                   8728: sub init_perm {
                   8729:     &reset_perm();
1.300     albertel 8730:     foreach my $test_perm ('vgr','mgr','opa') {
                   8731: 
                   8732: 	my $scope = $env{'request.course.id'};
                   8733: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8734: 
                   8735: 	    $scope .= '/'.$env{'request.course.sec'};
                   8736: 	    if ( $perm{$test_perm}=
                   8737: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8738: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8739: 	    } else {
                   8740: 		delete($perm{$test_perm});
                   8741: 	    }
1.285     albertel 8742: 	}
                   8743:     }
                   8744: }
                   8745: 
1.400     www      8746: sub gather_clicker_ids {
1.408     albertel 8747:     my %clicker_ids;
1.400     www      8748: 
                   8749:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8750: 
                   8751:     # Set up a couple variables.
1.407     albertel 8752:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8753:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8754:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8755: 
1.407     albertel 8756:     foreach my $student (keys(%$classlist)) {
1.438     www      8757:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8758:         my $username = $classlist->{$student}->[$username_idx];
                   8759:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8760:         my $clickers =
1.408     albertel 8761: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8762:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8763:             $id=~s/^[\#0]+//;
1.421     www      8764:             $id=~s/[\-\:]//g;
1.407     albertel 8765:             if (exists($clicker_ids{$id})) {
1.408     albertel 8766: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8767:             } else {
1.408     albertel 8768: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8769:             }
                   8770:         }
                   8771:     }
1.407     albertel 8772:     return %clicker_ids;
1.400     www      8773: }
                   8774: 
1.402     www      8775: sub gather_adv_clicker_ids {
1.408     albertel 8776:     my %clicker_ids;
1.402     www      8777:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8778:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8779:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8780:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8781:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8782:             my ($puname,$pudom)=split(/\:/,$person);
                   8783:             my $clickers =
1.408     albertel 8784: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8785:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8786: 		$id=~s/^[\#0]+//;
1.421     www      8787:                 $id=~s/[\-\:]//g;
1.408     albertel 8788: 		if (exists($clicker_ids{$id})) {
                   8789: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8790: 		} else {
                   8791: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8792: 		}
1.405     www      8793:             }
1.402     www      8794:         }
                   8795:     }
1.407     albertel 8796:     return %clicker_ids;
1.402     www      8797: }
                   8798: 
1.413     www      8799: sub clicker_grading_parameters {
                   8800:     return ('gradingmechanism' => 'scalar',
                   8801:             'upfiletype' => 'scalar',
                   8802:             'specificid' => 'scalar',
                   8803:             'pcorrect' => 'scalar',
                   8804:             'pincorrect' => 'scalar');
                   8805: }
                   8806: 
1.400     www      8807: sub process_clicker {
1.608     www      8808:     my ($r,$symb)=@_;
1.400     www      8809:     if (!$symb) {return '';}
                   8810:     my $result=&checkforfile_js();
1.632     www      8811:     $result.=&Apache::loncommon::start_data_table().
                   8812:              &Apache::loncommon::start_data_table_header_row().
                   8813:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8814:              &Apache::loncommon::end_data_table_header_row().
                   8815:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8816: # Attempt to restore parameters from last session, set defaults if not present
                   8817:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8818:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8819:                                                  \%Saveable_Parameters);
                   8820:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8821:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8822:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8823:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8824: 
                   8825:     my %checked;
1.521     www      8826:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8827:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8828:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8829:        }
                   8830:     }
                   8831: 
1.632     www      8832:     my $upload=&mt("Evaluate File");
1.400     www      8833:     my $type=&mt("Type");
1.402     www      8834:     my $attendance=&mt("Award points just for participation");
                   8835:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8836:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8837:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8838:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8839:     my $pcorrect=&mt("Percentage points for correct solution");
                   8840:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8841:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8842: 						   {'iclicker' => 'i>clicker',
                   8843:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8844:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8845:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8846: function sanitycheck() {
                   8847: // Accept only integer percentages
                   8848:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8849:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8850: // Find out grading choice
                   8851:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8852:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8853:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8854:       }
                   8855:    }
                   8856: // By default, new choice equals user selection
                   8857:    newgradingchoice=gradingchoice;
                   8858: // Not good to give more points for false answers than correct ones
                   8859:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8860:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8861:    }
                   8862: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8863:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8864:       document.forms.gradesupload.pcorrect.value=100;
                   8865:       document.forms.gradesupload.pincorrect.value=100;
                   8866:    }
                   8867: // If the values are different, cannot be attendance only
                   8868:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8869:        (gradingchoice=='attendance')) {
                   8870:        newgradingchoice='personnel';
                   8871:    }
                   8872: // Change grading choice to new one
                   8873:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8874:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8875:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8876:       } else {
                   8877:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8878:       }
                   8879:    }
                   8880: // Remember the old state
                   8881:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8882: }
1.597     wenzelju 8883: ENDUPFORM
                   8884:     $result.= <<ENDUPFORM;
1.400     www      8885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8886: <input type="hidden" name="symb" value="$symb" />
                   8887: <input type="hidden" name="command" value="processclickerfile" />
                   8888: <input type="file" name="upfile" size="50" />
                   8889: <br /><label>$type: $selectform</label>
1.632     www      8890: ENDUPFORM
                   8891:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8892:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8893:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8894: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8895: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8896: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8897: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8898: <br />&nbsp;&nbsp;&nbsp;
                   8899: <input type="text" name="givenanswer" size="50" />
1.413     www      8900: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8901: ENDGRADINGFORM
                   8902:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8903:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8904:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8905: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8906: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8907: </form>'
1.632     www      8908: ENDPERCFORM
                   8909:     $result.='</td>'.
                   8910:              &Apache::loncommon::end_data_table_row().
                   8911:              &Apache::loncommon::end_data_table();
1.400     www      8912:     return $result;
                   8913: }
                   8914: 
                   8915: sub process_clicker_file {
1.608     www      8916:     my ($r,$symb)=@_;
1.400     www      8917:     if (!$symb) {return '';}
1.413     www      8918: 
                   8919:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8920:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8921:                                               \%Saveable_Parameters);
1.598     www      8922:     my $result='';
1.404     www      8923:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8924: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8925: 	return $result;
1.404     www      8926:     }
1.522     www      8927:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8928:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8929:         return $result;
1.521     www      8930:     }
1.522     www      8931:     my $foundgiven=0;
1.521     www      8932:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8933:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8934:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      8935:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      8936:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8937:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8938:         $foundgiven=$#answers+1;
1.521     www      8939:     }
1.407     albertel 8940:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8941:     my %correct_ids;
1.404     www      8942:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8943: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8944:     }
                   8945:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8946: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8947: 	   $correct_id=~tr/a-z/A-Z/;
                   8948: 	   $correct_id=~s/\s//gs;
                   8949: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8950:            $correct_id=~s/[\-\:]//g;
1.414     www      8951:            if ($correct_id) {
                   8952: 	      $correct_ids{$correct_id}='specified';
                   8953:            }
                   8954:         }
1.400     www      8955:     }
1.404     www      8956:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8957: 	$result.=&mt('Score based on attendance only');
1.521     www      8958:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8959:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8960:     } else {
1.408     albertel 8961: 	my $number=0;
1.411     www      8962: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8963: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8964: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8965: 	    if ($correct_ids{$id} eq 'specified') {
                   8966: 		$result.=&mt('specified');
                   8967: 	    } else {
                   8968: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8969: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8970: 	    }
                   8971: 	    $number++;
                   8972: 	}
1.411     www      8973:         $result.="</p>\n";
1.408     albertel 8974: 	if ($number==0) {
                   8975: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8976: 	    return $result;
1.408     albertel 8977: 	}
1.404     www      8978:     }
1.405     www      8979:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8980:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8981: 		     '<span class="LC_error">',
                   8982: 		     '</span>',
                   8983: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8984:         return $result;
1.405     www      8985:     }
1.410     www      8986: 
                   8987: # Were able to get all the info needed, now analyze the file
                   8988: 
1.411     www      8989:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8990:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      8991:     $result.=&Apache::loncommon::start_data_table().
                   8992:              &Apache::loncommon::start_data_table_header_row().
                   8993:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   8994:              &Apache::loncommon::end_data_table_header_row().
                   8995:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   8996: <td>
1.410     www      8997: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8998: <input type="hidden" name="symb" value="$symb" />
                   8999: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9000: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9001: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9002: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9003: ENDHEADER
1.522     www      9004:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9005:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9006:     } 
1.408     albertel 9007:     my %responses;
                   9008:     my @questiontitles;
1.405     www      9009:     my $errormsg='';
                   9010:     my $number=0;
                   9011:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9012: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9013:     }
1.419     www      9014:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9015:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9016:     }
1.411     www      9017:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9018:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9019:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9020:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9021:              '<br />';
1.522     www      9022:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9023:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9024:        return $result;
1.522     www      9025:     } 
1.414     www      9026: # Remember Question Titles
                   9027: # FIXME: Possibly need delimiter other than ":"
                   9028:     for (my $i=0;$i<$number;$i++) {
                   9029:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9030:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9031:     }
1.411     www      9032:     my $correct_count=0;
                   9033:     my $student_count=0;
                   9034:     my $unknown_count=0;
1.414     www      9035: # Match answers with usernames
                   9036: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9037:     foreach my $id (keys(%responses)) {
1.410     www      9038:        if ($correct_ids{$id}) {
1.414     www      9039:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9040:           $correct_count++;
1.410     www      9041:        } elsif ($clicker_ids{$id}) {
1.437     www      9042:           if ($clicker_ids{$id}=~/\,/) {
                   9043: # More than one user with the same clicker!
1.632     www      9044:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9045:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9046:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9047:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9048:                            "<select name='multi".$id."'>";
                   9049:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9050:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9051:              }
                   9052:              $result.='</select>';
                   9053:              $unknown_count++;
                   9054:           } else {
                   9055: # Good: found one and only one user with the right clicker
                   9056:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9057:              $student_count++;
                   9058:           }
1.410     www      9059:        } else {
1.632     www      9060:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9061:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9062:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9063:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9064:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9065:                    "\n".&mt("Domain").": ".
                   9066:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9067:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9068:           $unknown_count++;
1.410     www      9069:        }
1.405     www      9070:     }
1.412     www      9071:     $result.='<hr />'.
                   9072:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9073:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9074:        if ($correct_count==0) {
                   9075:           $errormsg.="Found no correct answers answers for grading!";
                   9076:        } elsif ($correct_count>1) {
1.414     www      9077:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9078:        }
                   9079:     }
1.428     www      9080:     if ($number<1) {
                   9081:        $errormsg.="Found no questions.";
                   9082:     }
1.412     www      9083:     if ($errormsg) {
                   9084:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9085:     } else {
                   9086:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9087:     }
1.632     www      9088:     $result.='</form></td>'.
                   9089:              &Apache::loncommon::end_data_table_row().
                   9090:              &Apache::loncommon::end_data_table();
1.614     www      9091:     return $result;
1.400     www      9092: }
                   9093: 
1.405     www      9094: sub iclicker_eval {
1.406     www      9095:     my ($questiontitles,$responses)=@_;
1.405     www      9096:     my $number=0;
                   9097:     my $errormsg='';
                   9098:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9099:         my %components=&Apache::loncommon::record_sep($line);
                   9100:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9101: 	if ($entries[0] eq 'Question') {
                   9102: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9103: 		$$questiontitles[$number]=$entries[$i];
                   9104: 		$number++;
                   9105: 	    }
                   9106: 	}
                   9107: 	if ($entries[0]=~/^\#/) {
                   9108: 	    my $id=$entries[0];
                   9109: 	    my @idresponses;
                   9110: 	    $id=~s/^[\#0]+//;
                   9111: 	    for (my $i=0;$i<$number;$i++) {
                   9112: 		my $idx=3+$i*6;
1.644     www      9113:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9114: 		push(@idresponses,$entries[$idx]);
                   9115: 	    }
                   9116: 	    $$responses{$id}=join(',',@idresponses);
                   9117: 	}
1.405     www      9118:     }
                   9119:     return ($errormsg,$number);
                   9120: }
                   9121: 
1.419     www      9122: sub interwrite_eval {
                   9123:     my ($questiontitles,$responses)=@_;
                   9124:     my $number=0;
                   9125:     my $errormsg='';
1.420     www      9126:     my $skipline=1;
                   9127:     my $questionnumber=0;
                   9128:     my %idresponses=();
1.419     www      9129:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9130:         my %components=&Apache::loncommon::record_sep($line);
                   9131:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9132:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9133:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9134:         next if $skipline;
                   9135:         if ($entries[0]!=$questionnumber) {
                   9136:            $questionnumber=$entries[0];
                   9137:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9138:            $number++;
1.419     www      9139:         }
1.420     www      9140:         my $id=$entries[4];
                   9141:         $id=~s/^[\#0]+//;
1.421     www      9142:         $id=~s/^v\d*\://i;
                   9143:         $id=~s/[\-\:]//g;
1.420     www      9144:         $idresponses{$id}[$number]=$entries[6];
                   9145:     }
1.524     raeburn  9146:     foreach my $id (keys(%idresponses)) {
1.420     www      9147:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9148:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9149:     }
                   9150:     return ($errormsg,$number);
                   9151: }
                   9152: 
1.414     www      9153: sub assign_clicker_grades {
1.608     www      9154:     my ($r,$symb)=@_;
1.414     www      9155:     if (!$symb) {return '';}
1.416     www      9156: # See which part we are saving to
1.582     raeburn  9157:     my $res_error;
                   9158:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9159:     if ($res_error) {
                   9160:         return &navmap_errormsg();
                   9161:     }
1.416     www      9162: # FIXME: This should probably look for the first handgradeable part
                   9163:     my $part=$$partlist[0];
                   9164: # Start screen output
1.632     www      9165:     my $result=&Apache::loncommon::start_data_table().
                   9166:              &Apache::loncommon::start_data_table_header_row().
                   9167:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9168:              &Apache::loncommon::end_data_table_header_row().
                   9169:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9170: # Get correct result
                   9171: # FIXME: Possibly need delimiter other than ":"
                   9172:     my @correct=();
1.415     www      9173:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9174:     my $number=$env{'form.number'};
                   9175:     if ($gradingmechanism ne 'attendance') {
1.414     www      9176:        foreach my $key (keys(%env)) {
                   9177:           if ($key=~/^form\.correct\:/) {
                   9178:              my @input=split(/\,/,$env{$key});
                   9179:              for (my $i=0;$i<=$#input;$i++) {
                   9180:                  if (($correct[$i]) && ($input[$i]) &&
                   9181:                      ($correct[$i] ne $input[$i])) {
                   9182:                     $result.='<br /><span class="LC_warning">'.
                   9183:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9184:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9185:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9186:                     $correct[$i]=$input[$i];
                   9187:                  }
                   9188:              }
                   9189:           }
                   9190:        }
1.415     www      9191:        for (my $i=0;$i<$number;$i++) {
1.644     www      9192:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9193:              $result.='<br /><span class="LC_error">'.
                   9194:                       &mt('No correct result given for question "[_1]"!',
                   9195:                           $env{'form.question:'.$i}).'</span>';
                   9196:           }
                   9197:        }
1.644     www      9198:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9199:     }
                   9200: # Start grading
1.415     www      9201:     my $pcorrect=$env{'form.pcorrect'};
                   9202:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9203:     my $storecount=0;
1.632     www      9204:     my %users=();
1.415     www      9205:     foreach my $key (keys(%env)) {
1.420     www      9206:        my $user='';
1.415     www      9207:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9208:           $user=$1;
                   9209:        }
                   9210:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9211:           my $id=$1;
                   9212:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9213:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9214:           } elsif ($env{'form.multi'.$id}) {
                   9215:              $user=$env{'form.multi'.$id};
1.420     www      9216:           }
                   9217:        }
1.632     www      9218:        if ($user) {
                   9219:           if ($users{$user}) {
                   9220:              $result.='<br /><span class="LC_warning">'.
                   9221:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9222:                       '</span><br />';
                   9223:           }
                   9224:           $users{$user}=1; 
1.415     www      9225:           my @answer=split(/\,/,$env{$key});
                   9226:           my $sum=0;
1.522     www      9227:           my $realnumber=$number;
1.415     www      9228:           for (my $i=0;$i<$number;$i++) {
1.576     www      9229:              if  ($correct[$i] eq '-') {
                   9230:                 $realnumber--;
1.644     www      9231:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9232:                 if ($gradingmechanism eq 'attendance') {
                   9233:                    $sum+=$pcorrect;
1.576     www      9234:                 } elsif ($correct[$i] eq '*') {
1.522     www      9235:                    $sum+=$pcorrect;
1.415     www      9236:                 } else {
1.644     www      9237: # We actually grade if correct or not
                   9238:                    my $increment=$pincorrect;
                   9239: # Special case: numerical answer "0"
                   9240:                    if ($correct[$i] eq '0') {
                   9241:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9242:                          $increment=$pcorrect;
                   9243:                       }
                   9244: # General numerical answer, both evaluate to something non-zero
                   9245:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9246:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9247:                          $increment=$pcorrect;
                   9248:                       }
                   9249: # Must be just alphanumeric
                   9250:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9251:                       $increment=$pcorrect;
1.415     www      9252:                    }
1.644     www      9253:                    $sum+=$increment;
1.415     www      9254:                 }
                   9255:              }
                   9256:           }
1.522     www      9257:           my $ave=$sum/(100*$realnumber);
1.416     www      9258: # Store
                   9259:           my ($username,$domain)=split(/\:/,$user);
                   9260:           my %grades=();
                   9261:           $grades{"resource.$part.solved"}='correct_by_override';
                   9262:           $grades{"resource.$part.awarded"}=$ave;
                   9263:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9264:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9265:                                                  $env{'request.course.id'},
                   9266:                                                  $domain,$username);
                   9267:           if ($returncode ne 'ok') {
                   9268:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9269:           } else {
                   9270:              $storecount++;
                   9271:           }
1.415     www      9272:        }
                   9273:     }
                   9274: # We are done
1.549     hauer    9275:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9276:              '</td>'.
                   9277:              &Apache::loncommon::end_data_table_row().
                   9278:              &Apache::loncommon::end_data_table();
1.614     www      9279:     return $result;
1.414     www      9280: }
                   9281: 
1.582     raeburn  9282: sub navmap_errormsg {
                   9283:     return '<div class="LC_error">'.
                   9284:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9285:            &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  9286:            '</div>';
                   9287: }
1.607     droeschl 9288: 
1.609     www      9289: sub startpage {
1.613     www      9290:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9291:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9292:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9293:                                           {'bread_crumbs' => $crumbs}));
1.645     www      9294:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
1.613     www      9295:     unless ($nodisplayflag) {
                   9296:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9297:     }
1.607     droeschl 9298: }
1.582     raeburn  9299: 
1.622     www      9300: sub select_problem {
                   9301:     my ($r)=@_;
1.632     www      9302:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9303:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9304:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9305:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9306: }
                   9307: 
1.1       albertel 9308: sub handler {
1.41      ng       9309:     my $request=$_[0];
1.434     albertel 9310:     &reset_caches();
1.646     raeburn  9311:     if ($request->header_only) {
                   9312:         &Apache::loncommon::content_type($request,'text/html');
                   9313:         $request->send_http_header;
                   9314:         return OK;
                   9315:     }
                   9316:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9317: 
                   9318:     &init_perm();
                   9319:     if (!$env{'request.course.id'}) {
                   9320:         # Not in a course.
                   9321:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9322:         return HTTP_NOT_ACCEPTABLE;
                   9323:     } elsif (!%perm) {
                   9324:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9325:     }
1.646     raeburn  9326:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9327:     $request->send_http_header;
1.646     raeburn  9328: 
1.608     www      9329: 
                   9330: # see what command we need to execute
                   9331: 
1.160     albertel 9332:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9333:     my $command=$commands[0];
1.447     foxr     9334: 
1.160     albertel 9335:     if ($#commands > 0) {
                   9336: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9337:     }
1.608     www      9338: 
                   9339: # see what the symb is
                   9340: 
                   9341:     my $symb=$env{'form.symb'};
                   9342:     unless ($symb) {
                   9343:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9344:        $symb=&Apache::lonnet::symbread($url);
                   9345:     }
1.646     raeburn  9346:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9347: 
1.513     foxr     9348:     $ssi_error = 0;
1.637     www      9349:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9350: #
1.637     www      9351: # Not called from a resource, but inside a course
1.601     www      9352: #    
1.622     www      9353:         &startpage($request,undef,[],1,1);
                   9354:         &select_problem($request);
1.41      ng       9355:     } else {
1.104     albertel 9356: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9357:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9358: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9359: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9360:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9361:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9362: 	    &pickStudentPage($request,$symb);
1.103     albertel 9363: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9364:             &startpage($request,$symb,
                   9365:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9366:                                        {href=>'',text=>'Select student'},
                   9367:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9368: 	    &displayPage($request,$symb);
1.104     albertel 9369: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9370:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9371:                                        {href=>'',text=>'Select student'},
                   9372:                                        {href=>'',text=>'Grade student'},
                   9373:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9374: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9375: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9376:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9377:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9378: 	    &processGroup($request,$symb);
1.104     albertel 9379: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9380:             &startpage($request,$symb);
                   9381: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9382: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9383:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9384: 	    $request->print(&submit_options($request,$symb));
1.598     www      9385:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9386:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9387:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9388:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9389:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9390:             $request->print(&submit_options_table($request,$symb));
1.598     www      9391:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9392:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9393:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9394: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9395:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9396: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9397: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9398:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9399:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9400: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9401: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9402:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9403:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9404:                                                                              text=>"Modify grades"},
                   9405:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9406: 	    $request->print(&editgrades($request,$symb));
1.602     www      9407:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9408:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9409:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9410: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9411:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9412:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9413: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9414:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9415:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9416:             $request->print(&process_clicker($request,$symb));
1.400     www      9417:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9418:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9419:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9420:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9421:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9422:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9423:                                        {href=>'', text=>'Process clicker file'},
                   9424:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9425:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9426: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9427:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9428: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9429: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9430:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9431: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9432: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9433:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9434: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9435: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9436: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9437:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9438: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9439: 	    } else {
1.257     albertel 9440: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9441: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9442: 		} else {
1.257     albertel 9443: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9444: 		}
1.627     www      9445:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9446: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9447: 	    }
1.246     albertel 9448: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9449:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9450: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9451: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9452:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9453: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9454:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9455:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9456:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9457: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9458:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9459: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9460: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9461:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9462: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9463:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9464:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9465: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9466:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9467:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9468:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9469:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9470: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9471:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9472:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9473:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9474: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9475:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9476:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9477:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9478:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9479:             $request->print(&checkscantron_results($request,$symb));
                   9480:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9481:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9482:             $request->print(&submit_options_download($request,$symb));
                   9483:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9484:             &startpage($request,$symb,
                   9485:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9486:     {href=>'', text=>'Download submissions'}]);
                   9487:             &submit_download_link($request,$symb);
1.106     albertel 9488: 	} elsif ($command) {
1.620     www      9489:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9490: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9491: 	}
1.2       albertel 9492:     }
1.513     foxr     9493:     if ($ssi_error) {
                   9494: 	&ssi_print_error($request);
                   9495:     }
1.639     www      9496:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9497:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9498:     &reset_caches();
1.646     raeburn  9499:     return OK;
1.44      ng       9500: }
                   9501: 
1.1       albertel 9502: 1;
                   9503: 
1.13      albertel 9504: __END__;
1.531     jms      9505: 
                   9506: 
                   9507: =head1 NAME
                   9508: 
                   9509: Apache::grades
                   9510: 
                   9511: =head1 SYNOPSIS
                   9512: 
                   9513: Handles the viewing of grades.
                   9514: 
                   9515: This is part of the LearningOnline Network with CAPA project
                   9516: described at http://www.lon-capa.org.
                   9517: 
                   9518: =head1 OVERVIEW
                   9519: 
                   9520: Do an ssi with retries:
                   9521: While I'd love to factor out this with the vesrion in lonprintout,
                   9522: 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
                   9523: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9524: 
                   9525: At least the logic that drives this has been pulled out into loncommon.
                   9526: 
                   9527: 
                   9528: 
                   9529: ssi_with_retries - Does the server side include of a resource.
                   9530:                      if the ssi call returns an error we'll retry it up to
                   9531:                      the number of times requested by the caller.
                   9532:                      If we still have a proble, no text is appended to the
                   9533:                      output and we set some global variables.
                   9534:                      to indicate to the caller an SSI error occurred.  
                   9535:                      All of this is supposed to deal with the issues described
                   9536:                      in LonCAPA BZ 5631 see:
                   9537:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9538:                      by informing the user that this happened.
                   9539: 
                   9540: Parameters:
                   9541:   resource   - The resource to include.  This is passed directly, without
                   9542:                interpretation to lonnet::ssi.
                   9543:   form       - The form hash parameters that guide the interpretation of the resource
                   9544:                
                   9545:   retries    - Number of retries allowed before giving up completely.
                   9546: Returns:
                   9547:   On success, returns the rendered resource identified by the resource parameter.
                   9548: Side Effects:
                   9549:   The following global variables can be set:
                   9550:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9551:                               It is up to the caller to initialize this to false
                   9552:                               if desired.
                   9553:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9554:                               of the resource that could not be rendered by the ssi
                   9555:                               call.
                   9556:    ssi_error_message   - The error string fetched from the ssi response
                   9557:                               in the event of an error.
                   9558: 
                   9559: 
                   9560: =head1 HANDLER SUBROUTINE
                   9561: 
                   9562: ssi_with_retries()
                   9563: 
                   9564: =head1 SUBROUTINES
                   9565: 
                   9566: =over
                   9567: 
                   9568: =item scantron_get_correction() : 
                   9569: 
                   9570:    Builds the interface screen to interact with the operator to fix a
                   9571:    specific error condition in a specific scanline
                   9572: 
                   9573:  Arguments:
                   9574:     $r           - Apache request object
                   9575:     $i           - number of the current scanline
                   9576:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9577:     $scan_config - hash ref as returned from &get_scantron_config()
                   9578:     $line        - full contents of the current scanline
                   9579:     $error       - error condition, valid values are
                   9580:                    'incorrectCODE', 'duplicateCODE',
                   9581:                    'doublebubble', 'missingbubble',
                   9582:                    'duplicateID', 'incorrectID'
                   9583:     $arg         - extra information needed
                   9584:        For errors:
                   9585:          - duplicateID   - paper number that this studentID was seen before on
                   9586:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9587:                            seen on before
                   9588:          - incorrectCODE - current incorrect CODE 
                   9589:          - doublebubble  - array ref of the bubble lines that have double
                   9590:                            bubble errors
                   9591:          - missingbubble - array ref of the bubble lines that have missing
                   9592:                            bubble errors
                   9593: 
                   9594: =item  scantron_get_maxbubble() : 
                   9595: 
1.582     raeburn  9596:    Arguments:
                   9597:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9598:                       failure to retrieve a navmap object.
                   9599:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9600:        calling routine should trap the error condition and display the warning
                   9601:        found in &navmap_errormsg().
                   9602: 
1.649     raeburn  9603:        $scantron_config - Reference to bubblesheet format configuration hash.
                   9604: 
1.531     jms      9605:    Returns the maximum number of bubble lines that are expected to
                   9606:    occur. Does this by walking the selected sequence rendering the
                   9607:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9608:    for what the current value of the problem counter is.
                   9609: 
                   9610:    Caches the results to $env{'form.scantron_maxbubble'},
                   9611:    $env{'form.scantron.bubble_lines.n'}, 
                   9612:    $env{'form.scantron.first_bubble_line.n'} and
                   9613:    $env{"form.scantron.sub_bubblelines.n"}
                   9614:    which are the total number of bubble, lines, the number of bubble
                   9615:    lines for response n and number of the first bubble line for response n,
                   9616:    and a comma separated list of numbers of bubble lines for sub-questions
                   9617:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9618: 
                   9619: 
                   9620: =item  scantron_validate_missingbubbles() : 
                   9621: 
                   9622:    Validates all scanlines in the selected file to not have any
                   9623:     answers that don't have bubbles that have not been verified
                   9624:     to be bubble free.
                   9625: 
                   9626: =item  scantron_process_students() : 
                   9627: 
                   9628:    Routine that does the actual grading of the bubble sheet information.
                   9629: 
                   9630:    The parsed scanline hash is added to %env 
                   9631: 
                   9632:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9633:    foreach resource , with the form data of
                   9634: 
                   9635: 	'submitted'     =>'scantron' 
                   9636: 	'grade_target'  =>'grade',
                   9637: 	'grade_username'=> username of student
                   9638: 	'grade_domain'  => domain of student
                   9639: 	'grade_courseid'=> of course
                   9640: 	'grade_symb'    => symb of resource to grade
                   9641: 
                   9642:     This triggers a grading pass. The problem grading code takes care
                   9643:     of converting the bubbled letter information (now in %env) into a
                   9644:     valid submission.
                   9645: 
                   9646: =item  scantron_upload_scantron_data() :
                   9647: 
                   9648:     Creates the screen for adding a new bubble sheet data file to a course.
                   9649: 
                   9650: =item  scantron_upload_scantron_data_save() : 
                   9651: 
                   9652:    Adds a provided bubble information data file to the course if user
                   9653:    has the correct privileges to do so. 
                   9654: 
                   9655: =item  valid_file() :
                   9656: 
                   9657:    Validates that the requested bubble data file exists in the course.
                   9658: 
                   9659: =item  scantron_download_scantron_data() : 
                   9660: 
                   9661:    Shows a list of the three internal files (original, corrected,
                   9662:    skipped) for a specific bubble sheet data file that exists in the
                   9663:    course.
                   9664: 
                   9665: =item  scantron_validate_ID() : 
                   9666: 
                   9667:    Validates all scanlines in the selected file to not have any
1.556     weissno  9668:    invalid or underspecified student/employee IDs
1.531     jms      9669: 
1.582     raeburn  9670: =item navmap_errormsg() :
                   9671: 
                   9672:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9673:    Should be called whenever the request to instantiate a navmap object fails.  
                   9674: 
1.531     jms      9675: =back
                   9676: 
                   9677: =cut

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