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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.662   ! raeburn     4: # $Id: grades.pm,v 1.661 2011/10/11 18:04:40 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.447     foxr       57: 
1.513     foxr       58: #  These variables are used to recover from ssi errors
                     59: 
                     60: my $ssi_retries = 5;
                     61: my $ssi_error;
                     62: my $ssi_error_resource;
                     63: my $ssi_error_message;
                     64: 
                     65: 
                     66: sub ssi_with_retries {
                     67:     my ($resource, $retries, %form) = @_;
                     68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     69:     if ($response->is_error) {
                     70: 	$ssi_error          = 1;
                     71: 	$ssi_error_resource = $resource;
                     72: 	$ssi_error_message  = $response->code . " " . $response->message;
                     73:     }
                     74: 
                     75:     return $content;
                     76: 
                     77: }
                     78: #
                     79: #  Prodcuces an ssi retry failure error message to the user:
                     80: #
                     81: 
                     82: sub ssi_print_error {
                     83:     my ($r) = @_;
1.516     raeburn    84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     85:     $r->print('
                     86: <br />
                     87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     88: <p>
                     89: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     91: '.&mt('Error:').' '.$ssi_error_message.'
                     92: </p>
                     93: <p>'.
                     94: &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 />'.
                     95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     96: '</p>');
                     97:     return;
1.513     foxr       98: }
                     99: 
1.44      ng        100: #
1.146     albertel  101: # --- Retrieve the parts from the metadata file.---
1.598     www       102: # Returns an array of everything that the resources stores away
                    103: #
                    104: 
1.44      ng        105: sub getpartlist {
1.582     raeburn   106:     my ($symb,$errorref) = @_;
1.439     albertel  107: 
                    108:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   109:     unless (ref($navmap)) {
                    110:         if (ref($errorref)) { 
                    111:             $$errorref = 'navmap';
                    112:             return;
                    113:         }
                    114:     }
1.439     albertel  115:     my $res      = $navmap->getBySymb($symb);
                    116:     my $partlist = $res->parts();
                    117:     my $url      = $res->src();
                    118:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    119: 
1.146     albertel  120:     my @stores;
1.439     albertel  121:     foreach my $part (@{ $partlist }) {
1.146     albertel  122: 	foreach my $key (@metakeys) {
                    123: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    124: 	}
                    125:     }
                    126:     return @stores;
1.2       albertel  127: }
                    128: 
1.129     ng        129: #--- Format fullname, username:domain if different for display
                    130: #--- Use anywhere where the student names are listed
                    131: sub nameUserString {
                    132:     my ($type,$fullname,$uname,$udom) = @_;
                    133:     if ($type eq 'header') {
1.485     albertel  134: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        135:     } else {
1.398     albertel  136: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    137: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        138:     }
                    139: }
                    140: 
1.44      ng        141: #--- Get the partlist and the response type for a given problem. ---
                    142: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       143: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        144: sub response_type {
1.582     raeburn   145:     my ($symb,$response_error) = @_;
1.377     albertel  146: 
                    147:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   148:     unless (ref($navmap)) {
                    149:         if (ref($response_error)) {
                    150:             $$response_error = 1;
                    151:         }
                    152:         return;
                    153:     }
1.377     albertel  154:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   155:     unless (ref($res)) {
                    156:         $$response_error = 1;
                    157:         return;
                    158:     }
1.377     albertel  159:     my $partlist = $res->parts();
1.392     albertel  160:     my %vPart = 
                    161: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  162:     my (%response_types,%handgrade);
                    163:     foreach my $part (@{ $partlist }) {
1.392     albertel  164: 	next if (%vPart && !exists($vPart{$part}));
                    165: 
1.377     albertel  166: 	my @types = $res->responseType($part);
                    167: 	my @ids = $res->responseIds($part);
                    168: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    169: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    170: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    171: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    172: 				     '.handgrade',$symb);
1.41      ng        173: 	}
                    174:     }
1.377     albertel  175:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        176: }
                    177: 
1.375     albertel  178: sub flatten_responseType {
                    179:     my ($responseType) = @_;
                    180:     my @part_response_id =
                    181: 	map { 
                    182: 	    my $part = $_;
                    183: 	    map {
                    184: 		[$part,$_]
                    185: 		} sort(keys(%{ $responseType->{$part} }));
                    186: 	} sort(keys(%$responseType));
                    187:     return @part_response_id;
                    188: }
                    189: 
1.207     albertel  190: sub get_display_part {
1.324     albertel  191:     my ($partID,$symb)=@_;
1.207     albertel  192:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    193:     if (defined($display) and $display ne '') {
1.577     bisitz    194:         $display.= ' (<span class="LC_internal_info">'
                    195:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  196:     } else {
                    197: 	$display=$partID;
                    198:     }
                    199:     return $display;
                    200: }
1.269     raeburn   201: 
1.434     albertel  202: sub reset_caches {
                    203:     &reset_analyze_cache();
                    204:     &reset_perm();
                    205: }
                    206: 
                    207: {
                    208:     my %analyze_cache;
1.557     raeburn   209:     my %analyze_cache_formkeys;
1.148     albertel  210: 
1.434     albertel  211:     sub reset_analyze_cache {
                    212: 	undef(%analyze_cache);
1.557     raeburn   213:         undef(%analyze_cache_formkeys);
1.434     albertel  214:     }
                    215: 
                    216:     sub get_analyze {
1.649     raeburn   217: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  218: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   219:         if ($type eq 'randomizetry') {
                    220:             if ($trial ne '') {
                    221:                 $key .= "\0".$trial;
                    222:             }
                    223:         }
1.557     raeburn   224: 	if (exists($analyze_cache{$key})) {
                    225:             my $getupdate = 0;
                    226:             if (ref($add_to_hash) eq 'HASH') {
                    227:                 foreach my $item (keys(%{$add_to_hash})) {
                    228:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    229:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    230:                             $getupdate = 1;
                    231:                             last;
                    232:                         }
                    233:                     } else {
                    234:                         $getupdate = 1;
                    235:                     }
                    236:                 }
                    237:             }
                    238:             if (!$getupdate) {
                    239:                 return $analyze_cache{$key};
                    240:             }
                    241:         }
1.434     albertel  242: 
                    243: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    244: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   245:         my %form = ('grade_target'      => 'analyze',
                    246:                     'grade_domain'      => $udom,
                    247:                     'grade_symb'        => $symb,
                    248:                     'grade_courseid'    =>  $env{'request.course.id'},
                    249:                     'grade_username'    => $uname,
                    250:                     'grade_noincrement' => $no_increment);
1.649     raeburn   251:         if ($bubbles_per_row ne '') {
                    252:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    253:         }
1.640     raeburn   254:         if ($type eq 'randomizetry') {
                    255:             $form{'grade_questiontype'} = $type;
                    256:             if ($rndseed ne '') {
                    257:                 $form{'grade_rndseed'} = $rndseed;
                    258:             }
                    259:         }
1.557     raeburn   260:         if (ref($add_to_hash)) {
                    261:             %form = (%form,%{$add_to_hash});
1.640     raeburn   262:         }
1.557     raeburn   263: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  264: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    265: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   266:         if (ref($add_to_hash) eq 'HASH') {
                    267:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    268:         } else {
                    269:             $analyze_cache_formkeys{$key} = {};
                    270:         }
1.434     albertel  271: 	return $analyze_cache{$key} = \%analyze;
                    272:     }
                    273: 
                    274:     sub get_order {
1.640     raeburn   275: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    276: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  277: 	return $analyze->{"$partid.$respid.shown"};
                    278:     }
                    279: 
                    280:     sub get_radiobutton_correct_foil {
1.640     raeburn   281: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    282: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    283:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   284:         if (ref($foils) eq 'ARRAY') {
                    285: 	    foreach my $foil (@{$foils}) {
                    286: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    287: 		    return $foil;
                    288: 	        }
1.434     albertel  289: 	    }
                    290: 	}
                    291:     }
1.554     raeburn   292: 
                    293:     sub scantron_partids_tograde {
1.649     raeburn   294:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   295:         my (%analysis,@parts);
                    296:         if (ref($resource)) {
                    297:             my $symb = $resource->symb();
1.557     raeburn   298:             my $add_to_form;
                    299:             if ($check_for_randomlist) {
                    300:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    301:             }
1.649     raeburn   302:             my $analyze = 
                    303:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    304:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   305:             if (ref($analyze) eq 'HASH') {
                    306:                 %analysis = %{$analyze};
                    307:             }
                    308:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    309:                 foreach my $part (@{$analysis{'parts'}}) {
                    310:                     my ($id,$respid) = split(/\./,$part);
                    311:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    312:                         push(@parts,$part);
                    313:                     }
                    314:                 }
                    315:             }
                    316:         }
                    317:         return (\%analysis,\@parts);
                    318:     }
                    319: 
1.148     albertel  320: }
1.434     albertel  321: 
1.118     ng        322: #--- Clean response type for display
1.335     albertel  323: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    324: #        response types only.
1.118     ng        325: sub cleanRecord {
1.336     albertel  326:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   327: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  328:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  329:     if ($response =~ /^(option|rank)$/) {
                    330: 	my %answer=&Apache::lonnet::str2hash($answer);
                    331: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    332: 	my ($toprow,$bottomrow);
                    333: 	foreach my $foil (@$order) {
                    334: 	    if ($grading{$foil} == 1) {
                    335: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    336: 	    } else {
                    337: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    338: 	    }
1.398     albertel  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  340: 	}
                    341: 	return '<blockquote><table border="1">'.
1.466     albertel  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   344: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  345:     } elsif ($response eq 'match') {
                    346: 	my %answer=&Apache::lonnet::str2hash($answer);
                    347: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    348: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    349: 	my ($toprow,$middlerow,$bottomrow);
                    350: 	foreach my $foil (@$order) {
                    351: 	    my $item=shift(@items);
                    352: 	    if ($grading{$foil} == 1) {
                    353: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  354: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  355: 	    } else {
                    356: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  357: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  358: 	    }
1.398     albertel  359: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        360: 	}
1.126     ng        361: 	return '<blockquote><table border="1">'.
1.466     albertel  362: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    363: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  364: 	    $middlerow.'</tr>'.
1.466     albertel  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   366: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  367:     } elsif ($response eq 'radiobutton') {
                    368: 	my %answer=&Apache::lonnet::str2hash($answer);
                    369: 	my ($toprow,$bottomrow);
1.434     albertel  370: 	my $correct = 
1.640     raeburn   371: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  372: 	foreach my $foil (@$order) {
1.148     albertel  373: 	    if (exists($answer{$foil})) {
1.434     albertel  374: 		if ($foil eq $correct) {
1.466     albertel  375: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  376: 		} else {
1.466     albertel  377: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  378: 		}
                    379: 	    } else {
1.466     albertel  380: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  381: 	    }
1.398     albertel  382: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  383: 	}
                    384: 	return '<blockquote><table border="1">'.
1.466     albertel  385: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    386: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   387: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  388:     } elsif ($response eq 'essay') {
1.257     albertel  389: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        390: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  391: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    392: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        393: 
1.257     albertel  394: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    395: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    396: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    397: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    398: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    399: 	    $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        400: 	}
1.166     albertel  401: 	$answer =~ s-\n-<br />-g;
                    402: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  403:     } elsif ( $response eq 'organic') {
                    404: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    405: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    406: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    407: 	return $result;
1.335     albertel  408:     } elsif ( $response eq 'Task') {
                    409: 	if ( $answer eq 'SUBMITTED') {
                    410: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  411: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  412: 	    return $result;
                    413: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    414: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    415: 			       keys(%{$record}));
                    416: 	    return join('<br />',($version,@matches));
                    417: 			       
                    418: 			       
                    419: 	} else {
                    420: 	    my $result =
                    421: 		'<p>'
                    422: 		.&mt('Overall result: [_1]',
                    423: 		     $record->{$version."resource.$respid.$partid.status"})
                    424: 		.'</p>';
                    425: 	    
                    426: 	    $result .= '<ul>';
                    427: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    428: 			     keys(%{$record}));
                    429: 	    foreach my $grade (sort(@grade)) {
                    430: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    431: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    432: 				     $dim, $record->{$grade}).
                    433: 			  '</li>';
                    434: 	    }
                    435: 	    $result.='</ul>';
                    436: 	    return $result;
                    437: 	}
1.440     albertel  438:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    439: 	$answer = 
                    440: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    441: 							      $answer);
1.122     ng        442:     }
1.118     ng        443:     return $answer;
                    444: }
                    445: 
                    446: #-- A couple of common js functions
                    447: sub commonJSfunctions {
                    448:     my $request = shift;
1.597     wenzelju  449:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        450:     function radioSelection(radioButton) {
                    451: 	var selection=null;
                    452: 	if (radioButton.length > 1) {
                    453: 	    for (var i=0; i<radioButton.length; i++) {
                    454: 		if (radioButton[i].checked) {
                    455: 		    return radioButton[i].value;
                    456: 		}
                    457: 	    }
                    458: 	} else {
                    459: 	    if (radioButton.checked) return radioButton.value;
                    460: 	}
                    461: 	return selection;
                    462:     }
                    463: 
                    464:     function pullDownSelection(selectOne) {
                    465: 	var selection="";
                    466: 	if (selectOne.length > 1) {
                    467: 	    for (var i=0; i<selectOne.length; i++) {
                    468: 		if (selectOne[i].selected) {
                    469: 		    return selectOne[i].value;
                    470: 		}
                    471: 	    }
                    472: 	} else {
1.138     albertel  473:             // only one value it must be the selected one
                    474: 	    return selectOne.value;
1.118     ng        475: 	}
                    476:     }
                    477: COMMONJSFUNCTIONS
                    478: }
                    479: 
1.44      ng        480: #--- Dumps the class list with usernames,list of sections,
                    481: #--- section, ids and fullnames for each user.
                    482: sub getclasslist {
1.449     banghart  483:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  484:     my @getsec;
1.450     banghart  485:     my @getgroup;
1.442     banghart  486:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  487:     if (!ref($getsec)) {
                    488: 	if ($getsec ne '' && $getsec ne 'all') {
                    489: 	    @getsec=($getsec);
                    490: 	}
                    491:     } else {
                    492: 	@getsec=@{$getsec};
                    493:     }
                    494:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  495:     if (!ref($getgroup)) {
                    496: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    497: 	    @getgroup=($getgroup);
                    498: 	}
                    499:     } else {
                    500: 	@getgroup=@{$getgroup};
                    501:     }
                    502:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  503: 
1.449     banghart  504:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  505:     # Bail out if we were unable to get the classlist
1.56      matthew   506:     return if (! defined($classlist));
1.449     banghart  507:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   508:     #
                    509:     my %sections;
                    510:     my %fullnames;
1.205     matthew   511:     foreach my $student (keys(%$classlist)) {
                    512:         my $end      = 
                    513:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    514:         my $start    = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    516:         my $id       = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    518:         my $section  = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    520:         my $fullname = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    522:         my $status   = 
                    523:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  524:         my $group   = 
                    525:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        526: 	# filter students according to status selected
1.442     banghart  527: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    528: 	    if (!($stu_status =~ $status)) {
1.450     banghart  529: 		delete($classlist->{$student});
1.76      ng        530: 		next;
                    531: 	    }
                    532: 	}
1.450     banghart  533: 	# filter students according to groups selected
1.453     banghart  534: 	my @stu_groups = split(/,/,$group);
1.450     banghart  535: 	if (@getgroup) {
                    536: 	    my $exclude = 1;
1.454     banghart  537: 	    foreach my $grp (@getgroup) {
                    538: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  539: 	            if ($stu_group eq $grp) {
                    540: 	                $exclude = 0;
                    541:     	            } 
1.450     banghart  542: 	        }
1.453     banghart  543:     	        if (($grp eq 'none') && !$group) {
                    544:         	        $exclude = 0;
                    545:         	}
1.450     banghart  546: 	    }
                    547: 	    if ($exclude) {
                    548: 	        delete($classlist->{$student});
                    549: 	    }
                    550: 	}
1.205     matthew   551: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  552: 	if (&canview($section)) {
1.291     albertel  553: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  554: 		$sections{$section}++;
1.450     banghart  555: 		if ($classlist->{$student}) {
                    556: 		    $fullnames{$student}=$fullname;
                    557: 		}
1.103     albertel  558: 	    } else {
1.205     matthew   559: 		delete($classlist->{$student});
1.103     albertel  560: 	    }
                    561: 	} else {
1.205     matthew   562: 	    delete($classlist->{$student});
1.103     albertel  563: 	}
1.44      ng        564:     }
                    565:     my %seen = ();
1.56      matthew   566:     my @sections = sort(keys(%sections));
                    567:     return ($classlist,\@sections,\%fullnames);
1.44      ng        568: }
                    569: 
1.103     albertel  570: sub canmodify {
                    571:     my ($sec)=@_;
                    572:     if ($perm{'mgr'}) {
                    573: 	if (!defined($perm{'mgr_section'})) {
                    574: 	    # can modify whole class
                    575: 	    return 1;
                    576: 	} else {
                    577: 	    if ($sec eq $perm{'mgr_section'}) {
                    578: 		#can modify the requested section
                    579: 		return 1;
                    580: 	    } else {
                    581: 		# can't modify the request section
                    582: 		return 0;
                    583: 	    }
                    584: 	}
                    585:     }
                    586:     #can't modify
                    587:     return 0;
                    588: }
                    589: 
                    590: sub canview {
                    591:     my ($sec)=@_;
                    592:     if ($perm{'vgr'}) {
                    593: 	if (!defined($perm{'vgr_section'})) {
                    594: 	    # can modify whole class
                    595: 	    return 1;
                    596: 	} else {
                    597: 	    if ($sec eq $perm{'vgr_section'}) {
                    598: 		#can modify the requested section
                    599: 		return 1;
                    600: 	    } else {
                    601: 		# can't modify the request section
                    602: 		return 0;
                    603: 	    }
                    604: 	}
                    605:     }
                    606:     #can't modify
                    607:     return 0;
                    608: }
                    609: 
1.44      ng        610: #--- Retrieve the grade status of a student for all the parts
                    611: sub student_gradeStatus {
1.324     albertel  612:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  613:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        614:     my %partstatus = ();
                    615:     foreach (@$partlist) {
1.128     ng        616: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        617: 	$status              = 'nothing' if ($status eq '');
                    618: 	$partstatus{$_}      = $status;
                    619: 	my $subkey           = "resource.$_.submitted_by";
                    620: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    621:     }
                    622:     return %partstatus;
                    623: }
                    624: 
1.45      ng        625: # hidden form and javascript that calls the form
                    626: # Use by verifyscript and viewgrades
                    627: # Shows a student's view of problem and submission
                    628: sub jscriptNform {
1.324     albertel  629:     my ($symb) = @_;
1.442     banghart  630:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  631:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        632: 	'    function viewOneStudent(user,domain) {'."\n".
                    633: 	'	document.onestudent.student.value = user;'."\n".
                    634: 	'	document.onestudent.userdom.value = domain;'."\n".
                    635: 	'	document.onestudent.submit();'."\n".
                    636: 	'    }'."\n".
1.597     wenzelju  637: 	"\n");
1.45      ng        638:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  640: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        641: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    642: 	'<input type="hidden" name="student" value="" />'."\n".
                    643: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    644: 	'</form>'."\n";
                    645:     return $jscript;
                    646: }
1.39      ng        647: 
1.447     foxr      648: 
                    649: 
1.315     bowersj2  650: # Given the score (as a number [0-1] and the weight) what is the final
                    651: # point value? This function will round to the nearest tenth, third,
                    652: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  653: sub compute_points {
1.315     bowersj2  654:     my ($score, $weight) = @_;
                    655:     
                    656:     my $tolerance = .00001;
                    657:     my $points = $score * $weight;
                    658: 
                    659:     # Check for nearness to 1/x.
                    660:     my $check_for_nearness = sub {
                    661:         my ($factor) = @_;
                    662:         my $num = ($points * $factor) + $tolerance;
                    663:         my $floored_num = floor($num);
1.316     albertel  664:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  665:             return $floored_num / $factor;
                    666:         }
                    667:         return $points;
                    668:     };
                    669: 
                    670:     $points = $check_for_nearness->(10);
                    671:     $points = $check_for_nearness->(3);
                    672:     $points = $check_for_nearness->(4);
                    673:     
                    674:     return $points;
                    675: }
                    676: 
1.44      ng        677: #------------------ End of general use routines --------------------
1.87      www       678: 
                    679: #
                    680: # Find most similar essay
                    681: #
                    682: 
                    683: sub most_similar {
1.426     albertel  684:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       685: 
                    686: # ignore spaces and punctuation
                    687: 
                    688:     $uessay=~s/\W+/ /gs;
                    689: 
1.282     www       690: # ignore empty submissions (occuring when only files are sent)
                    691: 
1.598     www       692:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       693: 
1.87      www       694: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       695:     my $limit=0.6;
1.87      www       696:     my $sname='';
                    697:     my $sdom='';
                    698:     my $scrsid='';
                    699:     my $sessay='';
                    700: # go through all essays ...
1.426     albertel  701:     foreach my $tkey (keys(%$old_essays)) {
                    702: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       703: # ... except the same student
1.426     albertel  704:         next if (($tname eq $uname) && ($tdom eq $udom));
                    705: 	my $tessay=$old_essays->{$tkey};
                    706: 	$tessay=~s/\W+/ /gs;
1.87      www       707: # String similarity gives up if not even limit
1.426     albertel  708: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       709: # Found one
1.426     albertel  710: 	if ($tsimilar>$limit) {
                    711: 	    $limit=$tsimilar;
                    712: 	    $sname=$tname;
                    713: 	    $sdom=$tdom;
                    714: 	    $scrsid=$tcrsid;
                    715: 	    $sessay=$old_essays->{$tkey};
                    716: 	}
1.87      www       717:     }
1.88      www       718:     if ($limit>0.6) {
1.87      www       719:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    720:     } else {
                    721:        return ('','','','',0);
                    722:     }
                    723: }
                    724: 
1.44      ng        725: #-------------------------------------------------------------------
                    726: 
                    727: #------------------------------------ Receipt Verification Routines
1.45      ng        728: #
1.602     www       729: 
                    730: sub initialverifyreceipt {
1.608     www       731:    my ($request,$symb) = @_;
1.602     www       732:    &commonJSfunctions($request);
1.605     www       733:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       734:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    735:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       736:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    737:         '<input type="hidden" name="command" value="verify" />'.
                    738:         "</form>\n";
1.602     www       739: }
                    740: 
1.44      ng        741: #--- Check whether a receipt number is valid.---
                    742: sub verifyreceipt {
1.608     www       743:     my ($request,$symb)  = @_;
1.44      ng        744: 
1.257     albertel  745:     my $courseid = $env{'request.course.id'};
1.184     www       746:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  747: 	$env{'form.receipt'};
1.44      ng        748:     $receipt     =~ s/[^\-\d]//g;
                    749: 
1.487     albertel  750:     my $title.=
                    751: 	'<h3><span class="LC_info">'.
1.605     www       752: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    753: 	'</span></h3>'."\n";
1.44      ng        754: 
                    755:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   756:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  757:     
                    758:     my $receiptparts=0;
1.390     albertel  759:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    760: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  761:     my $parts=['0'];
1.582     raeburn   762:     if ($receiptparts) {
                    763:         my $res_error; 
                    764:         ($parts)=&response_type($symb,\$res_error);
                    765:         if ($res_error) {
                    766:             return &navmap_errormsg();
                    767:         } 
                    768:     }
1.486     albertel  769:     
                    770:     my $header = 
                    771: 	&Apache::loncommon::start_data_table().
                    772: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  773: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    774: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    775: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  776:     if ($receiptparts) {
1.487     albertel  777: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  778:     }
                    779:     $header.=
                    780: 	&Apache::loncommon::end_data_table_header_row();
                    781: 
1.294     albertel  782:     foreach (sort 
                    783: 	     {
                    784: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    785: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    786: 		 }
                    787: 		 return $a cmp $b;
                    788: 	     } (keys(%$fullname))) {
1.44      ng        789: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  790: 	foreach my $part (@$parts) {
                    791: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  792: 		$contents.=
                    793: 		    &Apache::loncommon::start_data_table_row().
                    794: 		    '<td>&nbsp;'."\n".
1.177     albertel  795: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  796: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  797: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    798: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    799: 		if ($receiptparts) {
                    800: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    801: 		}
1.486     albertel  802: 		$contents.= 
                    803: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  804: 		
                    805: 		$matches++;
                    806: 	    }
1.44      ng        807: 	}
                    808:     }
                    809:     if ($matches == 0) {
1.584     bisitz    810:         $string = $title
                    811:                  .'<p class="LC_warning">'
                    812:                  .&mt('No match found for the above receipt number.')
                    813:                  .'</p>';
1.44      ng        814:     } else {
1.324     albertel  815: 	$string = &jscriptNform($symb).$title.
1.487     albertel  816: 	    '<p>'.
1.584     bisitz    817: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  818: 	    '</p>'.
1.486     albertel  819: 	    $header.
                    820: 	    $contents.
                    821: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        822:     }
1.614     www       823:     return $string;
1.44      ng        824: }
                    825: 
                    826: #--- This is called by a number of programs.
                    827: #--- Called from the Grading Menu - View/Grade an individual student
                    828: #--- Also called directly when one clicks on the subm button 
                    829: #    on the problem page.
1.30      ng        830: sub listStudents {
1.617     www       831:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  832: 
1.257     albertel  833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  836:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       837:     unless ($submitonly) {
                    838:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    839:     }
1.49      albertel  840: 
1.632     www       841:     my $result='';
1.623     www       842:     my $res_error;
                    843:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  844: 
1.559     raeburn   845:     my %lt = &Apache::lonlocal::texthash (
                    846: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    847: 		'single'   => 'Please select the student before clicking on the Next button.',
                    848: 	     );
1.597     wenzelju  849:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        850:     function checkSelect(checkBox) {
                    851: 	var ctr=0;
                    852: 	var sense="";
                    853: 	if (checkBox.length > 1) {
                    854: 	    for (var i=0; i<checkBox.length; i++) {
                    855: 		if (checkBox[i].checked) {
                    856: 		    ctr++;
                    857: 		}
                    858: 	    }
1.485     albertel  859: 	    sense = '$lt{'multiple'}';
1.110     ng        860: 	} else {
                    861: 	    if (checkBox.checked) {
                    862: 		ctr = 1;
                    863: 	    }
1.485     albertel  864: 	    sense = '$lt{'single'}';
1.110     ng        865: 	}
                    866: 	if (ctr == 0) {
1.485     albertel  867: 	    alert(sense);
1.110     ng        868: 	    return false;
                    869: 	}
                    870: 	document.gradesub.submit();
                    871:     }
                    872: 
                    873:     function reLoadList(formname) {
1.112     ng        874: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        875: 	formname.command.value = 'submission';
                    876: 	formname.submit();
                    877:     }
1.45      ng        878: LISTJAVASCRIPT
                    879: 
1.118     ng        880:     &commonJSfunctions($request);
1.41      ng        881:     $request->print($result);
1.39      ng        882: 
1.154     albertel  883:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       884: 	"\n";
1.485     albertel  885: 	
1.561     bisitz    886:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    887:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    888:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    889:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    890:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    891:                   .&Apache::lonhtmlcommon::row_closure();
                    892:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    893:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    894:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    895:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    896:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  897: 
                    898:     my $submission_options;
1.442     banghart  899:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    900:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  901:     $env{'form.Status'} = $saveStatus;
1.485     albertel  902:     $submission_options.=
1.592     bisitz    903:         '<span class="LC_nobreak">'.
1.624     www       904:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    905:         &mt('last submission only').' </label></span>'."\n".
                    906:         '<span class="LC_nobreak">'.
                    907:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    908:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    909:         '<span class="LC_nobreak">'.
1.628     www       910:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    911:         &mt('by dates and submissions').'</label></span>'."\n".
                    912:         '<span class="LC_nobreak">'.
                    913:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    914:         &mt('all details').'</label></span>';
1.561     bisitz    915:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    916:                   .$submission_options
                    917:                   .&Apache::lonhtmlcommon::row_closure();
                    918: 
                    919:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    920:                   .'<select name="increment">'
                    921:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    922:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    923:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    924:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    925:                   .'</select>'
                    926:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  927: 
                    928:     $gradeTable .= 
1.432     banghart  929:         &build_section_inputs().
1.45      ng        930: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  931: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        932: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    933: 
1.618     www       934:     if (exists($env{'form.Status'})) {
1.561     bisitz    935: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        936:     } else {
1.561     bisitz    937:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    938:                       .&Apache::lonhtmlcommon::StatusOptions(
                    939:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    940:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        941:     }
1.112     ng        942: 
1.561     bisitz    943:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    944:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    945:                   .&Apache::lonhtmlcommon::row_closure(1)
                    946:                   .&Apache::lonhtmlcommon::end_pick_box();
                    947: 
                    948:     $gradeTable .= '<p>'
1.618     www       949:                   .&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    950:                   .'<input type="hidden" name="command" value="processGroup" />'
                    951:                   .'</p>';
1.249     albertel  952: 
                    953: # checkall buttons
                    954:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        955:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    956:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    957:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  958:     $gradeTable.=&check_buttons();
1.450     banghart  959:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  960:     $gradeTable.= &Apache::loncommon::start_data_table().
                    961: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        962:     my $loop = 0;
                    963:     while ($loop < 2) {
1.485     albertel  964: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    965: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       966: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  967: 	    foreach my $part (sort(@$partlist)) {
                    968: 		my $display_part=
                    969: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    970: 		$gradeTable.=
                    971: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        972: 	    }
1.301     albertel  973: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  974: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        975: 	}
                    976: 	$loop++;
1.126     ng        977: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        978:     }
1.474     albertel  979:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        980: 
1.45      ng        981:     my $ctr = 0;
1.294     albertel  982:     foreach my $student (sort 
                    983: 			 {
                    984: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    985: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    986: 			     }
                    987: 			     return $a cmp $b;
                    988: 			 }
                    989: 			 (keys(%$fullname))) {
1.41      ng        990: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  991: 
1.110     ng        992: 	my %status = ();
1.301     albertel  993: 
                    994: 	if ($submitonly eq 'queued') {
                    995: 	    my %queue_status = 
                    996: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    997: 							$udom,$uname);
                    998: 	    next if (!defined($queue_status{'gradingqueue'}));
                    999: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1000: 	}
                   1001: 
1.618     www      1002: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1003: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1004: 	    my $submitted = 0;
1.164     albertel 1005: 	    my $graded = 0;
1.248     albertel 1006: 	    my $incorrect = 0;
1.110     ng       1007: 	    foreach (keys(%status)) {
1.145     albertel 1008: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1009: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1010: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1011: 		
1.110     ng       1012: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1013: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1014: 		    $submitted = 0;
1.150     albertel 1015: 		    my ($part)=split(/\./,$partid);
1.110     ng       1016: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1017: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1018: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1019: 		}
1.41      ng       1020: 	    }
1.248     albertel 1021: 	    
1.156     albertel 1022: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1023: 				     $submitonly eq 'incorrect' ||
                   1024: 				     $submitonly eq 'graded'));
1.248     albertel 1025: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1026: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1027: 	}
1.34      ng       1028: 
1.45      ng       1029: 	$ctr++;
1.249     albertel 1030: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1031:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1032: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1033: 	    if ($ctr%2 ==1) {
                   1034: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1035: 	    }
1.126     ng       1036: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1037:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1038:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1039: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1040: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1041: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1042: 
1.618     www      1043: 	    if ($submitonly ne 'all') {
1.524     raeburn  1044: 		foreach (sort(keys(%status))) {
1.485     albertel 1045: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1046: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1047: 		}
1.41      ng       1048: 	    }
1.126     ng       1049: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1050: 	    if ($ctr%2 ==0) {
                   1051: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1052: 	    }
1.41      ng       1053: 	}
                   1054:     }
1.110     ng       1055:     if ($ctr%2 ==1) {
1.126     ng       1056: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1057: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1058: 		foreach (@$partlist) {
                   1059: 		    $gradeTable.='<td>&nbsp;</td>';
                   1060: 		}
1.301     albertel 1061: 	    } elsif ($submitonly eq 'queued') {
                   1062: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1063: 	    }
1.474     albertel 1064: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1065:     }
                   1066: 
1.474     albertel 1067:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1068:         '<input type="button" '.
                   1069:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1070:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1071:     if ($ctr == 0) {
1.96      albertel 1072: 	my $num_students=(scalar(keys(%$fullname)));
                   1073: 	if ($num_students eq 0) {
1.485     albertel 1074: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1075: 	} else {
1.171     albertel 1076: 	    my $submissions='submissions';
                   1077: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1078: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1079: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1081: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1082: 		    $num_students).
                   1083: 		'</span><br />';
1.96      albertel 1084: 	}
1.46      ng       1085:     } elsif ($ctr == 1) {
1.474     albertel 1086: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1087:     }
                   1088:     $request->print($gradeTable);
1.44      ng       1089:     return '';
1.10      ng       1090: }
                   1091: 
1.44      ng       1092: #---- Called from the listStudents routine
1.249     albertel 1093: 
                   1094: sub check_script {
                   1095:     my ($form, $type)=@_;
1.597     wenzelju 1096:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1097:     function checkall() {
                   1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1099:             ele = document.forms.'.$form.'.elements[i];
                   1100:             if (ele.name == "'.$type.'") {
                   1101:             document.forms.'.$form.'.elements[i].checked=true;
                   1102:                                        }
                   1103:         }
                   1104:     }
                   1105: 
                   1106:     function checksec() {
                   1107:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1108:             ele = document.forms.'.$form.'.elements[i];
                   1109:            string = document.forms.'.$form.'.chksec.value;
                   1110:            if
                   1111:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1112:               document.forms.'.$form.'.elements[i].checked=true;
                   1113:             }
                   1114:         }
                   1115:     }
                   1116: 
                   1117: 
                   1118:     function uncheckall() {
                   1119:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1120:             ele = document.forms.'.$form.'.elements[i];
                   1121:             if (ele.name == "'.$type.'") {
                   1122:             document.forms.'.$form.'.elements[i].checked=false;
                   1123:                                        }
                   1124:         }
                   1125:     }
                   1126: 
1.597     wenzelju 1127: '."\n");
1.249     albertel 1128:     return $chkallscript;
                   1129: }
                   1130: 
                   1131: sub check_buttons {
1.485     albertel 1132:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1133:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1134:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1135:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1136:     return $buttons;
                   1137: }
                   1138: 
1.44      ng       1139: #     Displays the submissions for one student or a group of students
1.34      ng       1140: sub processGroup {
1.619     www      1141:     my ($request,$symb)  = @_;
1.41      ng       1142:     my $ctr        = 0;
1.155     albertel 1143:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1144:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1145: 
1.396     banghart 1146:     foreach my $student (@stuchecked) {
                   1147: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1148: 	$env{'form.student'}        = $uname;
                   1149: 	$env{'form.userdom'}        = $udom;
                   1150: 	$env{'form.fullname'}       = $fullname;
1.619     www      1151: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1152: 	$ctr++;
                   1153:     }
                   1154:     return '';
1.35      ng       1155: }
1.34      ng       1156: 
1.44      ng       1157: #------------------------------------------------------------------------------------
                   1158: #
                   1159: #-------------------------- Next few routines handles grading by student, essentially
                   1160: #                           handles essay response type problem/part
                   1161: #
                   1162: #--- Javascript to handle the submission page functionality ---
                   1163: sub sub_page_js {
                   1164:     my $request = shift;
1.539     riegler  1165: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1166:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1167:     function updateRadio(formname,id,weight) {
1.125     ng       1168: 	var gradeBox = formname["GD_BOX"+id];
                   1169: 	var radioButton = formname["RADVAL"+id];
                   1170: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1171: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1172: 	gradeBox.value = pts;
                   1173: 	var resetbox = false;
                   1174: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1175: 	    alert("$alertmsg"+pts);
1.71      ng       1176: 	    for (var i=0; i<radioButton.length; i++) {
                   1177: 		if (radioButton[i].checked) {
                   1178: 		    gradeBox.value = i;
                   1179: 		    resetbox = true;
                   1180: 		}
                   1181: 	    }
                   1182: 	    if (!resetbox) {
                   1183: 		formtextbox.value = "";
                   1184: 	    }
                   1185: 	    return;
1.44      ng       1186: 	}
1.71      ng       1187: 
                   1188: 	if (pts > weight) {
                   1189: 	    var resp = confirm("You entered a value ("+pts+
                   1190: 			       ") greater than the weight for the part. Accept?");
                   1191: 	    if (resp == false) {
1.125     ng       1192: 		gradeBox.value = oldpts;
1.71      ng       1193: 		return;
                   1194: 	    }
1.44      ng       1195: 	}
1.13      albertel 1196: 
1.71      ng       1197: 	for (var i=0; i<radioButton.length; i++) {
                   1198: 	    radioButton[i].checked=false;
                   1199: 	    if (pts == i && pts != "") {
                   1200: 		radioButton[i].checked=true;
                   1201: 	    }
                   1202: 	}
                   1203: 	updateSelect(formname,id);
1.125     ng       1204: 	formname["stores"+id].value = "0";
1.41      ng       1205:     }
1.5       albertel 1206: 
1.72      ng       1207:     function writeBox(formname,id,pts) {
1.125     ng       1208: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1209: 	if (checkSolved(formname,id) == 'update') {
                   1210: 	    gradeBox.value = pts;
                   1211: 	} else {
1.125     ng       1212: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1213: 	    gradeBox.value = oldpts;
1.125     ng       1214: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1215: 	    for (var i=0; i<radioButton.length; i++) {
                   1216: 		radioButton[i].checked=false;
1.72      ng       1217: 		if (i == oldpts) {
1.71      ng       1218: 		    radioButton[i].checked=true;
                   1219: 		}
                   1220: 	    }
1.41      ng       1221: 	}
1.125     ng       1222: 	formname["stores"+id].value = "0";
1.71      ng       1223: 	updateSelect(formname,id);
                   1224: 	return;
1.41      ng       1225:     }
1.44      ng       1226: 
1.71      ng       1227:     function clearRadBox(formname,id) {
                   1228: 	if (checkSolved(formname,id) == 'noupdate') {
                   1229: 	    updateSelect(formname,id);
                   1230: 	    return;
                   1231: 	}
1.125     ng       1232: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1233: 	for (var i=0; i<gradeSelect.length; i++) {
                   1234: 	    if (gradeSelect[i].selected) {
                   1235: 		var selectx=i;
                   1236: 	    }
                   1237: 	}
1.125     ng       1238: 	var stores = formname["stores"+id];
1.71      ng       1239: 	if (selectx == stores.value) { return };
1.125     ng       1240: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1241: 	gradeBox.value = "";
1.125     ng       1242: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1243: 	for (var i=0; i<radioButton.length; i++) {
                   1244: 	    radioButton[i].checked=false;
                   1245: 	}
                   1246: 	stores.value = selectx;
                   1247:     }
1.5       albertel 1248: 
1.71      ng       1249:     function checkSolved(formname,id) {
1.125     ng       1250: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1251: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1252: 	    if (!reply) {return "noupdate";}
1.120     ng       1253: 	    formname.overRideScore.value = 'yes';
1.41      ng       1254: 	}
1.71      ng       1255: 	return "update";
1.13      albertel 1256:     }
1.71      ng       1257: 
                   1258:     function updateSelect(formname,id) {
1.125     ng       1259: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1260: 	return;
1.41      ng       1261:     }
1.33      ng       1262: 
1.121     ng       1263: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1264:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1265: 	formname.gradeOpt.value = val;
1.71      ng       1266: 	if (val == "Save & Next") {
                   1267: 	    for (i=0;i<=total;i++) {
                   1268: 		for (j=0;j<parttot;j++) {
1.125     ng       1269: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1270: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1271: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1272: 			if (points == "") {
1.125     ng       1273: 			    var name = formname["name"+i].value;
1.129     ng       1274: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1275: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1276: 					       ", part "+partid+". Continue?");
1.71      ng       1277: 			    if (resp == false) {
1.125     ng       1278: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1279: 				return false;
                   1280: 			    }
                   1281: 			}
                   1282: 		    }
                   1283: 		    
                   1284: 		}
                   1285: 	    }
                   1286: 	    
                   1287: 	}
1.120     ng       1288: 	formname.submit();
                   1289:     }
                   1290: 
1.71      ng       1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1292:     function checkSubmitPage(formname,total) {
                   1293: 	noscore = new Array(100);
                   1294: 	var ptr = 0;
                   1295: 	for (i=1;i<total;i++) {
1.125     ng       1296: 	    var partid = formname["q_"+i].value;
1.127     ng       1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1299: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1300: 		if (points == "" && status != "correct_by_student") {
                   1301: 		    noscore[ptr] = i;
                   1302: 		    ptr++;
                   1303: 		}
                   1304: 	    }
                   1305: 	}
                   1306: 	if (ptr != 0) {
                   1307: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1308: 	    var prolist = "";
                   1309: 	    if (ptr == 1) {
                   1310: 		prolist = noscore[0];
                   1311: 	    } else {
                   1312: 		var i = 0;
                   1313: 		while (i < ptr-1) {
                   1314: 		    prolist += noscore[i]+", ";
                   1315: 		    i++;
                   1316: 		}
                   1317: 		prolist += "and "+noscore[i];
                   1318: 	    }
                   1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1320: 	    if (resp == false) {
                   1321: 		return false;
                   1322: 	    }
                   1323: 	}
1.45      ng       1324: 
1.71      ng       1325: 	formname.submit();
                   1326:     }
                   1327: SUBJAVASCRIPT
                   1328: }
1.45      ng       1329: 
1.71      ng       1330: #--- javascript for essay type problem --
                   1331: sub sub_page_kw_js {
                   1332:     my $request = shift;
1.80      ng       1333:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1334:     &commonJSfunctions($request);
1.350     albertel 1335: 
1.629     www      1336:     my $inner_js_msg_central= (<<INNERJS);
                   1337: <script type="text/javascript">
1.350     albertel 1338:     function checkInput() {
                   1339:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1340:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1341:       var usrctr = document.msgcenter.usrctr.value;
                   1342:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1343:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1344: 
                   1345:       var msgchk = "";
                   1346:       if (document.msgcenter.subchk.checked) {
                   1347:          msgchk = "msgsub,";
                   1348:       }
                   1349:       var includemsg = 0;
                   1350:       for (var i=1; i<=nmsg; i++) {
                   1351:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1352:           var frmmsg = document.msgcenter["msg"+i];
                   1353:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1354:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1355:           showflg.value = "1";
                   1356:           var chkbox = document.msgcenter["msgn"+i];
                   1357:           if (chkbox.checked) {
                   1358:              msgchk += "savemsg"+i+",";
                   1359:              includemsg = 1;
                   1360:           }
                   1361:       }
                   1362:       if (document.msgcenter.newmsgchk.checked) {
                   1363:          msgchk += "newmsg"+usrctr;
                   1364:          includemsg = 1;
                   1365:       }
                   1366:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1367:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1368:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1369:       includemsg.value = msgchk;
                   1370: 
                   1371:       self.close()
                   1372: 
                   1373:     }
1.629     www      1374: </script>
1.350     albertel 1375: INNERJS
                   1376: 
1.629     www      1377:     my $inner_js_highlight_central= (<<INNERJS);
                   1378: <script type="text/javascript">
1.351     albertel 1379:     function updateChoice(flag) {
                   1380:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1381:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1382:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1383:       opener.document.SCORE.refresh.value = "on";
                   1384:       if (opener.document.SCORE.keywords.value!=""){
                   1385:          opener.document.SCORE.submit();
                   1386:       }
                   1387:       self.close()
                   1388:     }
1.629     www      1389: </script>
1.351     albertel 1390: INNERJS
                   1391: 
                   1392:     my $start_page_msg_central = 
                   1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1394: 				       {'js_ready'  => 1,
                   1395: 					'only_body' => 1,
                   1396: 					'bgcolor'   =>'#FFFFFF',});
                   1397:     my $end_page_msg_central = 
                   1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1399: 
                   1400: 
                   1401:     my $start_page_highlight_central = 
                   1402:         &Apache::loncommon::start_page('Highlight Central',
                   1403: 				       $inner_js_highlight_central,
1.350     albertel 1404: 				       {'js_ready'  => 1,
                   1405: 					'only_body' => 1,
                   1406: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1407:     my $end_page_highlight_central = 
1.350     albertel 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1409: 
1.219     www      1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1411:     $docopen=~s/^document\.//;
1.652     raeburn  1412:     my %lt = &Apache::lonlocal::texthash(
                   1413:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1414:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1415:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1416:                 comp => 'Compose Message for: ',
                   1417:                 incl => 'Include',
1.656     raeburn  1418:                 type => 'Type',
1.652     raeburn  1419:                 subj => 'Subject',
                   1420:                 mesa => 'Message',
                   1421:                 new  => 'New',
                   1422:                 save => 'Save',
                   1423:                 canc => 'Cancel',
                   1424:                 kehi => 'Keyword Highlight Options',
                   1425:                 txtc => 'Text Color',
                   1426:                 font => 'Font Size',
1.656     raeburn  1427:                 fnst => 'Font Style',
1.652     raeburn  1428:              );
1.597     wenzelju 1429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1430: 
1.44      ng       1431: //===================== Show list of keywords ====================
1.122     ng       1432:   function keywords(formname) {
1.652     raeburn  1433:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1434:     if (nret==null) return;
1.122     ng       1435:     formname.keywords.value = nret;
1.44      ng       1436: 
1.122     ng       1437:     if (formname.keywords.value != "") {
1.128     ng       1438: 	formname.refresh.value = "on";
1.122     ng       1439: 	formname.submit();
1.44      ng       1440:     }
                   1441:     return;
                   1442:   }
                   1443: 
                   1444: //===================== Script to view submitted by ==================
                   1445:   function viewSubmitter(submitter) {
                   1446:     document.SCORE.refresh.value = "on";
                   1447:     document.SCORE.NCT.value = "1";
                   1448:     document.SCORE.unamedom0.value = submitter;
                   1449:     document.SCORE.submit();
                   1450:     return;
                   1451:   }
                   1452: 
                   1453: //===================== Script to add keyword(s) ==================
                   1454:   function getSel() {
                   1455:     if (document.getSelection) txt = document.getSelection();
                   1456:     else if (document.selection) txt = document.selection.createRange().text;
                   1457:     else return;
                   1458:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1459:     if (cleantxt=="") {
1.652     raeburn  1460: 	alert("$lt{'plse'}");
1.44      ng       1461: 	return;
                   1462:     }
1.652     raeburn  1463:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1464:     if (nret==null) return;
1.127     ng       1465:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1466:     if (document.SCORE.keywords.value != "") {
1.127     ng       1467: 	document.SCORE.refresh.value = "on";
1.44      ng       1468: 	document.SCORE.submit();
                   1469:     }
                   1470:     return;
                   1471:   }
                   1472: 
                   1473: //====================== Script for composing message ==============
1.80      ng       1474:    // preload images
                   1475:    img1 = new Image();
                   1476:    img1.src = "$iconpath/mailbkgrd.gif";
                   1477:    img2 = new Image();
                   1478:    img2.src = "$iconpath/mailto.gif";
                   1479: 
1.44      ng       1480:   function msgCenter(msgform,usrctr,fullname) {
                   1481:     var Nmsg  = msgform.savemsgN.value;
                   1482:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1483:     var subject = msgform.msgsub.value;
1.127     ng       1484:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1485:     re = /msgsub/;
                   1486:     var shwsel = "";
                   1487:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1488:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1489:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1490:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1491: 	var testmsg = "savemsg"+i+",";
                   1492: 	re = new RegExp(testmsg,"g");
1.44      ng       1493: 	shwsel = "";
                   1494: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1495: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1496: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1497: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1498: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1499:     }
1.125     ng       1500:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1501:     shwsel = "";
                   1502:     re = /newmsg/;
                   1503:     if (re.test(msgchk)) { shwsel = "checked" }
                   1504:     newMsg(newmsg,shwsel);
                   1505:     msgTail(); 
                   1506:     return;
                   1507:   }
                   1508: 
1.123     ng       1509:   function checkEntities(strx) {
                   1510:     if (strx.length == 0) return strx;
                   1511:     var orgStr = ["&", "<", ">", '"']; 
                   1512:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1513:     var counter = 0;
                   1514:     while (counter < 4) {
                   1515: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1516: 	counter++;
                   1517:     }
                   1518:     return strx;
                   1519:   }
                   1520: 
                   1521:   function strReplace(strx, orgStr, newStr) {
                   1522:     return strx.split(orgStr).join(newStr);
                   1523:   }
                   1524: 
1.44      ng       1525:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1526:     var height = 70*Nmsg+250;
1.44      ng       1527:     var scrollbar = "no";
                   1528:     if (height > 600) {
                   1529: 	height = 600;
                   1530: 	scrollbar = "yes";
                   1531:     }
1.118     ng       1532:     var xpos = (screen.width-600)/2;
                   1533:     xpos = (xpos < 0) ? '0' : xpos;
                   1534:     var ypos = (screen.height-height)/2-30;
                   1535:     ypos = (ypos < 0) ? '0' : ypos;
                   1536: 
1.647     bisitz   1537:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1538:     pWin.focus();
                   1539:     pDoc = pWin.document;
1.219     www      1540:     pDoc.$docopen;
1.351     albertel 1541:     pDoc.write('$start_page_msg_central');
1.76      ng       1542: 
                   1543:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1544:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.652     raeburn  1545:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1546: 
1.564     bisitz   1547:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1548:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1549:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1550: }
                   1551:     function displaySubject(msg,shwsel) {
1.76      ng       1552:     pDoc = pWin.document;
                   1553:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1554:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1555:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1556:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1557: }
                   1558: 
1.72      ng       1559:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1560:     pDoc = pWin.document;
                   1561:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1562:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1563:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1564:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1565: }
                   1566: 
                   1567:   function newMsg(newmsg,shwsel) {
1.76      ng       1568:     pDoc = pWin.document;
                   1569:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.652     raeburn  1570:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1571:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1572:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1573: }
                   1574: 
                   1575:   function msgTail() {
1.76      ng       1576:     pDoc = pWin.document;
1.465     albertel 1577:     pDoc.write("<\\/table>");
                   1578:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1579:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1580:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1581:     pDoc.write("<\\/form>");
1.351     albertel 1582:     pDoc.write('$end_page_msg_central');
1.128     ng       1583:     pDoc.close();
1.44      ng       1584: }
                   1585: 
                   1586: //====================== Script for keyword highlight options ==============
                   1587:   function kwhighlight() {
                   1588:     var kwclr    = document.SCORE.kwclr.value;
                   1589:     var kwsize   = document.SCORE.kwsize.value;
                   1590:     var kwstyle  = document.SCORE.kwstyle.value;
                   1591:     var redsel = "";
                   1592:     var grnsel = "";
                   1593:     var blusel = "";
                   1594:     if (kwclr=="red")   {var redsel="checked"};
                   1595:     if (kwclr=="green") {var grnsel="checked"};
                   1596:     if (kwclr=="blue")  {var blusel="checked"};
                   1597:     var sznsel = "";
                   1598:     var sz1sel = "";
                   1599:     var sz2sel = "";
                   1600:     if (kwsize=="0")  {var sznsel="checked"};
                   1601:     if (kwsize=="+1") {var sz1sel="checked"};
                   1602:     if (kwsize=="+2") {var sz2sel="checked"};
                   1603:     var synsel = "";
                   1604:     var syisel = "";
                   1605:     var sybsel = "";
                   1606:     if (kwstyle=="")    {var synsel="checked"};
                   1607:     if (kwstyle=="<i>") {var syisel="checked"};
                   1608:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1609:     highlightCentral();
                   1610:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1611:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1612:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1613:     highlightend();
                   1614:     return;
                   1615:   }
                   1616: 
                   1617:   function highlightCentral() {
1.76      ng       1618: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1619:     var xpos = (screen.width-400)/2;
                   1620:     xpos = (xpos < 0) ? '0' : xpos;
                   1621:     var ypos = (screen.height-330)/2-30;
                   1622:     ypos = (ypos < 0) ? '0' : ypos;
                   1623: 
1.206     albertel 1624:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1625:     hwdWin.focus();
                   1626:     var hDoc = hwdWin.document;
1.219     www      1627:     hDoc.$docopen;
1.351     albertel 1628:     hDoc.write('$start_page_highlight_central');
1.76      ng       1629:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.652     raeburn  1630:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1631: 
1.564     bisitz   1632:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1633:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.656     raeburn  1634:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1635:   }
                   1636: 
                   1637:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1638:     var hDoc = hwdWin.document;
                   1639:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1640:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1641:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1642:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1643:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1644:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1645:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1646:     hDoc.write("<\\/tr>");
1.44      ng       1647:   }
                   1648: 
                   1649:   function highlightend() { 
1.76      ng       1650:     var hDoc = hwdWin.document;
1.465     albertel 1651:     hDoc.write("<\\/table>");
                   1652:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1653:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1654:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1655:     hDoc.write("<\\/form>");
1.351     albertel 1656:     hDoc.write('$end_page_highlight_central');
1.128     ng       1657:     hDoc.close();
1.44      ng       1658:   }
                   1659: 
                   1660: SUBJAVASCRIPT
                   1661: }
                   1662: 
1.349     albertel 1663: sub get_increment {
1.348     bowersj2 1664:     my $increment = $env{'form.increment'};
                   1665:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1666:         $increment != .1) {
                   1667:         $increment = 1;
                   1668:     }
                   1669:     return $increment;
                   1670: }
                   1671: 
1.585     bisitz   1672: sub gradeBox_start {
                   1673:     return (
                   1674:         &Apache::loncommon::start_data_table()
                   1675:        .&Apache::loncommon::start_data_table_header_row()
                   1676:        .'<th>'.&mt('Part').'</th>'
                   1677:        .'<th>'.&mt('Points').'</th>'
                   1678:        .'<th>&nbsp;</th>'
                   1679:        .'<th>'.&mt('Assign Grade').'</th>'
                   1680:        .'<th>'.&mt('Weight').'</th>'
                   1681:        .'<th>'.&mt('Grade Status').'</th>'
                   1682:        .&Apache::loncommon::end_data_table_header_row()
                   1683:     );
                   1684: }
                   1685: 
                   1686: sub gradeBox_end {
                   1687:     return (
                   1688:         &Apache::loncommon::end_data_table()
                   1689:     );
                   1690: }
1.71      ng       1691: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1692: sub gradeBox {
1.322     albertel 1693:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1694:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1695: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1696:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1697:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1698:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1699:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1700:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1701: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1702:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1703:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1704:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1705: 				       [$partid]);
                   1706:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1707:     if ($last_resets{$partid}) {
                   1708:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1709:     }
1.585     bisitz   1710:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1711:     my $ctr = 0;
1.348     bowersj2 1712:     my $thisweight = 0;
1.349     albertel 1713:     my $increment = &get_increment();
1.485     albertel 1714: 
                   1715:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1716:     while ($thisweight<=$wgt) {
1.532     bisitz   1717: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1718:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1719: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1720: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1721: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1722:         $thisweight += $increment;
1.71      ng       1723: 	$ctr++;
                   1724:     }
1.485     albertel 1725:     $radio.='</tr></table>';
                   1726: 
                   1727:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1728: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1729: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1730: 	$wgt.')" /></td>'."\n";
1.485     albertel 1731:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1732: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1733: 	' </td>'."\n";
                   1734:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1735: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1736:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1737: 	$line.='<option></option>'.
                   1738: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1739:     } else {
1.485     albertel 1740: 	$line.='<option selected="selected"></option>'.
                   1741: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1742:     }
1.485     albertel 1743:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1744: 
                   1745: 
                   1746:     $result .= 
1.585     bisitz   1747: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1748:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1749:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1750: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1751: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1752: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1753:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1754:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1755:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1756:         $aggtries.'" />'."\n";
1.582     raeburn  1757:     my $res_error;
                   1758:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1759:     if ($res_error) {
                   1760:         return &navmap_errormsg();
                   1761:     }
1.318     banghart 1762:     return $result;
                   1763: }
1.322     albertel 1764: 
                   1765: sub handback_box {
1.623     www      1766:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1767:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1768:     my (@respids);
1.652     raeburn  1769:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1770:     foreach my $part_response_id (@part_response_id) {
                   1771:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1772:         if ($part eq $partid) {
1.375     albertel 1773:             push(@respids,$resp);
1.323     banghart 1774:         }
                   1775:     }
1.318     banghart 1776:     my $result;
1.323     banghart 1777:     foreach my $respid (@respids) {
1.322     albertel 1778: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1779: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1780: 	next if (!@$files);
1.654     raeburn  1781: 	my $file_counter = 0;
1.313     banghart 1782: 	foreach my $file (@$files) {
1.368     banghart 1783: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1784:                 $file_counter++;
1.368     banghart 1785:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1786:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1787:     	        $file_disp = "$name.$ext";
                   1788:     	        $file = $file_path.$file_disp;
                   1789:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1790:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1791:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1792:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1793: 	    }
1.322     albertel 1794: 	}
1.654     raeburn  1795:         if ($file_counter) {
                   1796:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1797:                        '<span class="LC_info">'.
                   1798:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1799:         }
1.313     banghart 1800:     }
1.318     banghart 1801:     return $result;    
1.71      ng       1802: }
1.44      ng       1803: 
1.58      albertel 1804: sub show_problem {
1.382     albertel 1805:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1806:     my $rendered;
1.382     albertel 1807:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1808:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1809:     if ($mode eq 'both' or $mode eq 'text') {
                   1810: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1811: 						       $env{'request.course.id'},
                   1812: 						       undef,\%form);
1.144     albertel 1813:     }
1.58      albertel 1814:     if ($removeform) {
                   1815: 	$rendered=~s|<form(.*?)>||g;
                   1816: 	$rendered=~s|</form>||g;
1.374     albertel 1817: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1818:     }
1.144     albertel 1819:     my $companswer;
                   1820:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1821: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1822: 	$companswer=
                   1823: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1824: 						    $env{'request.course.id'},
                   1825: 						    %form);
1.144     albertel 1826:     }
1.58      albertel 1827:     if ($removeform) {
                   1828: 	$companswer=~s|<form(.*?)>||g;
                   1829: 	$companswer=~s|</form>||g;
1.144     albertel 1830: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1831:     }
1.468     albertel 1832:     $rendered=
1.588     bisitz   1833:         '<div class="LC_Box">'
                   1834:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1835:        .$rendered
                   1836:        .'</div>';
1.468     albertel 1837:     $companswer=
1.588     bisitz   1838:         '<div class="LC_Box">'
                   1839:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1840:        .$companswer
                   1841:        .'</div>';
1.468     albertel 1842:     my $result;
1.144     albertel 1843:     if ($mode eq 'both') {
1.588     bisitz   1844:         $result=$rendered.$companswer;
1.144     albertel 1845:     } elsif ($mode eq 'text') {
1.588     bisitz   1846:         $result=$rendered;
1.144     albertel 1847:     } elsif ($mode eq 'answer') {
1.588     bisitz   1848:         $result=$companswer;
1.144     albertel 1849:     }
1.71      ng       1850:     return $result;
1.58      albertel 1851: }
1.397     albertel 1852: 
1.396     banghart 1853: sub files_exist {
                   1854:     my ($r, $symb) = @_;
                   1855:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1856: 
1.396     banghart 1857:     foreach my $student (@students) {
                   1858:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1859:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1860: 					      $udom,$uname);
1.396     banghart 1861:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1862:         foreach my $submission (@$string) {
                   1863:             my ($partid,$respid) =
                   1864: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1865:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1866: 					   \%record);
                   1867:             return 1 if (@$files);
1.396     banghart 1868:         }
                   1869:     }
1.397     albertel 1870:     return 0;
1.396     banghart 1871: }
1.397     albertel 1872: 
1.394     banghart 1873: sub download_all_link {
                   1874:     my ($r,$symb) = @_;
1.621     www      1875:     unless (&files_exist($r, $symb)) {
                   1876:        $r->print(&mt('There are currently no submitted documents.'));
                   1877:        return;
                   1878:     }
                   1879: 
1.395     albertel 1880:     my $all_students = 
                   1881: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1882: 
                   1883:     my $parts =
                   1884: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1885: 
1.394     banghart 1886:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1887:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1888:                              'cgi.'.$identifier.'.symb' => $symb,
                   1889:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1890:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1891: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1892:     return;
                   1893: }
                   1894: 
                   1895: sub submit_download_link {
                   1896:     my ($request,$symb) = @_;
                   1897:     if (!$symb) { return ''; }
                   1898: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1899:     &download_all_link($request,$symb);
1.394     banghart 1900: }
1.395     albertel 1901: 
1.432     banghart 1902: sub build_section_inputs {
                   1903:     my $section_inputs;
                   1904:     if ($env{'form.section'} eq '') {
                   1905:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1906:     } else {
                   1907:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1908:         foreach my $section (@sections) {
1.432     banghart 1909:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1910:         }
                   1911:     }
                   1912:     return $section_inputs;
                   1913: }
                   1914: 
1.44      ng       1915: # --------------------------- show submissions of a student, option to grade 
                   1916: sub submission {
1.608     www      1917:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1918:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1919:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1920:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1921:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1922: 
1.605     www      1923:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1924:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1925: 
                   1926:     if (!&canview($usec)) {
1.398     albertel 1927: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1928: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1929: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1930: 	return;
                   1931:     }
                   1932: 
1.257     albertel 1933:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1934:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1935:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1936:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1937:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1938: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1939: 	'/check.gif" height="16" border="0" />';
1.41      ng       1940: 
1.426     albertel 1941:     my %old_essays;
1.41      ng       1942:     # header info
                   1943:     if ($counter == 0) {
                   1944: 	&sub_page_js($request);
1.621     www      1945: 	&sub_page_kw_js($request);
1.118     ng       1946: 
1.44      ng       1947: 	# option to display problem, only once else it cause problems 
                   1948:         # with the form later since the problem has a form.
1.257     albertel 1949: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1950: 	    my $mode;
1.257     albertel 1951: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1952: 		$mode='both';
1.257     albertel 1953: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1954: 		$mode='text';
1.257     albertel 1955: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1956: 		$mode='answer';
                   1957: 	    }
1.329     albertel 1958: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1959: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1960: 	}
1.441     www      1961: 
1.44      ng       1962: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1963:         # if this subroutine has been called once.
1.41      ng       1964: 	my %keyhash = ();
1.624     www      1965: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1966:         if (1) {
1.41      ng       1967: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1968: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1969: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1970: 
1.257     albertel 1971: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1972: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1973: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1974: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1975: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1976: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1977: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1978: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1979: 	}
1.257     albertel 1980: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1981: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1982: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1983: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1984: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1985: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1986: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1987: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1988: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1989: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1990: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1991: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1992: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1993: 			&build_section_inputs().
1.326     albertel 1994: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1995: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1996: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1997: #	if ($env{'form.handgrade'} eq 'yes') {
                   1998:         if (1) {
1.257     albertel 1999: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2000: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2001: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2002: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2003: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2004: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2005: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2006: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2007: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2008: 	    }
1.123     ng       2009: 	}
1.41      ng       2010: 	
                   2011: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2012: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2013: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2014: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2015: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2016: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2017: 		'" />'."\n".
                   2018: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2019: 	    $cts++;
                   2020: 	}
                   2021: 	$request->print($prnmsg);
1.32      ng       2022: 
1.624     www      2023: #	if ($env{'form.handgrade'} eq 'yes') {
                   2024:         if (1) {
1.652     raeburn  2025: 
                   2026:             my %lt = &Apache::lonlocal::texthash(
                   2027:                           keyw => 'Keyword Options',
1.655     raeburn  2028:                           list => 'List',
1.652     raeburn  2029:                           past => 'Paste Selection to List',
1.661     www      2030:                           high => 'Highlight Attribute',
1.652     raeburn  2031:                      );    
1.88      www      2032: #
                   2033: # Print out the keyword options line
                   2034: #
1.41      ng       2035: 	    $request->print(<<KEYWORDS);
1.652     raeburn  2036: <br /><b>$lt{'keyw'}:</b>&nbsp;
1.655     raeburn  2037: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2038: <a href="#" onmousedown="javascript:getSel(); return false"
1.652     raeburn  2039:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2040: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2041: KEYWORDS
1.88      www      2042: #
                   2043: # Load the other essays for similarity check
                   2044: #
1.324     albertel 2045:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2046: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2047: 	    $apath=&escape($apath);
1.88      www      2048: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2049: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2050:         }
                   2051:     }
1.44      ng       2052: 
1.441     www      2053: # This is where output for one specific student would start
1.592     bisitz   2054:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2055:     $request->print(
                   2056:         "\n\n"
                   2057:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2058:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2059:        ."\n"
                   2060:     );
1.441     www      2061: 
1.592     bisitz   2062:     # Show additional functions if allowed
                   2063:     if ($perm{'vgr'}) {
                   2064:         $request->print(
                   2065:             &Apache::loncommon::track_student_link(
                   2066:                 &mt('View recent activity'),
                   2067:                 $uname,$udom,'check')
                   2068:            .' '
                   2069:         );
                   2070:     }
                   2071:     if ($perm{'opa'}) {
                   2072:         $request->print(
                   2073:             &Apache::loncommon::pprmlink(
                   2074:                 &mt('Set/Change parameters'),
                   2075:                 $uname,$udom,$symb,'check'));
                   2076:     }
                   2077: 
                   2078:     # Show Problem
1.257     albertel 2079:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2080: 	my $mode;
1.257     albertel 2081: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2082: 	    $mode='both';
1.257     albertel 2083: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2084: 	    $mode='text';
1.257     albertel 2085: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2086: 	    $mode='answer';
                   2087: 	}
1.329     albertel 2088: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2089: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2090:     }
1.144     albertel 2091: 
1.257     albertel 2092:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2093:     my $res_error;
                   2094:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2095:     if ($res_error) {
                   2096:         $request->print(&navmap_errormsg());
                   2097:         return;
                   2098:     }
1.41      ng       2099: 
1.44      ng       2100:     # Display student info
1.41      ng       2101:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2102: 
                   2103:     my $result='<div class="LC_Box">'
                   2104:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2105:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2106:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2107: #    if ($env{'form.handgrade'} eq 'no') {
                   2108:     if (1) {
1.588     bisitz   2109:         $result.='<p class="LC_info">'
                   2110:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2111:                 ."</p>\n";
1.469     albertel 2112:     }
                   2113: 
1.118     ng       2114:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2115:     my $fullname;
                   2116:     my $col_fullnames = [];
1.624     www      2117: #    if ($env{'form.handgrade'} eq 'yes') {
                   2118:     if (1) {
1.464     albertel 2119: 	(my $sub_result,$fullname,$col_fullnames)=
                   2120: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2121: 				 $counter);
                   2122: 	$result.=$sub_result;
1.41      ng       2123:     }
1.44      ng       2124:     $request->print($result."\n");
1.588     bisitz   2125: 
1.44      ng       2126:     # print student answer/submission
1.588     bisitz   2127:     # Options are (1) Handgraded submission only
1.44      ng       2128:     #             (2) Last submission, includes submission that is not handgraded 
                   2129:     #                  (for multi-response type part)
                   2130:     #             (3) Last submission plus the parts info
                   2131:     #             (4) The whole record for this student
1.257     albertel 2132:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2133: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2134: 	
                   2135: 	my $lastsubonly;
                   2136: 
1.588     bisitz   2137:         if ($$timestamp eq '') {
                   2138:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2139:         } else {
1.592     bisitz   2140:             $lastsubonly =
                   2141:                 '<div class="LC_grade_submissions_body">'
                   2142:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2143: 
1.151     albertel 2144: 	    my %seenparts;
1.375     albertel 2145: 	    my @part_response_id = &flatten_responseType($responseType);
                   2146: 	    foreach my $part (@part_response_id) {
1.393     albertel 2147: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2148: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2149: 
1.375     albertel 2150: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2151: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2152: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2153: 		    if (exists($seenparts{$partid})) { next; }
                   2154: 		    $seenparts{$partid}=1;
1.207     albertel 2155: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2156: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2157: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2158: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2159: 			'\');" target="_self">'.
1.257     albertel 2160: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2161: 		    $request->print($submitby);
                   2162: 		    next;
                   2163: 		}
                   2164: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2165: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2166:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2167:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2168:                         ' <span class="LC_internal_info">'.
1.623     www      2169:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2170:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2171: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2172: 		    next;
                   2173: 		}
1.468     albertel 2174: 		foreach my $submission (@$string) {
                   2175: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2176: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2177: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2178: 		    # Similarity check
                   2179: 		    my $similar='';
1.640     raeburn  2180:                     my ($type,$trial,$rndseed);
                   2181:                     if ($hide eq 'rand') {
                   2182:                         $type = 'randomizetry';
                   2183:                         $trial = $record{"resource.$partid.tries"};
                   2184:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2185:                     }
1.257     albertel 2186: 		    if($env{'form.checkPlag'}){
1.151     albertel 2187: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2188: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2189: 			if ($osim) {
                   2190: 			    $osim=int($osim*100.0);
1.426     albertel 2191: 			    my %old_course_desc = 
                   2192: 				&Apache::lonnet::coursedescription($ocrsid,
                   2193: 								   {'one_time' => 1});
                   2194: 
1.640     raeburn  2195:                             if ($hide eq 'anon') {
1.596     raeburn  2196:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2197:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2198:                             } else {
                   2199: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2200: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2201: 				        $osim,
                   2202: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2203: 				        $old_course_desc{'description'},
                   2204: 				        $old_course_desc{'num'},
                   2205: 				        $old_course_desc{'domain'}).
                   2206: 				    '</span></h3><blockquote><i>'.
                   2207: 				    &keywords_highlight($oessay).
                   2208: 				    '</i></blockquote><hr />';
                   2209:                             }
1.151     albertel 2210: 			}
1.150     albertel 2211: 		    }
1.640     raeburn  2212: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2213:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2214: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2215: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2216: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2217: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2218:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2219:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2220:                             ' <span class="LC_internal_info">'.
1.623     www      2221:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2222:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2223: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2224: 			if (@$files) {
1.640     raeburn  2225:                             if ($hide eq 'anon') {
1.596     raeburn  2226:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2227:                             } else {
                   2228:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2229:                                 foreach my $file (@$files) {
                   2230:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2231:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2232:                                 }
                   2233:                             }
1.236     albertel 2234: 			    $lastsubonly.='<br />';
1.41      ng       2235: 			}
1.640     raeburn  2236:                         if ($hide eq 'anon') {
1.596     raeburn  2237:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2238:                         } else {
                   2239: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2240: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.640     raeburn  2241: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2242:                         }
1.151     albertel 2243: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2244: 			$lastsubonly.='</div>';
1.41      ng       2245: 		    }
                   2246: 		}
                   2247: 	    }
1.588     bisitz   2248: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2249: 	}
                   2250: 	$request->print($lastsubonly);
1.468     albertel 2251:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2252:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2253: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2254:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2255: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2256: 								 $env{'request.course.id'},
1.44      ng       2257: 								 $last,'.submission',
                   2258: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2259:     }
1.121     ng       2260:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2261: 	.$udom.'" />'."\n");
1.44      ng       2262:     # return if view submission with no grading option
1.618     www      2263:     if (!&canmodify($usec)) {
1.633     www      2264: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2265: 	return;
1.180     albertel 2266:     } else {
1.468     albertel 2267: 	$request->print('</div>'."\n");
1.41      ng       2268:     }
1.33      ng       2269: 
1.121     ng       2270:     # essay grading message center
1.624     www      2271: #    if ($env{'form.handgrade'} eq 'yes') {
                   2272:     if (1) {
1.468     albertel 2273: 	my $result='<div class="LC_grade_message_center">';
                   2274:     
                   2275: 	$result.='<div class="LC_grade_message_center_header">'.
                   2276: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2277: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2278: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2279: 	if (scalar(@$col_fullnames) > 0) {
                   2280: 	    my $lastone = pop(@$col_fullnames);
                   2281: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2282: 	}
                   2283: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2284: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2285: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2286: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2287: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2288: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2289: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2290: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2291: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2292: 	    '<br />&nbsp;('.
1.468     albertel 2293: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2294: 	$result.='</div></div>';
1.121     ng       2295: 	$request->print($result);
1.118     ng       2296:     }
1.41      ng       2297: 
                   2298:     my %seen = ();
                   2299:     my @partlist;
1.129     ng       2300:     my @gradePartRespid;
1.375     albertel 2301:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2302:     $request->print(
1.588     bisitz   2303:         '<div class="LC_Box">'
                   2304:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2305:     );
1.592     bisitz   2306:     $request->print(&gradeBox_start());
1.375     albertel 2307:     foreach my $part_response_id (@part_response_id) {
                   2308:     	my ($partid,$respid) = @{ $part_response_id };
                   2309: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2310: 	next if ($seen{$partid} > 0);
1.41      ng       2311: 	$seen{$partid}++;
1.393     albertel 2312: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2313: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2314: 	push(@partlist,$partid);
                   2315: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2316: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2317:     }
1.585     bisitz   2318:     $request->print(&gradeBox_end()); # </div>
                   2319:     $request->print('</div>');
1.468     albertel 2320: 
                   2321:     $request->print('<div class="LC_grade_info_links">');
                   2322:     $request->print('</div>');
                   2323: 
1.45      ng       2324:     $result='<input type="hidden" name="partlist'.$counter.
                   2325: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2326:     $result.='<input type="hidden" name="gradePartRespid'.
                   2327: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2328:     my $ctr = 0;
                   2329:     while ($ctr < scalar(@partlist)) {
                   2330: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2331: 	    $partlist[$ctr].'" />'."\n";
                   2332: 	$ctr++;
                   2333:     }
1.468     albertel 2334:     $request->print($result.''."\n");
1.41      ng       2335: 
1.441     www      2336: # Done with printing info for one student
                   2337: 
1.468     albertel 2338:     $request->print('</div>');#LC_grade_show_user
1.441     www      2339: 
                   2340: 
1.41      ng       2341:     # print end of form
                   2342:     if ($counter == $total) {
1.592     bisitz   2343:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2344: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2345: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2346: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2347: 	my $ntstu ='<select name="NTSTU">'.
                   2348: 	    '<option>1</option><option>2</option>'.
                   2349: 	    '<option>3</option><option>5</option>'.
                   2350: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2351: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2352: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2353:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2354: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2355: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2356: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2357: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2358:         $endform.='<span class="LC_warning">'.
                   2359:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2360:                   '</span>'."\n" ;
1.349     albertel 2361:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2362:             "' name='increment' />";
1.485     albertel 2363: 	$endform.='</td></tr></table></form>';
1.41      ng       2364: 	$request->print($endform);
                   2365:     }
                   2366:     return '';
1.38      ng       2367: }
                   2368: 
1.464     albertel 2369: sub check_collaborators {
                   2370:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2371:     my ($result,@col_fullnames);
                   2372:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2373:     foreach my $part (keys(%$handgrade)) {
                   2374: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2375: 					'.maxcollaborators',
                   2376: 					$symb,$udom,$uname);
                   2377: 	next if ($ncol <= 0);
                   2378: 	$part =~ s/\_/\./g;
                   2379: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2380: 	my (@good_collaborators, @bad_collaborators);
                   2381: 	foreach my $possible_collaborator
1.630     www      2382: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2383: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2384: 	    next if ($possible_collaborator eq '');
1.631     www      2385: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2386: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2387: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2388: 	    # Doing this grep allows 'fuzzy' specification
                   2389: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2390: 			       keys(%$classlist));
                   2391: 	    if (! scalar(@matches)) {
                   2392: 		push(@bad_collaborators, $possible_collaborator);
                   2393: 	    } else {
                   2394: 		push(@good_collaborators, @matches);
                   2395: 	    }
                   2396: 	}
                   2397: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2398: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2399: 	    foreach my $name (@good_collaborators) {
                   2400: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2401: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2402: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2403: 	    }
1.630     www      2404: 	    $result.='</ol><br />'."\n";
1.466     albertel 2405: 	    my ($part)=split(/\./,$part);
1.464     albertel 2406: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2407: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2408: 		"\n";
                   2409: 	}
                   2410: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2411: 	    $result.='<div class="LC_warning">';
1.464     albertel 2412: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2413: 	    $result .= '</div>';
                   2414: 	}         
                   2415: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2416: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2417: 	    $result .= &mt('This student has submitted too many '.
                   2418: 		'collaborators.  Maximum is [_1].',$ncol);
                   2419: 	    $result .= '</div>';
                   2420: 	}
                   2421:     }
                   2422:     return ($result,$fullname,\@col_fullnames);
                   2423: }
                   2424: 
1.44      ng       2425: #--- Retrieve the last submission for all the parts
1.38      ng       2426: sub get_last_submission {
1.119     ng       2427:     my ($returnhash)=@_;
1.596     raeburn  2428:     my (@string,$timestamp,%lasthidden);
1.119     ng       2429:     if ($$returnhash{'version'}) {
1.46      ng       2430: 	my %lasthash=();
                   2431: 	my ($version);
1.119     ng       2432: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2433: 	    foreach my $key (sort(split(/\:/,
                   2434: 					$$returnhash{$version.':keys'}))) {
                   2435: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2436: 		$timestamp = 
1.545     raeburn  2437: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2438: 	    }
                   2439: 	}
1.640     raeburn  2440:         my (%typeparts,%randombytry);
1.596     raeburn  2441:         my $showsurv = 
                   2442:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2443:         foreach my $key (sort(keys(%lasthash))) {
                   2444:             if ($key =~ /\.type$/) {
                   2445:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2446:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2447:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2448:                     my ($ign,@parts) = split(/\./,$key);
                   2449:                     pop(@parts);
1.641     raeburn  2450:                     my $id = join('.',@parts);
1.640     raeburn  2451:                     if ($lasthash{$key} eq 'randomizetry') {
                   2452:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2453:                     } else {
                   2454:                         unless ($showsurv) {
                   2455:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2456:                         }
1.596     raeburn  2457:                     }
                   2458:                     delete($lasthash{$key});
                   2459:                 }
                   2460:             }
                   2461:         }
                   2462:         my @hidden = keys(%typeparts);
1.640     raeburn  2463:         my @randomize = keys(%randombytry);
1.397     albertel 2464: 	foreach my $key (keys(%lasthash)) {
                   2465: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2466:             my $hide;
                   2467:             if (@hidden) {
                   2468:                 foreach my $id (@hidden) {
                   2469:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2470:                         $hide = 'anon';
1.596     raeburn  2471:                         last;
                   2472:                     }
                   2473:                 }
                   2474:             }
1.640     raeburn  2475:             unless ($hide) {
                   2476:                 if (@randomize) {
                   2477:                     foreach my $id (@hidden) {
                   2478:                         if ($key =~ /^\Q$id\E/) {
                   2479:                             $hide = 'rand';
                   2480:                             last;
                   2481:                         }
                   2482:                     }
                   2483:                 }
                   2484:             }
1.397     albertel 2485: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2486: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2487: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2488: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2489: 	}
                   2490:     }
1.397     albertel 2491:     if (!@string) {
                   2492: 	$string[0] =
1.539     riegler  2493: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2494:     }
                   2495:     return (\@string,\$timestamp);
1.38      ng       2496: }
1.35      ng       2497: 
1.44      ng       2498: #--- High light keywords, with style choosen by user.
1.38      ng       2499: sub keywords_highlight {
1.44      ng       2500:     my $string    = shift;
1.257     albertel 2501:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2502:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2503:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2504:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2505:     foreach my $keyword (@keylist) {
                   2506: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2507:     }
                   2508:     return $string;
1.38      ng       2509: }
1.36      ng       2510: 
1.44      ng       2511: #--- Called from submission routine
1.38      ng       2512: sub processHandGrade {
1.608     www      2513:     my ($request,$symb) = @_;
1.324     albertel 2514:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2515:     my $button = $env{'form.gradeOpt'};
                   2516:     my $ngrade = $env{'form.NCT'};
                   2517:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2518:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2519:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2520: 
1.44      ng       2521:     if ($button eq 'Save & Next') {
                   2522: 	my $ctr = 0;
                   2523: 	while ($ctr < $ngrade) {
1.257     albertel 2524: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2525: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2526: 	    if ($errorflag eq 'no_score') {
                   2527: 		$ctr++;
                   2528: 		next;
                   2529: 	    }
1.104     albertel 2530: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2531: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2532: 		$ctr++;
                   2533: 		next;
                   2534: 	    }
1.257     albertel 2535: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2536: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2537: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2538:             my ($feedurl,$showsymb) =
                   2539: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2540: 	    my $messagetail;
1.62      albertel 2541: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2542: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2543: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2544: 		$subject.=' ['.$restitle.']';
1.44      ng       2545: 		my (@msgnum) = split(/,/,$includemsg);
                   2546: 		foreach (@msgnum) {
1.257     albertel 2547: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2548: 		}
1.80      ng       2549: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2550: 		if ($env{'form.withgrades'.$ctr}) {
                   2551: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2552: 		    $messagetail = " for <a href=\"".
1.605     www      2553: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2554: 		}
                   2555: 		$msgstatus = 
                   2556:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2557: 						     $message.$messagetail,
1.418     albertel 2558:                                                      undef,$feedurl,undef,
1.386     raeburn  2559:                                                      undef,undef,$showsymb,
                   2560:                                                      $restitle);
1.574     bisitz   2561: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2562: 				$msgstatus.'<br />');
1.44      ng       2563: 	    }
1.257     albertel 2564: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2565: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2566: 		foreach my $collabstr (@collabstrs) {
                   2567: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2568: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2569: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2570: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2571: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2572: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2573: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2574: 			    next;
1.418     albertel 2575: 			} elsif ($message ne '') {
                   2576: 			    my ($baseurl,$showsymb) = 
                   2577: 				&get_feedurl_and_symb($symb,$collaborator,
                   2578: 						      $udom);
                   2579: 			    if ($env{'form.withgrades'.$ctr}) {
                   2580: 				$messagetail = " for <a href=\"".
1.605     www      2581:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2582: 			    }
1.418     albertel 2583: 			    $msgstatus = 
                   2584: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2585: 			}
1.44      ng       2586: 		    }
                   2587: 		}
                   2588: 	    }
                   2589: 	    $ctr++;
                   2590: 	}
                   2591:     }
                   2592: 
1.624     www      2593: #    if ($env{'form.handgrade'} eq 'yes') {
                   2594:     if (1) {
1.119     ng       2595: 	# Keywords sorted in alphabatical order
1.257     albertel 2596: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2597: 	my %keyhash = ();
1.257     albertel 2598: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2599: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2600: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2601: 	$env{'form.keywords'} = join(' ',@keywords);
                   2602: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2603: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2604: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2605: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2606: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2607: 
                   2608: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2609: 	# New messages are saved in env for the next student.
1.119     ng       2610: 	# All messages are saved in nohist_handgrade.db
                   2611: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2612: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2613: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2614: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2615: 		$idx++;
                   2616: 	    }
                   2617: 	    $ctr++;
1.41      ng       2618: 	}
1.119     ng       2619: 	$ctr = 0;
                   2620: 	while ($ctr < $ngrade) {
1.257     albertel 2621: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2622: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2623: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2624: 		$idx++;
                   2625: 	    }
                   2626: 	    $ctr++;
1.41      ng       2627: 	}
1.257     albertel 2628: 	$env{'form.savemsgN'} = --$idx;
                   2629: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2630: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2631: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2632:     }
1.44      ng       2633:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2634:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2635:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2636: 	my ($ctr,$total) = (0,0);
                   2637: 	while ($ctr < $ngrade) {
1.257     albertel 2638: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2639: 	    $ctr++;
                   2640: 	}
1.257     albertel 2641: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2642: 	$ctr = 0;
                   2643: 	while ($ctr < $total) {
1.257     albertel 2644: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2645: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2646: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2647: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2648: 	    $ctr++;
                   2649: 	}
                   2650: 	return '';
                   2651:     }
1.36      ng       2652: 
1.44      ng       2653:     # Get the next/previous one or group of students
1.257     albertel 2654:     my $firststu = $env{'form.unamedom0'};
                   2655:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2656:     my $ctr = 2;
1.41      ng       2657:     while ($laststu eq '') {
1.257     albertel 2658: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2659: 	$ctr++;
                   2660: 	$laststu = $firststu if ($ctr > $ngrade);
                   2661:     }
1.44      ng       2662: 
1.41      ng       2663:     my (@parsedlist,@nextlist);
                   2664:     my ($nextflg) = 0;
1.524     raeburn  2665:     foreach my $item (sort 
1.294     albertel 2666: 	     {
                   2667: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2668: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2669: 		 }
                   2670: 		 return $a cmp $b;
                   2671: 	     } (keys(%$fullname))) {
1.605     www      2672: # FIXME: this is fishy, looks like the button label
1.41      ng       2673: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2674: 	    push(@parsedlist,$item);
1.41      ng       2675: 	}
1.524     raeburn  2676: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2677: 	if ($button eq 'Previous') {
1.524     raeburn  2678: 	    last if ($item eq $firststu);
                   2679: 	    push(@parsedlist,$item);
1.41      ng       2680: 	}
                   2681:     }
                   2682:     $ctr = 0;
1.605     www      2683: # FIXME: this is fishy, looks like the button label
1.41      ng       2684:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2685:     my $res_error;
                   2686:     my ($partlist) = &response_type($symb,\$res_error);
                   2687:     if ($res_error) {
                   2688:         $request->print(&navmap_errormsg());
                   2689:         return;
                   2690:     }
1.41      ng       2691:     foreach my $student (@parsedlist) {
1.257     albertel 2692: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2693: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2694: 	
                   2695: 	if ($submitonly eq 'queued') {
                   2696: 	    my %queue_status = 
                   2697: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2698: 							$udom,$uname);
                   2699: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2700: 	}
                   2701: 
1.156     albertel 2702: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2703: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2704: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2705: 	    my $submitted = 0;
1.248     albertel 2706: 	    my $ungraded = 0;
                   2707: 	    my $incorrect = 0;
1.524     raeburn  2708: 	    foreach my $item (keys(%status)) {
                   2709: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2710: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2711: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2712: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2713: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2714: 		    $submitted = 0;
                   2715: 		}
1.41      ng       2716: 	    }
1.156     albertel 2717: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2718: 				     $submitonly eq 'incorrect' ||
                   2719: 				     $submitonly eq 'graded'));
1.248     albertel 2720: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2721: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2722: 	}
1.524     raeburn  2723: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2724: 	last if ($ctr == $ntstu);
1.41      ng       2725: 	$ctr++;
                   2726:     }
1.36      ng       2727: 
1.41      ng       2728:     $ctr = 0;
                   2729:     my $total = scalar(@nextlist)-1;
1.39      ng       2730: 
1.524     raeburn  2731:     foreach (sort(@nextlist)) {
1.41      ng       2732: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2733: 	$env{'form.student'}  = $uname;
                   2734: 	$env{'form.userdom'}  = $udom;
                   2735: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2736: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2737: 	$ctr++;
                   2738:     }
                   2739:     if ($total < 0) {
1.653     raeburn  2740: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       2741: 	$request->print($the_end);
                   2742:     }
                   2743:     return '';
1.38      ng       2744: }
1.36      ng       2745: 
1.44      ng       2746: #---- Save the score and award for each student, if changed
1.38      ng       2747: sub saveHandGrade {
1.324     albertel 2748:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2749:     my @version_parts;
1.104     albertel 2750:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2751: 					   $env{'request.course.id'});
1.104     albertel 2752:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2753:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2754:     my @parts_graded;
1.77      ng       2755:     my %newrecord  = ();
                   2756:     my ($pts,$wgt) = ('','');
1.269     raeburn  2757:     my %aggregate = ();
                   2758:     my $aggregateflag = 0;
1.301     albertel 2759:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2760:     foreach my $new_part (@parts) {
1.337     banghart 2761: 	#collaborator ($submi may vary for different parts
1.259     banghart 2762: 	if ($submitter && $new_part ne $part) { next; }
                   2763: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2764: 	if ($dropMenu eq 'excused') {
1.259     banghart 2765: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2766: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2767: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2768: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2769: 		}
1.364     banghart 2770: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2771: 	    }
1.125     ng       2772: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2773: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2774: 	    foreach my $key (keys(%record)) {
1.259     banghart 2775: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2776: 	    }
1.259     banghart 2777: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2778: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2779:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2780: 
                   2781:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2782: 					       [$new_part]);
                   2783:             my $aggtries =$totaltries;
1.269     raeburn  2784:             if ($last_resets{$new_part}) {
1.270     albertel 2785:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2786: 					   $new_part);
1.269     raeburn  2787:             }
1.270     albertel 2788: 
                   2789:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2790:             if ($aggtries > 0) {
1.327     albertel 2791:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2792:                 $aggregateflag = 1;
                   2793:             }
1.125     ng       2794: 	} elsif ($dropMenu eq '') {
1.259     banghart 2795: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2796: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2797: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2798: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2799: 		next;
                   2800: 	    }
1.259     banghart 2801: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2802: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2803: 	    my $partial= $pts/$wgt;
1.259     banghart 2804: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2805: 		#do not update score for part if not changed.
1.346     banghart 2806:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2807: 		next;
1.251     banghart 2808: 	    } else {
1.524     raeburn  2809: 	        push(@parts_graded,$new_part);
1.153     albertel 2810: 	    }
1.259     banghart 2811: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2812: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2813: 	    }
1.259     banghart 2814: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2815: 	    if ($partial == 0) {
1.153     albertel 2816: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2817: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2818: 		}
1.41      ng       2819: 	    } else {
1.153     albertel 2820: 		if ($record{$reckey} ne 'correct_by_override') {
                   2821: 		    $newrecord{$reckey} = 'correct_by_override';
                   2822: 		}
                   2823: 	    }	    
                   2824: 	    if ($submitter && 
1.259     banghart 2825: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2826: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2827: 	    }
1.259     banghart 2828: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2829: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2830: 	}
1.259     banghart 2831: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2832: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2833: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2834: 	        $dropMenu eq 'reset status')
                   2835: 	   {
1.524     raeburn  2836: 	    push(@version_parts,$new_part);
1.259     banghart 2837: 	}
1.41      ng       2838:     }
1.301     albertel 2839:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2840:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2841: 
1.344     albertel 2842:     if (%newrecord) {
                   2843:         if (@version_parts) {
1.364     banghart 2844:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2845:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2846: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2847: 	    foreach my $new_part (@version_parts) {
                   2848: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2849: 				$new_part,\%newrecord);
                   2850: 	    }
1.259     banghart 2851:         }
1.44      ng       2852: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2853: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2854: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2855: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2856:     }
1.269     raeburn  2857:     if ($aggregateflag) {
                   2858:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2859: 			      $cdom,$cnum);
1.269     raeburn  2860:     }
1.301     albertel 2861:     return ('',$pts,$wgt);
1.36      ng       2862: }
1.322     albertel 2863: 
1.380     albertel 2864: sub check_and_remove_from_queue {
                   2865:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2866:     my @ungraded_parts;
                   2867:     foreach my $part (@{$parts}) {
                   2868: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2869: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2870: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2871: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2872: 		) {
                   2873: 	    push(@ungraded_parts, $part);
                   2874: 	}
                   2875:     }
                   2876:     if ( !@ungraded_parts ) {
                   2877: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2878: 					       $cnum,$domain,$stuname);
                   2879:     }
                   2880: }
                   2881: 
1.337     banghart 2882: sub handback_files {
                   2883:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2884:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2885:     my $res_error;
                   2886:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2887:     if ($res_error) {
                   2888:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2889:         return;
                   2890:     }
1.654     raeburn  2891:     my @handedback;
                   2892:     my $file_msg;
1.375     albertel 2893:     my @part_response_id = &flatten_responseType($responseType);
                   2894:     foreach my $part_response_id (@part_response_id) {
                   2895:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2896: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  2897:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   2898:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   2899:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   2900:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   2901:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 2902:                     my ($directory,$answer_file) = 
1.654     raeburn  2903:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 2904:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2905: 		        &file_name_version_ext($answer_file);
1.355     banghart 2906: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2907:                     my $getpropath = 1;
1.662   ! raeburn  2908:                     my ($dir_list,$listerror) = 
        !          2909:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
        !          2910:                                                  $domain,$stuname,$getpropath);
        !          2911: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.355     banghart 2912:                     # fix file name
                   2913:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2914:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  2915:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 2916:             	                                $save_file_name);
1.337     banghart 2917:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2918:                         $request->print('<br /><span class="LC_error">'.
                   2919:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  2920:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  2921:                                         '</span>');
1.356     banghart 2922:                     } else {
1.360     banghart 2923:                         # mark the file as read only
1.654     raeburn  2924:                         push(@handedback,$save_file_name);
1.367     albertel 2925: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2926: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2927: 			}
                   2928:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  2929: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 2930:                     }
1.654     raeburn  2931:                     $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 2932:                 }
                   2933:             }
                   2934:         }
1.654     raeburn  2935:     }
                   2936:     if (@handedback > 0) {
                   2937:         $request->print('<br />');
                   2938:         my @what = ($symb,$env{'request.course.id'},'handback');
                   2939:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   2940:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   2941:         my ($subject,$message);
                   2942:         if (scalar(@handedback) == 1) {
                   2943:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   2944:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   2945:         } else {
                   2946:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   2947:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   2948:         }
                   2949:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   2950:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   2951:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   2952:         my ($feedurl,$showsymb) =
                   2953:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   2954:         my $restitle = &Apache::lonnet::gettitle($symb);
                   2955:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   2956:         my $msgstatus =
                   2957:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   2958:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   2959:                  $restitle);
                   2960:         if ($msgstatus) {
                   2961:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   2962:         }
                   2963:     }
1.338     banghart 2964:     return;
1.337     banghart 2965: }
                   2966: 
1.418     albertel 2967: sub get_feedurl_and_symb {
                   2968:     my ($symb,$uname,$udom) = @_;
                   2969:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2970:     $url = &Apache::lonnet::clutter($url);
                   2971:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2972: 					$symb,$udom,$uname);
                   2973:     if ($encrypturl =~ /^yes$/i) {
                   2974: 	&Apache::lonenc::encrypted(\$url,1);
                   2975: 	&Apache::lonenc::encrypted(\$symb,1);
                   2976:     }
                   2977:     return ($url,$symb);
                   2978: }
                   2979: 
1.313     banghart 2980: sub get_submitted_files {
                   2981:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2982:     my @files;
                   2983:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2984:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2985:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2986:     	    push(@files,$file_url.$file);
                   2987:         }
                   2988:     }
                   2989:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2990:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2991:     }
                   2992:     return (\@files);
                   2993: }
1.322     albertel 2994: 
1.269     raeburn  2995: # ----------- Provides number of tries since last reset.
                   2996: sub get_num_tries {
                   2997:     my ($record,$last_reset,$part) = @_;
                   2998:     my $timestamp = '';
                   2999:     my $num_tries = 0;
                   3000:     if ($$record{'version'}) {
                   3001:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3002:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3003:                 $timestamp = $$record{$version.':timestamp'};
                   3004:                 if ($timestamp > $last_reset) {
                   3005:                     $num_tries ++;
                   3006:                 } else {
                   3007:                     last;
                   3008:                 }
                   3009:             }
                   3010:         }
                   3011:     }
                   3012:     return $num_tries;
                   3013: }
                   3014: 
                   3015: # ----------- Determine decrements required in aggregate totals 
                   3016: sub decrement_aggs {
                   3017:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3018:     my %decrement = (
                   3019:                         attempts => 0,
                   3020:                         users => 0,
                   3021:                         correct => 0
                   3022:                     );
                   3023:     $decrement{'attempts'} = $aggtries;
                   3024:     if ($solvedstatus =~ /^correct/) {
                   3025:         $decrement{'correct'} = 1;
                   3026:     }
                   3027:     if ($aggtries == $totaltries) {
                   3028:         $decrement{'users'} = 1;
                   3029:     }
1.524     raeburn  3030:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3031:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3032:     }
                   3033:     return;
                   3034: }
                   3035: 
                   3036: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3037: sub get_last_resets {
1.270     albertel 3038:     my ($symb,$courseid,$partids) =@_;
                   3039:     my %last_resets;
1.269     raeburn  3040:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3041:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3042:     my @keys;
                   3043:     foreach my $part (@{$partids}) {
                   3044: 	push(@keys,"$symb\0$part\0resettime");
                   3045:     }
                   3046:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3047: 				     $cdom,$cname);
                   3048:     foreach my $part (@{$partids}) {
                   3049: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3050:     }
1.270     albertel 3051:     return %last_resets;
1.269     raeburn  3052: }
                   3053: 
1.251     banghart 3054: # ----------- Handles creating versions for portfolio files as answers
                   3055: sub version_portfiles {
1.343     banghart 3056:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3057:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3058:     my @returned_keys;
1.255     banghart 3059:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3060:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3061:     foreach my $key (keys(%$record)) {
1.259     banghart 3062:         my $new_portfiles;
1.263     banghart 3063:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3064:             my @versioned_portfiles;
1.367     albertel 3065:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3066:             foreach my $file (@portfiles) {
1.306     banghart 3067:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3068:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3069: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3070: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3071:                 my $getpropath = 1;    
1.662   ! raeburn  3072:                 my ($dir_list,$listerror) = 
        !          3073:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
        !          3074:                                              $stu_name,$getpropath);
        !          3075:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3076:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3077:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3078:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3079:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3080:                         [$directory.$new_answer],
1.306     banghart 3081:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3082:                 }
1.252     banghart 3083:             }
1.343     banghart 3084:             $$record{$key} = join(',',@versioned_portfiles);
                   3085:             push(@returned_keys,$key);
1.251     banghart 3086:         }
                   3087:     } 
1.343     banghart 3088:     return (@returned_keys);   
1.305     banghart 3089: }
                   3090: 
1.307     banghart 3091: sub get_next_version {
1.341     banghart 3092:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3093:     my $version;
1.662   ! raeburn  3094:     if (ref($dir_list) eq 'ARRAY') {
        !          3095:         foreach my $row (@{$dir_list}) {
        !          3096:             my ($file) = split(/\&/,$row,2);
        !          3097:             my ($file_name,$file_version,$file_ext) =
        !          3098: 	        &file_name_version_ext($file);
        !          3099:             if (($file_name eq $answer_name) && 
        !          3100: 	        ($file_ext eq $answer_ext)) {
        !          3101:                      # gets here if filename and extension match, 
        !          3102:                      # regardless of version
1.307     banghart 3103:                 if ($file_version ne '') {
1.662   ! raeburn  3104:                     # a versioned file is found  so save it for later
        !          3105:                     if ($file_version > $version) {
        !          3106: 		        $version = $file_version;
        !          3107: 	            }
        !          3108:                 }
1.307     banghart 3109:             }
                   3110:         }
1.662   ! raeburn  3111:     }
1.307     banghart 3112:     $version ++;
                   3113:     return($version);
                   3114: }
                   3115: 
1.305     banghart 3116: sub version_selected_portfile {
1.306     banghart 3117:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3118:     my ($answer_name,$answer_ver,$answer_ext) =
                   3119:         &file_name_version_ext($file_name);
                   3120:     my $new_answer;
                   3121:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3122:     if($env{'form.copy'} eq '-1') {
                   3123:         $new_answer = 'problem getting file';
                   3124:     } else {
                   3125:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3126:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3127:                             $stu_name,$domain,'copy',
                   3128: 		        '/portfolio'.$directory.$new_answer);
                   3129:     }    
                   3130:     return ($new_answer);
1.251     banghart 3131: }
                   3132: 
1.304     albertel 3133: sub file_name_version_ext {
                   3134:     my ($file)=@_;
                   3135:     my @file_parts = split(/\./, $file);
                   3136:     my ($name,$version,$ext);
                   3137:     if (@file_parts > 1) {
                   3138: 	$ext=pop(@file_parts);
                   3139: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3140: 	    $version=pop(@file_parts);
                   3141: 	}
                   3142: 	$name=join('.',@file_parts);
                   3143:     } else {
                   3144: 	$name=join('.',@file_parts);
                   3145:     }
                   3146:     return($name,$version,$ext);
                   3147: }
                   3148: 
1.44      ng       3149: #--------------------------------------------------------------------------------------
                   3150: #
                   3151: #-------------------------- Next few routines handles grading by section or whole class
                   3152: #
                   3153: #--- Javascript to handle grading by section or whole class
1.42      ng       3154: sub viewgrades_js {
                   3155:     my ($request) = shift;
                   3156: 
1.539     riegler  3157:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3158:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3159:    function writePoint(partid,weight,point) {
1.125     ng       3160: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3161: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3162: 	if (point == "textval") {
1.125     ng       3163: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3164: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3165: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3166: 		var resetbox = false;
                   3167: 		for (var i=0; i<radioButton.length; i++) {
                   3168: 		    if (radioButton[i].checked) {
                   3169: 			textbox.value = i;
                   3170: 			resetbox = true;
                   3171: 		    }
                   3172: 		}
                   3173: 		if (!resetbox) {
                   3174: 		    textbox.value = "";
                   3175: 		}
                   3176: 		return;
                   3177: 	    }
1.109     matthew  3178: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3179: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3180: 				   ") greater than the weight for the part. Accept?");
                   3181: 		if (resp == false) {
                   3182: 		    textbox.value = "";
                   3183: 		    return;
                   3184: 		}
                   3185: 	    }
1.42      ng       3186: 	    for (var i=0; i<radioButton.length; i++) {
                   3187: 		radioButton[i].checked=false;
1.109     matthew  3188: 		if (parseFloat(point) == i) {
1.42      ng       3189: 		    radioButton[i].checked=true;
                   3190: 		}
                   3191: 	    }
1.41      ng       3192: 
1.42      ng       3193: 	} else {
1.125     ng       3194: 	    textbox.value = parseFloat(point);
1.42      ng       3195: 	}
1.41      ng       3196: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3197: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3198: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3199: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3200: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3201: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3202: 	    if (saveval != "correct") {
                   3203: 		scorename.value = point;
1.43      ng       3204: 		if (selname[0].selected != true) {
                   3205: 		    selname[0].selected = true;
                   3206: 		}
1.42      ng       3207: 	    }
                   3208: 	}
1.125     ng       3209: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3210:     }
                   3211: 
                   3212:     function writeRadText(partid,weight) {
1.125     ng       3213: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3214: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3215:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3216: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3217: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3218: 	    for (var i=0; i<radioButton.length; i++) {
                   3219: 		radioButton[i].checked=false;
                   3220: 
                   3221: 	    }
                   3222: 	    textbox.value = "";
                   3223: 
                   3224: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3225: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3226: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3227: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3228: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3229: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3230: 		if ((saveval != "correct") || override) {
1.42      ng       3231: 		    scorename.value = "";
1.125     ng       3232: 		    if (selval[1].selected) {
                   3233: 			selname[1].selected = true;
                   3234: 		    } else {
                   3235: 			selname[2].selected = true;
                   3236: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3237: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3238: 		    }
1.42      ng       3239: 		}
                   3240: 	    }
1.43      ng       3241: 	} else {
                   3242: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3243: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3244: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3245: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3246: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3247: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3248: 		if ((saveval != "correct") || override) {
1.125     ng       3249: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3250: 		    selname[0].selected = true;
                   3251: 		}
                   3252: 	    }
                   3253: 	}	    
1.42      ng       3254:     }
                   3255: 
                   3256:     function changeSelect(partid,user) {
1.125     ng       3257: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3258: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3259: 	var point  = textbox.value;
1.125     ng       3260: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3261: 
1.109     matthew  3262: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3263: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3264: 	    textbox.value = "";
                   3265: 	    return;
                   3266: 	}
1.109     matthew  3267: 	if (parseFloat(point) > parseFloat(weight)) {
                   3268: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3269: 			       ") greater than the weight of the part. Accept?");
                   3270: 	    if (resp == false) {
                   3271: 		textbox.value = "";
                   3272: 		return;
                   3273: 	    }
                   3274: 	}
1.42      ng       3275: 	selval[0].selected = true;
                   3276:     }
                   3277: 
                   3278:     function changeOneScore(partid,user) {
1.125     ng       3279: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3280: 	if (selval[1].selected || selval[2].selected) {
                   3281: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3282: 	    if (selval[2].selected) {
                   3283: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3284: 	    }
1.269     raeburn  3285:         }
1.42      ng       3286:     }
                   3287: 
                   3288:     function resetEntry(numpart) {
                   3289: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3290: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3291: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3292: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3293: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3294: 	    for (var i=0; i<radioButton.length; i++) {
                   3295: 		radioButton[i].checked=false;
                   3296: 
                   3297: 	    }
                   3298: 	    textbox.value = "";
                   3299: 	    selval[0].selected = true;
                   3300: 
                   3301: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3302: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3303: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3304: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3305: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3306: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3307: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3308: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3309: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3310: 		if (saveselval == "excused") {
1.43      ng       3311: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3312: 		} else {
1.43      ng       3313: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3314: 		}
                   3315: 	    }
1.41      ng       3316: 	}
1.42      ng       3317:     }
                   3318: 
1.41      ng       3319: VIEWJAVASCRIPT
1.42      ng       3320: }
                   3321: 
1.44      ng       3322: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3323: sub viewgrades {
1.608     www      3324:     my ($request,$symb) = @_;
1.42      ng       3325:     &viewgrades_js($request);
1.41      ng       3326: 
1.168     albertel 3327:     #need to make sure we have the correct data for later EXT calls, 
                   3328:     #thus invalidate the cache
                   3329:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3330:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3331:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3332:     &Apache::lonnet::clear_EXT_cache_status();
                   3333: 
1.398     albertel 3334:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3335: 
                   3336:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3337:     $result.=&jscriptNform($symb);
1.41      ng       3338: 
1.44      ng       3339:     #beginning of class grading form
1.442     banghart 3340:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3341:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3342: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3343: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3344: 	&build_section_inputs().
1.442     banghart 3345: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3346: 
1.560     raeburn  3347:     my ($common_header,$specific_header);
1.257     albertel 3348:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3349: 	$common_header = &mt('Assign Common Grade to Class');
                   3350:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3351:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3352:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3353: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3354:     } else {
1.560     raeburn  3355:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3356:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3357: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3358:     }
1.560     raeburn  3359:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3360:     #radio buttons/text box for assigning points for a section or class.
                   3361:     #handles different parts of a problem
1.582     raeburn  3362:     my $res_error;
                   3363:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3364:     if ($res_error) {
                   3365:         return &navmap_errormsg();
                   3366:     }
1.42      ng       3367:     my %weight = ();
                   3368:     my $ctsparts = 0;
1.45      ng       3369:     my %seen = ();
1.375     albertel 3370:     my @part_response_id = &flatten_responseType($responseType);
                   3371:     foreach my $part_response_id (@part_response_id) {
                   3372:     	my ($partid,$respid) = @{ $part_response_id };
                   3373: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3374: 	next if $seen{$partid};
                   3375: 	$seen{$partid}++;
1.375     albertel 3376: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3377: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3378: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3379: 
1.324     albertel 3380: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3381: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3382: 	my $ctr = 0;
1.42      ng       3383: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3384: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3385: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3386: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3387: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3388: 	    $ctr++;
                   3389: 	}
1.485     albertel 3390: 	$radio.='</tr></table>';
                   3391: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3392: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3393: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3394: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3395: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3396: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3397: 		$weight{$partid}.')"> '.
1.401     albertel 3398: 	    '<option selected="selected"> </option>'.
1.485     albertel 3399: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3400: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3401: 	    '</select></td>'.
                   3402:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3403: 	$line.='<input type="hidden" name="partid_'.
                   3404: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3405: 	$line.='<input type="hidden" name="weight_'.
                   3406: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3407: 
                   3408: 	$result.=
                   3409: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3410: 	    '<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 3411: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3412: 	$ctsparts++;
1.41      ng       3413:     }
1.474     albertel 3414:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3415: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3416:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3417: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3418: 
1.44      ng       3419:     #table listing all the students in a section/class
                   3420:     #header of table
1.560     raeburn  3421:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3422:               &Apache::loncommon::start_data_table().
                   3423: 	      &Apache::loncommon::start_data_table_header_row().
                   3424: 	      '<th>'.&mt('No.').'</th>'.
                   3425: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3426:     my $partserror;
                   3427:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3428:     if ($partserror) {
                   3429:         return &navmap_errormsg();
                   3430:     }
1.324     albertel 3431:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3432:     my @partids = ();
1.41      ng       3433:     foreach my $part (@parts) {
                   3434: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3435:         my $narrowtext = &mt('Tries');
                   3436: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3437: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3438: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3439:         push(@partids,$partid);
1.628     www      3440: #
                   3441: # FIXME: Looks like $display looks at English text
                   3442: #
1.324     albertel 3443: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3444: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3445: 	    $result.='<th>'.
                   3446: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3447: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3448: 	    next;
1.485     albertel 3449: 	    
1.207     albertel 3450: 	} else {
1.485     albertel 3451: 	    if ($display =~ /Problem Status/) {
                   3452: 		my $grade_status_mt = &mt('Grade Status');
                   3453: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3454: 	    }
                   3455: 	    my $part_mt = &mt('Part:');
                   3456: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3457: 	}
1.485     albertel 3458: 
1.474     albertel 3459: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3460:     }
1.474     albertel 3461:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3462: 
1.270     albertel 3463:     my %last_resets = 
                   3464: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3465: 
1.41      ng       3466:     #get info for each student
1.44      ng       3467:     #list all the students - with points and grade status
1.257     albertel 3468:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3469:     my $ctr = 0;
1.294     albertel 3470:     foreach (sort 
                   3471: 	     {
                   3472: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3473: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3474: 		 }
                   3475: 		 return $a cmp $b;
                   3476: 	     } (keys(%$fullname))) {
1.126     ng       3477: 	$ctr++;
1.324     albertel 3478: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3479: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3480:     }
1.474     albertel 3481:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3482:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3483:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3484: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3485:     if (scalar(%$fullname) eq 0) {
                   3486: 	my $colspan=3+scalar(@parts);
1.433     banghart 3487: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3488:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3489: 	$result='<span class="LC_warning">'.
1.485     albertel 3490: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3491: 	        $section_display, $stu_status).
1.433     banghart 3492: 	    '</span>';
1.96      albertel 3493:     }
1.41      ng       3494:     return $result;
                   3495: }
                   3496: 
1.44      ng       3497: #--- call by previous routine to display each student
1.41      ng       3498: sub viewstudentgrade {
1.324     albertel 3499:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3500:     my ($uname,$udom) = split(/:/,$student);
                   3501:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3502:     my %aggregates = (); 
1.474     albertel 3503:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3504: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3505: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3506: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3507: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3508: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3509:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3510:     foreach my $apart (@$parts) {
                   3511: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3512: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3513:         $result.='<td align="center">';
1.269     raeburn  3514:         my ($aggtries,$totaltries);
                   3515:         unless (exists($aggregates{$part})) {
1.270     albertel 3516: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3517: 
                   3518: 	    $aggtries = $totaltries;
1.269     raeburn  3519:             if ($$last_resets{$part}) {  
1.270     albertel 3520:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3521: 					   $part);
                   3522:             }
1.269     raeburn  3523:             $result.='<input type="hidden" name="'.
                   3524:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3525:             $result.='<input type="hidden" name="'.
                   3526:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3527:             $aggregates{$part} = 1;
                   3528:         }
1.41      ng       3529: 	if ($type eq 'awarded') {
1.320     albertel 3530: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3531: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3532: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3533: 	    $result.='<input type="text" name="'.
1.89      albertel 3534: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3535:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3536: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3537: 	} elsif ($type eq 'solved') {
                   3538: 	    my ($status,$foo)=split(/_/,$score,2);
                   3539: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3540: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3541: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3542: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3543: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3544:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3545: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3546: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3547: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3548: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3549: 	} else {
                   3550: 	    $result.='<input type="hidden" name="'.
                   3551: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3552: 		    "\n";
1.233     albertel 3553: 	    $result.='<input type="text" name="'.
1.122     ng       3554: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3555: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3556: 	}
                   3557:     }
1.474     albertel 3558:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3559:     return $result;
1.38      ng       3560: }
                   3561: 
1.44      ng       3562: #--- change scores for all the students in a section/class
                   3563: #    record does not get update if unchanged
1.38      ng       3564: sub editgrades {
1.608     www      3565:     my ($request,$symb) = @_;
1.41      ng       3566: 
1.433     banghart 3567:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3568:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3569:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3570: 
1.477     albertel 3571:     my $result= &Apache::loncommon::start_data_table().
                   3572: 	&Apache::loncommon::start_data_table_header_row().
                   3573: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3574: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3575:     my %scoreptr = (
                   3576: 		    'correct'  =>'correct_by_override',
                   3577: 		    'incorrect'=>'incorrect_by_override',
                   3578: 		    'excused'  =>'excused',
                   3579: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3580:                     'credited' =>'credit_attempted',
1.43      ng       3581: 		    'nothing'  => '',
                   3582: 		    );
1.257     albertel 3583:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3584: 
1.44      ng       3585:     my (@partid);
                   3586:     my %weight = ();
1.54      albertel 3587:     my %columns = ();
1.44      ng       3588:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3589: 
1.582     raeburn  3590:     my $partserror;
                   3591:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3592:     if ($partserror) {
                   3593:         return &navmap_errormsg();
                   3594:     }
1.54      albertel 3595:     my $header;
1.257     albertel 3596:     while ($ctr < $env{'form.totalparts'}) {
                   3597: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3598: 	push(@partid,$partid);
1.257     albertel 3599: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3600: 	$ctr++;
1.54      albertel 3601:     }
1.324     albertel 3602:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3603:     foreach my $partid (@partid) {
1.478     albertel 3604: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3605: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3606: 	$columns{$partid}=2;
                   3607: 	foreach my $stores (@parts) {
                   3608: 	    my ($part,$type) = &split_part_type($stores);
                   3609: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3610: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3611: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3612: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3613:             my $narrowtext = &mt('Tries');
                   3614: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3615: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3616: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3617: 	    $columns{$partid}+=2;
                   3618: 	}
                   3619:     }
                   3620:     foreach my $partid (@partid) {
1.324     albertel 3621: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3622: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3623: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3624: 	    '</th>';
1.54      albertel 3625: 
1.44      ng       3626:     }
1.477     albertel 3627:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3628: 	&Apache::loncommon::start_data_table_header_row().
                   3629: 	$header.
                   3630: 	&Apache::loncommon::end_data_table_header_row();
                   3631:     my @noupdate;
1.126     ng       3632:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3633:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3634: 	my $line;
1.257     albertel 3635: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3636: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3637: 	my %newrecord;
                   3638: 	my $updateflag = 0;
1.281     albertel 3639: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3640: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3641: 	if (!&canmodify($usec)) {
1.126     ng       3642: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3643: 	    push(@noupdate,
1.478     albertel 3644: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3645: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3646: 	    next;
                   3647: 	}
1.269     raeburn  3648:         my %aggregate = ();
                   3649:         my $aggregateflag = 0;
1.281     albertel 3650: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3651: 	foreach (@partid) {
1.257     albertel 3652: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3653: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3654: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3655: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3656: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3657: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3658: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3659: 	    my $score;
                   3660: 	    if ($partial eq '') {
1.257     albertel 3661: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3662: 	    } elsif ($partial > 0) {
                   3663: 		$score = 'correct_by_override';
                   3664: 	    } elsif ($partial == 0) {
                   3665: 		$score = 'incorrect_by_override';
                   3666: 	    }
1.257     albertel 3667: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3668: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3669: 
1.292     albertel 3670: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3671: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3672: 	    if ($dropMenu eq 'reset status' &&
                   3673: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3674: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3675: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3676: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3677: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3678: 		$updateflag = 1;
1.269     raeburn  3679:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3680:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3681:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3682:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3683:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3684:                     $aggregateflag = 1;
                   3685:                 }
1.139     albertel 3686: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3687: 		$updateflag = 1;
                   3688: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3689: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3690: 		$rec_update++;
1.125     ng       3691: 	    }
                   3692: 
1.93      albertel 3693: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3694: 		'<td align="center">'.$awarded.
                   3695: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3696: 
1.54      albertel 3697: 
                   3698: 	    my $partid=$_;
                   3699: 	    foreach my $stores (@parts) {
                   3700: 		my ($part,$type) = &split_part_type($stores);
                   3701: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3702: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3703: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3704: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3705: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3706: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3707: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3708: 		    $updateflag=1;
                   3709: 		}
1.93      albertel 3710: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3711: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3712: 	    }
1.44      ng       3713: 	}
1.477     albertel 3714: 	$line.="\n";
1.301     albertel 3715: 
                   3716: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3717: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3718: 
1.44      ng       3719: 	if ($updateflag) {
                   3720: 	    $count++;
1.257     albertel 3721: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3722: 				    $udom,$uname);
1.301     albertel 3723: 
                   3724: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3725: 					      $cnum,$udom,$uname)) {
                   3726: 		# need to figure out if should be in queue.
                   3727: 		my %record =  
                   3728: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3729: 					     $udom,$uname);
                   3730: 		my $all_graded = 1;
                   3731: 		my $none_graded = 1;
                   3732: 		foreach my $part (@parts) {
                   3733: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3734: 			$all_graded = 0;
                   3735: 		    } else {
                   3736: 			$none_graded = 0;
                   3737: 		    }
                   3738: 		}
                   3739: 
                   3740: 		if ($all_graded || $none_graded) {
                   3741: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3742: 							   $symb,$cdom,$cnum,
                   3743: 							   $udom,$uname);
                   3744: 		}
                   3745: 	    }
                   3746: 
1.477     albertel 3747: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3748: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3749: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3750: 	    $updateCtr++;
1.93      albertel 3751: 	} else {
1.477     albertel 3752: 	    push(@noupdate,
                   3753: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3754: 	    $noupdateCtr++;
1.44      ng       3755: 	}
1.269     raeburn  3756:         if ($aggregateflag) {
                   3757:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3758: 				  $cdom,$cnum);
1.269     raeburn  3759:         }
1.93      albertel 3760:     }
1.477     albertel 3761:     if (@noupdate) {
1.126     ng       3762: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3763: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3764: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3765: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3766: 	    &mt('No Changes Occurred For the Students Below').
                   3767: 	    '</td>'.
1.477     albertel 3768: 	    &Apache::loncommon::end_data_table_row();
                   3769: 	foreach my $line (@noupdate) {
                   3770: 	    $result.=
                   3771: 		&Apache::loncommon::start_data_table_row().
                   3772: 		$line.
                   3773: 		&Apache::loncommon::end_data_table_row();
                   3774: 	}
1.44      ng       3775:     }
1.614     www      3776:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3777:     my $msg = '<p><b>'.
                   3778: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3779: 	    $rec_update,$count).'</b><br />'.
                   3780: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3781: 	'</b></p>';
1.44      ng       3782:     return $title.$msg.$result;
1.5       albertel 3783: }
1.54      albertel 3784: 
                   3785: sub split_part_type {
                   3786:     my ($partstr) = @_;
                   3787:     my ($temp,@allparts)=split(/_/,$partstr);
                   3788:     my $type=pop(@allparts);
1.439     albertel 3789:     my $part=join('_',@allparts);
1.54      albertel 3790:     return ($part,$type);
                   3791: }
                   3792: 
1.44      ng       3793: #------------- end of section for handling grading by section/class ---------
                   3794: #
                   3795: #----------------------------------------------------------------------------
                   3796: 
1.5       albertel 3797: 
1.44      ng       3798: #----------------------------------------------------------------------------
                   3799: #
                   3800: #-------------------------- Next few routines handles grading by csv upload
                   3801: #
                   3802: #--- Javascript to handle csv upload
1.27      albertel 3803: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3804:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3805:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3806:   return(<<ENDPICK);
                   3807:   function verify(vf) {
                   3808:     var foundsomething=0;
                   3809:     var founduname=0;
1.243     albertel 3810:     var foundID=0;
1.27      albertel 3811:     for (i=0;i<=vf.nfields.value;i++) {
                   3812:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3813:       if (i==0 && tw!=0) { foundID=1; }
                   3814:       if (i==1 && tw!=0) { founduname=1; }
                   3815:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3816:     }
1.246     albertel 3817:     if (founduname==0 && foundID==0) {
                   3818: 	alert('$error1');
                   3819: 	return;
1.27      albertel 3820:     }
                   3821:     if (foundsomething==0) {
1.246     albertel 3822: 	alert('$error2');
                   3823: 	return;
1.27      albertel 3824:     }
                   3825:     vf.submit();
                   3826:   }
                   3827:   function flip(vf,tf) {
                   3828:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3829:     var i;
                   3830:     for (i=0;i<=vf.nfields.value;i++) {
                   3831:       //can not pick the same destination field for both name and domain
                   3832:       if (((i ==0)||(i ==1)) && 
                   3833:           ((tf==0)||(tf==1)) && 
                   3834:           (i!=tf) &&
                   3835:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3836:         eval('vf.f'+i+'.selectedIndex=0;')
                   3837:       }
                   3838:     }
                   3839:   }
                   3840: ENDPICK
                   3841: }
                   3842: 
                   3843: sub csvupload_javascript_forward_associate {
1.573     bisitz   3844:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3845:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3846:   return(<<ENDPICK);
                   3847:   function verify(vf) {
                   3848:     var foundsomething=0;
                   3849:     var founduname=0;
1.243     albertel 3850:     var foundID=0;
1.27      albertel 3851:     for (i=0;i<=vf.nfields.value;i++) {
                   3852:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3853:       if (tw==1) { foundID=1; }
                   3854:       if (tw==2) { founduname=1; }
                   3855:       if (tw>3) { foundsomething=1; }
1.27      albertel 3856:     }
1.246     albertel 3857:     if (founduname==0 && foundID==0) {
                   3858: 	alert('$error1');
                   3859: 	return;
1.27      albertel 3860:     }
                   3861:     if (foundsomething==0) {
1.246     albertel 3862: 	alert('$error2');
                   3863: 	return;
1.27      albertel 3864:     }
                   3865:     vf.submit();
                   3866:   }
                   3867:   function flip(vf,tf) {
                   3868:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3869:     var i;
                   3870:     //can not pick the same destination field twice
                   3871:     for (i=0;i<=vf.nfields.value;i++) {
                   3872:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3873:         eval('vf.f'+i+'.selectedIndex=0;')
                   3874:       }
                   3875:     }
                   3876:   }
                   3877: ENDPICK
                   3878: }
                   3879: 
1.26      albertel 3880: sub csvuploadmap_header {
1.324     albertel 3881:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3882:     my $javascript;
1.257     albertel 3883:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3884: 	$javascript=&csvupload_javascript_reverse_associate();
                   3885:     } else {
                   3886: 	$javascript=&csvupload_javascript_forward_associate();
                   3887:     }
1.45      ng       3888: 
1.418     albertel 3889:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3890:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3891:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3892:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3893:     my $reverse=&mt("Reverse Association");
1.41      ng       3894:     $request->print(<<ENDPICK);
1.632     www      3895: <br />
                   3896: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3897: <input type="hidden" name="associate"  value="" />
                   3898: <input type="hidden" name="phase"      value="three" />
                   3899: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3900: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3901: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3902: <input type="hidden" name="upfile_associate" 
1.257     albertel 3903:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3904: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3905: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3906: <hr />
                   3907: ENDPICK
1.597     wenzelju 3908:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3909:     return '';
1.26      albertel 3910: 
                   3911: }
                   3912: 
                   3913: sub csvupload_fields {
1.582     raeburn  3914:     my ($symb,$errorref) = @_;
                   3915:     my (@parts) = &getpartlist($symb,$errorref);
                   3916:     if (ref($errorref)) {
                   3917:         if ($$errorref) {
                   3918:             return;
                   3919:         }
                   3920:     }
                   3921: 
1.556     weissno  3922:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3923: 		['username','Student Username'],
                   3924: 		['domain','Student Domain']);
1.324     albertel 3925:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3926:     foreach my $part (sort(@parts)) {
                   3927: 	my @datum;
                   3928: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3929: 	my $name=$part;
                   3930: 	if  (!$display) { $display = $name; }
                   3931: 	@datum=($name,$display);
1.244     albertel 3932: 	if ($name=~/^stores_(.*)_awarded/) {
                   3933: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3934: 	}
1.41      ng       3935: 	push(@fields,\@datum);
                   3936:     }
                   3937:     return (@fields);
1.26      albertel 3938: }
                   3939: 
                   3940: sub csvuploadmap_footer {
1.41      ng       3941:     my ($request,$i,$keyfields) =@_;
                   3942:     $request->print(<<ENDPICK);
1.26      albertel 3943: </table>
                   3944: <input type="hidden" name="nfields" value="$i" />
                   3945: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3946: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3947: </form>
                   3948: ENDPICK
                   3949: }
                   3950: 
1.283     albertel 3951: sub checkforfile_js {
1.638     www      3952:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3953:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3954:     function checkUpload(formname) {
                   3955: 	if (formname.upfile.value == "") {
1.539     riegler  3956: 	    alert("$alertmsg");
1.86      ng       3957: 	    return false;
                   3958: 	}
                   3959: 	formname.submit();
                   3960:     }
                   3961: CSVFORMJS
1.283     albertel 3962:     return $result;
                   3963: }
                   3964: 
                   3965: sub upcsvScores_form {
1.608     www      3966:     my ($request,$symb) = @_;
1.283     albertel 3967:     if (!$symb) {return '';}
                   3968:     my $result=&checkforfile_js();
1.632     www      3969:     $result.=&Apache::loncommon::start_data_table().
                   3970:              &Apache::loncommon::start_data_table_header_row().
                   3971:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3972:              &Apache::loncommon::end_data_table_header_row().
                   3973:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3974:     my $upload=&mt("Upload Scores");
1.86      ng       3975:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3976:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3977:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3978:     $result.=<<ENDUPFORM;
1.106     albertel 3979: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3980: <input type="hidden" name="symb" value="$symb" />
                   3981: <input type="hidden" name="command" value="csvuploadmap" />
                   3982: $upfile_select
1.589     bisitz   3983: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3984: </form>
                   3985: ENDUPFORM
1.370     www      3986:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3987:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3988:              '</td>'.
                   3989:             &Apache::loncommon::end_data_table_row().
                   3990:             &Apache::loncommon::end_data_table();
1.86      ng       3991:     return $result;
                   3992: }
                   3993: 
                   3994: 
1.26      albertel 3995: sub csvuploadmap {
1.608     www      3996:     my ($request,$symb)= @_;
1.41      ng       3997:     if (!$symb) {return '';}
1.72      ng       3998: 
1.41      ng       3999:     my $datatoken;
1.257     albertel 4000:     if (!$env{'form.datatoken'}) {
1.41      ng       4001: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4002:     } else {
1.257     albertel 4003: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4004: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4005:     }
1.41      ng       4006:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4007:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4008:     my ($i,$keyfields);
                   4009:     if (@records) {
1.582     raeburn  4010:         my $fieldserror;
                   4011: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4012:         if ($fieldserror) {
                   4013:             $request->print(&navmap_errormsg());
                   4014:             return;
                   4015:         }
1.257     albertel 4016: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4017: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4018: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4019: 							  \@fields);
                   4020: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4021: 	    chop($keyfields);
                   4022: 	} else {
                   4023: 	    unshift(@fields,['none','']);
                   4024: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4025: 							    \@fields);
1.311     banghart 4026:             foreach my $rec (@records) {
                   4027:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4028:                 if (%temp) {
                   4029:                     $keyfields=join(',',sort(keys(%temp)));
                   4030:                     last;
                   4031:                 }
                   4032:             }
1.41      ng       4033: 	}
                   4034:     }
                   4035:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4036: 
1.41      ng       4037:     return '';
1.27      albertel 4038: }
                   4039: 
1.246     albertel 4040: sub csvuploadoptions {
1.608     www      4041:     my ($request,$symb)= @_;
1.632     www      4042:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4043:     $request->print(<<ENDPICK);
                   4044: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4045: <input type="hidden" name="command"    value="csvuploadassign" />
                   4046: <p>
                   4047: <label>
                   4048:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4049:    $overwrite
1.246     albertel 4050: </label>
                   4051: </p>
                   4052: ENDPICK
                   4053:     my %fields=&get_fields();
                   4054:     if (!defined($fields{'domain'})) {
1.257     albertel 4055: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4056: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4057:     }
1.257     albertel 4058:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4059: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4060: 	my $cleankey=$1;
                   4061: 	if ($cleankey eq 'command') { next; }
                   4062: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4063: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4064:     }
                   4065:     # FIXME do a check for any duplicated user ids...
                   4066:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4067:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4068: <hr /></form>'."\n");
1.246     albertel 4069:     return '';
                   4070: }
                   4071: 
                   4072: sub get_fields {
                   4073:     my %fields;
1.257     albertel 4074:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4075:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4076: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4077: 	    if ($env{'form.f'.$i} ne 'none') {
                   4078: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4079: 	    }
                   4080: 	} else {
1.257     albertel 4081: 	    if ($env{'form.f'.$i} ne 'none') {
                   4082: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4083: 	    }
                   4084: 	}
1.27      albertel 4085:     }
1.246     albertel 4086:     return %fields;
                   4087: }
                   4088: 
                   4089: sub csvuploadassign {
1.608     www      4090:     my ($request,$symb)= @_;
1.246     albertel 4091:     if (!$symb) {return '';}
1.345     bowersj2 4092:     my $error_msg = '';
1.246     albertel 4093:     &Apache::loncommon::load_tmp_file($request);
                   4094:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4095:     my %fields=&get_fields();
1.257     albertel 4096:     my $courseid=$env{'request.course.id'};
1.97      albertel 4097:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4098:     my @notallowed;
1.41      ng       4099:     my @skipped;
1.657     raeburn  4100:     my @warnings;
1.41      ng       4101:     my $countdone=0;
                   4102:     foreach my $grade (@gradedata) {
                   4103: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4104: 	my $domain;
                   4105: 	if ($entries{$fields{'domain'}}) {
                   4106: 	    $domain=$entries{$fields{'domain'}};
                   4107: 	} else {
1.257     albertel 4108: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4109: 	}
1.243     albertel 4110: 	$domain=~s/\s//g;
1.41      ng       4111: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4112: 	$username=~s/\s//g;
1.243     albertel 4113: 	if (!$username) {
                   4114: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4115: 	    $id=~s/\s//g;
1.243     albertel 4116: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4117: 	    $username=$ids{$id};
                   4118: 	}
1.41      ng       4119: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4120: 	    my $id=$entries{$fields{'ID'}};
                   4121: 	    $id=~s/\s//g;
                   4122: 	    if ($id) {
                   4123: 		push(@skipped,"$id:$domain");
                   4124: 	    } else {
                   4125: 		push(@skipped,"$username:$domain");
                   4126: 	    }
1.41      ng       4127: 	    next;
                   4128: 	}
1.108     albertel 4129: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4130: 	if (!&canmodify($usec)) {
                   4131: 	    push(@notallowed,"$username:$domain");
                   4132: 	    next;
                   4133: 	}
1.244     albertel 4134: 	my %points;
1.41      ng       4135: 	my %grades;
                   4136: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4137: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4138: 		$dest eq 'domain') { next; }
                   4139: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4140: 	    if ($dest=~/stores_(.*)_points/) {
                   4141: 		my $part=$1;
                   4142: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4143: 					      $symb,$domain,$username);
1.345     bowersj2 4144:                 if ($wgt) {
                   4145:                     $entries{$fields{$dest}}=~s/\s//g;
                   4146:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4147:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4148:                                           : 'correct_by_override';
1.638     www      4149:                     if ($pcr>1) {
1.657     raeburn  4150:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4151:                     }
1.345     bowersj2 4152:                     $grades{"resource.$part.awarded"}=$pcr;
                   4153:                     $grades{"resource.$part.solved"}=$award;
                   4154:                     $points{$part}=1;
                   4155:                 } else {
                   4156:                     $error_msg = "<br />" .
                   4157:                         &mt("Some point values were assigned"
                   4158:                             ." for problems with a weight "
                   4159:                             ."of zero. These values were "
                   4160:                             ."ignored.");
                   4161:                 }
1.244     albertel 4162: 	    } else {
                   4163: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4164: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4165: 		my $store_key=$dest;
                   4166: 		$store_key=~s/^stores/resource/;
                   4167: 		$store_key=~s/_/\./g;
                   4168: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4169: 	    }
1.41      ng       4170: 	}
1.508     www      4171: 	if (! %grades) { 
                   4172:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4173:         } else {
                   4174: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4175: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4176: 					   $env{'request.course.id'},
                   4177: 					   $domain,$username);
1.508     www      4178: 	   if ($result eq 'ok') {
1.627     www      4179: # Successfully stored
1.508     www      4180: 	      $request->print('.');
1.627     www      4181: # Remove from grading queue
                   4182:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4183:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4184:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4185:                                              $domain,$username);
                   4186:               $countdone++;
                   4187:            } else {
1.508     www      4188: 	      $request->print("<p><span class=\"LC_error\">".
                   4189:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4190:                                   "$username:$domain",$result)."</span></p>");
                   4191: 	   }
                   4192: 	   $request->rflush();
                   4193:         }
1.41      ng       4194:     }
1.570     www      4195:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4196:     if (@warnings) {
                   4197:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4198:         $request->print(join(', ',@warnings));
                   4199:     }
1.41      ng       4200:     if (@skipped) {
1.571     www      4201: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4202:         $request->print(join(', ',@skipped));
1.106     albertel 4203:     }
                   4204:     if (@notallowed) {
1.571     www      4205: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4206: 	$request->print(join(', ',@notallowed));
1.41      ng       4207:     }
1.106     albertel 4208:     $request->print("<br />\n");
1.345     bowersj2 4209:     return $error_msg;
1.26      albertel 4210: }
1.44      ng       4211: #------------- end of section for handling csv file upload ---------
                   4212: #
                   4213: #-------------------------------------------------------------------
                   4214: #
1.122     ng       4215: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4216: #
                   4217: #--- Select a page/sequence and a student to grade
1.68      ng       4218: sub pickStudentPage {
1.608     www      4219:     my ($request,$symb) = @_;
1.68      ng       4220: 
1.539     riegler  4221:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4222:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4223: 
                   4224: function checkPickOne(formname) {
1.76      ng       4225:     if (radioSelection(formname.student) == null) {
1.539     riegler  4226: 	alert("$alertmsg");
1.68      ng       4227: 	return;
                   4228:     }
1.125     ng       4229:     ptr = pullDownSelection(formname.selectpage);
                   4230:     formname.page.value = formname["page"+ptr].value;
                   4231:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4232:     formname.submit();
                   4233: }
                   4234: 
                   4235: LISTJAVASCRIPT
1.118     ng       4236:     &commonJSfunctions($request);
1.608     www      4237: 
1.257     albertel 4238:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4239:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4240:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4241: 
1.398     albertel 4242:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4243: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4244: 
1.80      ng       4245:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4246:     my $map_error;
                   4247:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4248:     if ($map_error) {
                   4249:         $request->print(&navmap_errormsg());
                   4250:         return; 
                   4251:     }
1.137     albertel 4252:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4253: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4254: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4255:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4256:     my $ctr=0;
1.68      ng       4257:     foreach (@$titles) {
                   4258: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4259: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4260: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4261: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4262: 	$ctr++;
1.68      ng       4263:     }
1.485     albertel 4264:     $select.= '</select>';
1.539     riegler  4265:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4266: 
1.70      ng       4267:     $ctr=0;
                   4268:     foreach (@$titles) {
                   4269: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4270: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4271: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4272: 	$ctr++;
                   4273:     }
1.72      ng       4274:     $result.='<input type="hidden" name="page" />'."\n".
                   4275: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4276: 
1.485     albertel 4277:     my $options =
                   4278: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4279: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4280:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4281: 
                   4282:     $options =
                   4283: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4284: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4285: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4286:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4287:     
                   4288:     $result.=&build_section_inputs();
1.442     banghart 4289:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4290:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4291: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4292: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4293: 
1.539     riegler  4294:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4295: 
1.80      ng       4296:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4297:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4298: 
1.68      ng       4299:     $request->print($result);
                   4300: 
1.485     albertel 4301:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4302: 	&Apache::loncommon::start_data_table().
                   4303: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4304: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4305: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4306: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4307: 	'<th>'.&nameUserString('header').'</th>'.
                   4308: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4309:  
1.76      ng       4310:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4311:     my $ptr = 1;
1.294     albertel 4312:     foreach my $student (sort 
                   4313: 			 {
                   4314: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4315: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4316: 			     }
                   4317: 			     return $a cmp $b;
                   4318: 			 } (keys(%$fullname))) {
1.68      ng       4319: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4320: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4321:                                   : '</td>');
1.126     ng       4322: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4323: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4324: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4325: 	$studentTable.=
                   4326: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4327:                          : '');
1.68      ng       4328: 	$ptr++;
                   4329:     }
1.484     albertel 4330:     if ($ptr%2 == 0) {
                   4331: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4332: 	    &Apache::loncommon::end_data_table_row();
                   4333:     }
                   4334:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4335:     $studentTable.='<input type="button" '.
1.589     bisitz   4336:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4337: 
                   4338:     $request->print($studentTable);
                   4339: 
                   4340:     return '';
                   4341: }
                   4342: 
                   4343: sub getSymbMap {
1.582     raeburn  4344:     my ($map_error) = @_;
1.132     bowersj2 4345:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4346:     unless (ref($navmap)) {
                   4347:         if (ref($map_error)) {
                   4348:             $$map_error = 'navmap';
                   4349:         }
                   4350:         return;
                   4351:     }
1.68      ng       4352:     my %symbx = ();
                   4353:     my @titles = ();
1.117     bowersj2 4354:     my $minder = 0;
                   4355: 
                   4356:     # Gather every sequence that has problems.
1.240     albertel 4357:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4358: 					       1,0,1);
1.117     bowersj2 4359:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4360: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4361: 	    my $title = $minder.'.'.
                   4362: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4363: 	    push(@titles, $title); # minder in case two titles are identical
                   4364: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4365: 	    $minder++;
1.241     albertel 4366: 	}
1.68      ng       4367:     }
                   4368:     return \@titles,\%symbx;
                   4369: }
                   4370: 
1.72      ng       4371: #
                   4372: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4373: sub displayPage {
1.608     www      4374:     my ($request,$symb) = @_;
1.257     albertel 4375:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4376:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4377:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4378:     my $pageTitle = $env{'form.page'};
1.103     albertel 4379:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4380:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4381:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4382: 
                   4383:     #need to make sure we have the correct data for later EXT calls, 
                   4384:     #thus invalidate the cache
                   4385:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4386:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4387:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4388:     &Apache::lonnet::clear_EXT_cache_status();
                   4389: 
1.103     albertel 4390:     if (!&canview($usec)) {
1.485     albertel 4391: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4392: 	return;
                   4393:     }
1.398     albertel 4394:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4395:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4396: 	'</h3>'."\n";
1.500     albertel 4397:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4398:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4399: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4400:     } else {
                   4401: 	delete($env{'form.CODE'});
                   4402:     }
1.71      ng       4403:     &sub_page_js($request);
                   4404:     $request->print($result);
                   4405: 
1.132     bowersj2 4406:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4407:     unless (ref($navmap)) {
                   4408:         $request->print(&navmap_errormsg());
                   4409:         return;
                   4410:     }
1.257     albertel 4411:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4412:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4413:     if (!$map) {
1.485     albertel 4414: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4415: 	return; 
                   4416:     }
1.68      ng       4417:     my $iterator = $navmap->getIterator($map->map_start(),
                   4418: 					$map->map_finish());
                   4419: 
1.71      ng       4420:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4421: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4422: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4423: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4424: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4425: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4426: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4427: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4428: 
1.382     albertel 4429:     if (defined($env{'form.CODE'})) {
                   4430: 	$studentTable.=
                   4431: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4432:     }
1.381     albertel 4433:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4434: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4435: 
1.594     bisitz   4436:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4437:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4438:         '</span>'."\n".
1.484     albertel 4439: 	&Apache::loncommon::start_data_table().
                   4440: 	&Apache::loncommon::start_data_table_header_row().
                   4441: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4442: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4443: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4444: 
1.329     albertel 4445:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4446:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4447:     $iterator->next(); # skip the first BEGIN_MAP
                   4448:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4449:     while ($depth > 0) {
1.68      ng       4450:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4451:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4452: 
1.385     albertel 4453:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4454: 	    my $parts = $curRes->parts();
1.68      ng       4455:             my $title = $curRes->compTitle();
1.71      ng       4456: 	    my $symbx = $curRes->symb();
1.484     albertel 4457: 	    $studentTable.=
                   4458: 		&Apache::loncommon::start_data_table_row().
                   4459: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4460: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4461: 		                        : '<br />('.&mt('[_1]parts)',
                   4462: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4463: 		 ).
                   4464: 		 '</td>';
1.71      ng       4465: 	    $studentTable.='<td valign="top">';
1.382     albertel 4466: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4467: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4468: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4469: 					     undef,'both',\%form);
1.71      ng       4470: 	    } else {
1.382     albertel 4471: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4472: 		$companswer =~ s|<form(.*?)>||g;
                   4473: 		$companswer =~ s|</form>||g;
1.71      ng       4474: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4475: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4476: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4477: #		}
1.116     ng       4478: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4479: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4480: 	    }
                   4481: 
1.257     albertel 4482: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4483: 
1.257     albertel 4484: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4485: 		if ($record{'version'} eq '') {
1.485     albertel 4486: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4487: 		} else {
1.116     ng       4488: 		    my %responseType = ();
                   4489: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4490: 			my @responseIds =$curRes->responseIds($partid);
                   4491: 			my @responseType =$curRes->responseType($partid);
                   4492: 			my %responseIds;
                   4493: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4494: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4495: 			}
                   4496: 			$responseType{$partid} = \%responseIds;
1.116     ng       4497: 		    }
1.148     albertel 4498: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4499: 
1.71      ng       4500: 		}
1.257     albertel 4501: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4502: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4503: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4504: 									$env{'request.course.id'},
1.71      ng       4505: 									'','.submission');
                   4506:  
                   4507: 	    }
1.103     albertel 4508: 	    if (&canmodify($usec)) {
1.585     bisitz   4509:             $studentTable.=&gradeBox_start();
1.103     albertel 4510: 		foreach my $partid (@{$parts}) {
                   4511: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4512: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4513: 		    $question++;
                   4514: 		}
1.585     bisitz   4515:             $studentTable.=&gradeBox_end();
1.196     albertel 4516: 		$prob++;
1.71      ng       4517: 	    }
                   4518: 	    $studentTable.='</td></tr>';
1.68      ng       4519: 
1.103     albertel 4520: 	}
1.68      ng       4521:         $curRes = $iterator->next();
                   4522:     }
                   4523: 
1.589     bisitz   4524:     $studentTable.=
                   4525:         '</table>'."\n".
                   4526:         '<input type="button" value="'.&mt('Save').'" '.
                   4527:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4528:         '</form>'."\n";
1.71      ng       4529:     $request->print($studentTable);
                   4530: 
                   4531:     return '';
1.119     ng       4532: }
                   4533: 
                   4534: sub displaySubByDates {
1.148     albertel 4535:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4536:     my $isCODE=0;
1.335     albertel 4537:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4538:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4539:     my $studentTable=&Apache::loncommon::start_data_table().
                   4540: 	&Apache::loncommon::start_data_table_header_row().
                   4541: 	'<th>'.&mt('Date/Time').'</th>'.
                   4542: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4543: 	'<th>'.&mt('Submission').'</th>'.
                   4544: 	'<th>'.&mt('Status').'</th>'.
                   4545: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4546:     my ($version);
                   4547:     my %mark;
1.148     albertel 4548:     my %orders;
1.119     ng       4549:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4550:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4551: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4552:     }
1.335     albertel 4553: 
                   4554:     my $interaction;
1.525     raeburn  4555:     my $no_increment = 1;
1.640     raeburn  4556:     my %lastrndseed;
1.119     ng       4557:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4558: 	my $timestamp = 
                   4559: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4560: 	if (exists($$record{$version.':resource.0.version'})) {
                   4561: 	    $interaction = $$record{$version.':resource.0.version'};
                   4562: 	}
                   4563: 
                   4564: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4565: 		             : "$version:resource");
1.467     albertel 4566: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4567: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4568: 	if ($isCODE) {
                   4569: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4570: 	}
1.119     ng       4571: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4572: 	my @displaySub = ();
                   4573: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4574:             my ($hidden,$type);
                   4575:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4576:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4577:                 $hidden = 1;
                   4578:             }
1.335     albertel 4579: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4580: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4581: 	    
1.122     ng       4582: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4583: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4584: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4585: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4586: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4587:                     
1.335     albertel 4588: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4589: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4590:                     $displaySub[0].='<span class="LC_nobreak"';
                   4591:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4592:                                    .' <span class="LC_internal_info">'
1.625     www      4593:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4594:                                    .'</span>'
                   4595:                                    .' <b>';
1.596     raeburn  4596:                     if ($hidden) {
                   4597:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4598:                     } else {
1.640     raeburn  4599:                         my ($trial,$rndseed,$newvariation);
                   4600:                         if ($type eq 'randomizetry') {
                   4601:                             $trial = $$record{"$where.$partid.tries"};
                   4602:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4603:                         }
1.596     raeburn  4604: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4605: 			    $displaySub[0].=&mt('Trial not counted');
                   4606: 		        } else {
                   4607: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4608: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4609:                             if ($rndseed || $lastrndseed{$partid}) {
                   4610:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4611:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4612:                                 }
                   4613:                             }
                   4614:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4615: 		        }
                   4616: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4617:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4618: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4619: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4620: 			    $orders{$partid}->{$responseId}=
                   4621: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4622:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4623: 		        }
1.640     raeburn  4624: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4625: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4626: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4627:                     }
1.147     albertel 4628: 		}
                   4629: 	    }
1.335     albertel 4630: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4631: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4632: 				    $$record{"$where.$partid.checkedin"},
                   4633: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4634: 					'<br />';
1.335     albertel 4635: 	    }
                   4636: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4637: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4638: 		    lc($$record{"$where.$partid.award"}).' '.
                   4639: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4640: 		    '<br />';
                   4641: 	    }
1.335     albertel 4642: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4643: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4644: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4645: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4646: 		$displaySub[2].=
                   4647: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4648: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4649: 	    }
                   4650: 	}
                   4651: 	# needed because old essay regrader has not parts info
                   4652: 	if (exists $$record{"$version:resource.regrader"}) {
                   4653: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4654: 	}
                   4655: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4656: 	if ($displaySub[2]) {
1.467     albertel 4657: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4658: 	}
1.467     albertel 4659: 	$studentTable.='&nbsp;</td>'.
                   4660: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4661:     }
1.467     albertel 4662:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4663:     return $studentTable;
1.71      ng       4664: }
                   4665: 
                   4666: sub updateGradeByPage {
1.608     www      4667:     my ($request,$symb) = @_;
1.71      ng       4668: 
1.257     albertel 4669:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4670:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4671:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4672:     my $pageTitle = $env{'form.page'};
1.103     albertel 4673:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4674:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4675:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4676:     if (!&canmodify($usec)) {
1.526     raeburn  4677: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4678: 	return;
                   4679:     }
1.398     albertel 4680:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4681:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4682: 	'</h3>'."\n";
1.70      ng       4683: 
1.68      ng       4684:     $request->print($result);
                   4685: 
1.582     raeburn  4686: 
1.132     bowersj2 4687:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4688:     unless (ref($navmap)) {
                   4689:         $request->print(&navmap_errormsg());
                   4690:         return;
                   4691:     }
1.257     albertel 4692:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4693:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4694:     if (!$map) {
1.527     raeburn  4695: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4696: 	return; 
                   4697:     }
1.71      ng       4698:     my $iterator = $navmap->getIterator($map->map_start(),
                   4699: 					$map->map_finish());
1.70      ng       4700: 
1.484     albertel 4701:     my $studentTable=
                   4702: 	&Apache::loncommon::start_data_table().
                   4703: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4704: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4705: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4706: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4707: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4708: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4709: 
                   4710:     $iterator->next(); # skip the first BEGIN_MAP
                   4711:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4712:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4713:     while ($depth > 0) {
1.71      ng       4714:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4715:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4716: 
1.385     albertel 4717:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4718: 	    my $parts = $curRes->parts();
1.71      ng       4719:             my $title = $curRes->compTitle();
                   4720: 	    my $symbx = $curRes->symb();
1.484     albertel 4721: 	    $studentTable.=
                   4722: 		&Apache::loncommon::start_data_table_row().
                   4723: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4724: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4725:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4726: 		.')').'</td>';
1.71      ng       4727: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4728: 
                   4729: 	    my %newrecord=();
                   4730: 	    my @displayPts=();
1.269     raeburn  4731:             my %aggregate = ();
                   4732:             my $aggregateflag = 0;
1.71      ng       4733: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4734: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4735: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4736: 
1.257     albertel 4737: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4738: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4739: 		my $partial = $newpts/$wgt;
                   4740: 		my $score;
                   4741: 		if ($partial > 0) {
                   4742: 		    $score = 'correct_by_override';
1.125     ng       4743: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4744: 		    $score = 'incorrect_by_override';
                   4745: 		}
1.257     albertel 4746: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4747: 		if ($dropMenu eq 'excused') {
1.71      ng       4748: 		    $partial = '';
                   4749: 		    $score = 'excused';
1.125     ng       4750: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4751: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4752: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4753: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4754: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4755: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4756: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4757: 		    $changeflag++;
                   4758: 		    $newpts = '';
1.269     raeburn  4759:                     
                   4760:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4761:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4762:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4763:                     if ($aggtries > 0) {
                   4764:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4765:                         $aggregateflag = 1;
                   4766:                     }
1.71      ng       4767: 		}
1.324     albertel 4768: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4769: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4770: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4771: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4772: 		    '&nbsp;<br />';
1.526     raeburn  4773: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4774: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4775: 		    '&nbsp;<br />';
1.71      ng       4776: 		$question++;
1.380     albertel 4777: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4778: 
1.71      ng       4779: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4780: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4781: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4782: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4783: 
                   4784: 		$changeflag++;
                   4785: 	    }
                   4786: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4787: 		my %record = 
                   4788: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4789: 					     $udom,$uname);
                   4790: 
                   4791: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4792: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4793: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4794: 		    $newrecord{'resource.CODE'} = '';
                   4795: 		}
1.257     albertel 4796: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4797: 					$udom,$uname);
1.382     albertel 4798: 		%record = &Apache::lonnet::restore($symbx,
                   4799: 						   $env{'request.course.id'},
                   4800: 						   $udom,$uname);
1.380     albertel 4801: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4802: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4803: 	    }
1.380     albertel 4804: 	    
1.269     raeburn  4805:             if ($aggregateflag) {
                   4806:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4807:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4808:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4809:             }
1.125     ng       4810: 
1.71      ng       4811: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4812: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4813: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4814: 
1.196     albertel 4815: 	    $prob++;
1.68      ng       4816: 	}
1.71      ng       4817:         $curRes = $iterator->next();
1.68      ng       4818:     }
1.98      albertel 4819: 
1.484     albertel 4820:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4821:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4822: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4823: 		  $changeflag));
1.76      ng       4824:     $request->print($grademsg.$studentTable);
1.68      ng       4825: 
1.70      ng       4826:     return '';
                   4827: }
                   4828: 
1.72      ng       4829: #-------- end of section for handling grading by page/sequence ---------
                   4830: #
                   4831: #-------------------------------------------------------------------
                   4832: 
1.581     www      4833: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4834: #
                   4835: #------ start of section for handling grading by page/sequence ---------
                   4836: 
1.423     albertel 4837: =pod
                   4838: 
                   4839: =head1 Bubble sheet grading routines
                   4840: 
1.424     albertel 4841:   For this documentation:
                   4842: 
                   4843:    'scanline' refers to the full line of characters
                   4844:    from the file that we are parsing that represents one entire sheet
                   4845: 
                   4846:    'bubble line' refers to the data
1.659     raeburn  4847:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 4848: 
                   4849: 
1.659     raeburn  4850: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 4851: into a course. When a user wants to grade, they select a
1.659     raeburn  4852: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 4853: one of the predefined configurations for what each scanline looks
                   4854: like.
                   4855: 
                   4856: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4857: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4858: because too light bubbling), 'double bubble' (each bubble line should
                   4859: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4860: invalid student/employee ID
1.424     albertel 4861: 
                   4862: If the CODE option is used that determines the randomization of the
1.556     weissno  4863: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4864: username:domain.
                   4865: 
                   4866: During the validation phase the instructor can choose to skip scanlines. 
                   4867: 
1.659     raeburn  4868: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 4869: 
                   4870:   scantron_original_filename (unmodified original file)
                   4871:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4872:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4873: 
                   4874: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  4875: correction information that isn't representable in the bubblesheet
1.424     albertel 4876: file (see &scantron_getfile() for more information)
                   4877: 
                   4878: After all scanlines are either valid, marked as valid or skipped, then
                   4879: foreach line foreach problem in the picked sequence, an ssi request is
                   4880: made that simulates a user submitting their selected letter(s) against
                   4881: the homework problem.
1.423     albertel 4882: 
                   4883: =over 4
                   4884: 
                   4885: 
                   4886: 
                   4887: =item defaultFormData
                   4888: 
                   4889:   Returns html hidden inputs used to hold context/default values.
                   4890: 
                   4891:  Arguments:
                   4892:   $symb - $symb of the current resource 
                   4893: 
                   4894: =cut
1.422     foxr     4895: 
1.81      albertel 4896: sub defaultFormData {
1.324     albertel 4897:     my ($symb)=@_;
1.613     www      4898:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4899: }
                   4900: 
1.447     foxr     4901: 
1.423     albertel 4902: =pod 
                   4903: 
                   4904: =item getSequenceDropDown
                   4905: 
                   4906:    Return html dropdown of possible sequences to grade
                   4907:  
                   4908:  Arguments:
1.582     raeburn  4909:    $symb - $symb of the current resource
                   4910:    $map_error - ref to scalar which will container error if
                   4911:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4912: 
                   4913: =cut
1.422     foxr     4914: 
1.75      albertel 4915: sub getSequenceDropDown {
1.582     raeburn  4916:     my ($symb,$map_error)=@_;
1.75      albertel 4917:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4918:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4919:     if (ref($map_error)) {
                   4920:         return if ($$map_error);
                   4921:     }
1.137     albertel 4922:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4923:     my $ctr=0;
                   4924:     foreach (@$titles) {
                   4925: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4926: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4927: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4928: 	    '>'.$showtitle.'</option>'."\n";
                   4929: 	$ctr++;
                   4930:     }
                   4931:     $result.= '</select>';
                   4932:     return $result;
                   4933: }
                   4934: 
1.495     albertel 4935: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4936:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4937: 
                   4938: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4939: 
1.509     raeburn  4940: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4941:                                    # matchresponse or rankresponse, where 
                   4942:                                    # an individual response can have multiple 
                   4943:                                    # lines
1.503     raeburn  4944: 
                   4945: my %responsetype_per_response;     # responsetype for each response
                   4946: 
1.495     albertel 4947: # Save and restore the bubble lines array to the form env.
                   4948: 
                   4949: 
                   4950: sub save_bubble_lines {
                   4951:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4952: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4953: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4954: 	    $first_bubble_line{$line};
1.503     raeburn  4955:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4956:             $subdivided_bubble_lines{$line};
                   4957:         $env{"form.scantron.responsetype.$line"} =
                   4958:             $responsetype_per_response{$line};
1.495     albertel 4959:     }
                   4960: }
                   4961: 
                   4962: 
                   4963: sub restore_bubble_lines {
                   4964:     my $line = 0;
                   4965:     %bubble_lines_per_response = ();
                   4966:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4967: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4968: 	$bubble_lines_per_response{$line} = $value;
                   4969: 	$first_bubble_line{$line}  =
                   4970: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4971:         $subdivided_bubble_lines{$line} =
                   4972:             $env{"form.scantron.sub_bubblelines.$line"};
                   4973:         $responsetype_per_response{$line} =
                   4974:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4975: 	$line++;
                   4976:     }
                   4977: }
                   4978: 
                   4979: #  Given the parsed scanline, get the response for 
                   4980: #  'answer' number n:
                   4981: 
                   4982: sub get_response_bubbles {
                   4983:     my ($parsed_line, $response)  = @_;
                   4984: 
                   4985:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4986:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4987:     
                   4988:     my $selected = "";
                   4989: 
                   4990:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4991: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4992: 	$bubble_line++;
                   4993:     }
                   4994:     return $selected;
                   4995: }
1.423     albertel 4996: 
                   4997: =pod 
                   4998: 
                   4999: =item scantron_filenames
                   5000: 
                   5001:    Returns a list of the scantron files in the current course 
                   5002: 
                   5003: =cut
1.422     foxr     5004: 
1.202     albertel 5005: sub scantron_filenames {
1.257     albertel 5006:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5007:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5008:     my $getpropath = 1;
1.662   ! raeburn  5009:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
        !          5010:                                                         $cname,$getpropath);
1.202     albertel 5011:     my @possiblenames;
1.662   ! raeburn  5012:     if (ref($dirlist) eq 'ARRAY') {
        !          5013:         foreach my $filename (sort(@{$dirlist})) {
        !          5014: 	    ($filename)=split(/&/,$filename);
        !          5015: 	    if ($filename!~/^scantron_orig_/) { next ; }
        !          5016: 	    $filename=~s/^scantron_orig_//;
        !          5017: 	    push(@possiblenames,$filename);
        !          5018:         }
1.202     albertel 5019:     }
                   5020:     return @possiblenames;
                   5021: }
                   5022: 
1.423     albertel 5023: =pod 
                   5024: 
                   5025: =item scantron_uploads
                   5026: 
                   5027:    Returns  html drop-down list of scantron files in current course.
                   5028: 
                   5029:  Arguments:
                   5030:    $file2grade - filename to set as selected in the dropdown
                   5031: 
                   5032: =cut
1.422     foxr     5033: 
1.202     albertel 5034: sub scantron_uploads {
1.209     ng       5035:     my ($file2grade) = @_;
1.202     albertel 5036:     my $result=	'<select name="scantron_selectfile">';
                   5037:     $result.="<option></option>";
                   5038:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5039: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5040:     }
                   5041:     $result.="</select>";
                   5042:     return $result;
                   5043: }
                   5044: 
1.423     albertel 5045: =pod 
                   5046: 
                   5047: =item scantron_scantab
                   5048: 
                   5049:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5050:   file.
                   5051: 
                   5052: =cut
1.422     foxr     5053: 
1.82      albertel 5054: sub scantron_scantab {
                   5055:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5056:     $result.='<option></option>'."\n";
1.518     raeburn  5057:     my @lines = &get_scantronformat_file();
                   5058:     if (@lines > 0) {
                   5059:         foreach my $line (@lines) {
                   5060:             next if (($line =~ /^\#/) || ($line eq ''));
                   5061: 	    my ($name,$descrip)=split(/:/,$line);
                   5062: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5063:         }
1.82      albertel 5064:     }
                   5065:     $result.='</select>'."\n";
1.518     raeburn  5066:     return $result;
                   5067: }
                   5068: 
                   5069: =pod
                   5070: 
                   5071: =item get_scantronformat_file
                   5072: 
                   5073:   Returns an array containing lines from the scantron format file for
                   5074:   the domain of the course.
                   5075: 
                   5076:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5077:   lines are from this file.
                   5078: 
                   5079:   Otherwise, if a default.tab has been published in RES space by the 
                   5080:   domainconfig user, lines are from this file.
                   5081: 
                   5082:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5083:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5084: 
1.518     raeburn  5085: =cut
                   5086: 
                   5087: sub get_scantronformat_file {
                   5088:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5089:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5090:     my $gottab = 0;
                   5091:     my @lines;
                   5092:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5093:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5094:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5095:             if ($formatfile ne '-1') {
                   5096:                 @lines = split("\n",$formatfile,-1);
                   5097:                 $gottab = 1;
                   5098:             }
                   5099:         }
                   5100:     }
                   5101:     if (!$gottab) {
                   5102:         my $confname = $cdom.'-domainconfig';
                   5103:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5104:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5105:         if ($formatfile ne '-1') {
                   5106:             @lines = split("\n",$formatfile,-1);
                   5107:             $gottab = 1;
                   5108:         }
                   5109:     }
                   5110:     if (!$gottab) {
1.519     raeburn  5111:         my @domains = &Apache::lonnet::current_machine_domains();
                   5112:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5113:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5114:             @lines = <$fh>;
                   5115:             close($fh);
                   5116:         } else {
                   5117:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5118:             @lines = <$fh>;
                   5119:             close($fh);
                   5120:         }
1.518     raeburn  5121:     }
                   5122:     return @lines;
1.82      albertel 5123: }
                   5124: 
1.423     albertel 5125: =pod 
                   5126: 
                   5127: =item scantron_CODElist
                   5128: 
                   5129:   Returns html drop down of the saved CODE lists from current course,
                   5130:   generated from earlier printings.
                   5131: 
                   5132: =cut
1.422     foxr     5133: 
1.186     albertel 5134: sub scantron_CODElist {
1.257     albertel 5135:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5136:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5137:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5138:     my $namechoice='<option></option>';
1.225     albertel 5139:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5140: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5141: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5142: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5143:     }
                   5144:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5145:     return $namechoice;
                   5146: }
                   5147: 
1.423     albertel 5148: =pod 
                   5149: 
                   5150: =item scantron_CODEunique
                   5151: 
                   5152:   Returns the html for "Each CODE to be used once" radio.
                   5153: 
                   5154: =cut
1.422     foxr     5155: 
1.186     albertel 5156: sub scantron_CODEunique {
1.532     bisitz   5157:     my $result='<span class="LC_nobreak">
1.272     albertel 5158:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5159:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5160:                 </span>
1.532     bisitz   5161:                 <span class="LC_nobreak">
1.272     albertel 5162:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5163:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5164:                 </span>';
1.186     albertel 5165:     return $result;
                   5166: }
1.423     albertel 5167: 
                   5168: =pod 
                   5169: 
                   5170: =item scantron_selectphase
                   5171: 
1.659     raeburn  5172:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5173:   Allows for - starting a grading run.
1.424     albertel 5174:              - downloading existing scan data (original, corrected
1.423     albertel 5175:                                                 or skipped info)
                   5176: 
                   5177:              - uploading new scan data
                   5178: 
                   5179:  Arguments:
                   5180:   $r          - The Apache request object
                   5181:   $file2grade - name of the file that contain the scanned data to score
                   5182: 
                   5183: =cut
1.186     albertel 5184: 
1.75      albertel 5185: sub scantron_selectphase {
1.608     www      5186:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5187:     if (!$symb) {return '';}
1.582     raeburn  5188:     my $map_error;
                   5189:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5190:     if ($map_error) {
                   5191:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5192:         return;
                   5193:     }
1.324     albertel 5194:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5195:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5196:     my $format_selector=&scantron_scantab();
1.186     albertel 5197:     my $CODE_selector=&scantron_CODElist();
                   5198:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5199:     my $result;
1.422     foxr     5200: 
1.513     foxr     5201:     $ssi_error = 0;
                   5202: 
1.606     wenzelju 5203:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5204:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5205: 
                   5206: 	# Chunk of form to prompt for a scantron file upload.
                   5207: 
                   5208:         $r->print('
                   5209:     <br />
                   5210:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5211:        '.&Apache::loncommon::start_data_table_header_row().'
                   5212:             <th>
                   5213:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5214:             </th>
                   5215:        '.&Apache::loncommon::end_data_table_header_row().'
                   5216:        '.&Apache::loncommon::start_data_table_row().'
                   5217:             <td>
                   5218: ');
1.608     www      5219:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5220:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5221:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5222:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5223:     function checkUpload(formname) {
                   5224: 	if (formname.upfile.value == "") {
                   5225: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5226: 	    return false;
                   5227: 	}
                   5228: 	formname.submit();
                   5229:     }'));
                   5230:     $r->print('
                   5231:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5232:                 '.$default_form_data.'
                   5233:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5234:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5235:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5236:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5237:                 <br />
                   5238:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5239:               </form>
                   5240: ');
                   5241: 
                   5242:         $r->print('
                   5243:             </td>
                   5244:        '.&Apache::loncommon::end_data_table_row().'
                   5245:        '.&Apache::loncommon::end_data_table().'
                   5246: ');
                   5247:     }
                   5248: 
1.422     foxr     5249:     # Chunk of form to prompt for a file to grade and how:
                   5250: 
1.489     albertel 5251:     $result.= '
                   5252:     <br />
                   5253:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5254:     <input type="hidden" name="command" value="scantron_warning" />
                   5255:     '.$default_form_data.'
                   5256:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5257:        '.&Apache::loncommon::start_data_table_header_row().'
                   5258:             <th colspan="2">
1.492     albertel 5259:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5260:             </th>
                   5261:        '.&Apache::loncommon::end_data_table_header_row().'
                   5262:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5263:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5264:        '.&Apache::loncommon::end_data_table_row().'
                   5265:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5266:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5267:        '.&Apache::loncommon::end_data_table_row().'
                   5268:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5269:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5270:        '.&Apache::loncommon::end_data_table_row().'
                   5271:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5272:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5273:        '.&Apache::loncommon::end_data_table_row().'
                   5274:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5275:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5276:        '.&Apache::loncommon::end_data_table_row().'
                   5277:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5278: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5279:             <td>
1.492     albertel 5280: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5281:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5282:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5283: 	    </td>
1.489     albertel 5284:        '.&Apache::loncommon::end_data_table_row().'
                   5285:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5286:             <td colspan="2">
1.572     www      5287:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5288:             </td>
1.489     albertel 5289:        '.&Apache::loncommon::end_data_table_row().'
                   5290:     '.&Apache::loncommon::end_data_table().'
                   5291:     </form>
                   5292: ';
1.162     albertel 5293:    
                   5294:     $r->print($result);
                   5295: 
1.422     foxr     5296: 
                   5297: 
                   5298:     # Chunk of the form that prompts to view a scoring office file,
                   5299:     # corrected file, skipped records in a file.
                   5300: 
1.489     albertel 5301:     $r->print('
                   5302:    <br />
                   5303:    <form action="/adm/grades" name="scantron_download">
                   5304:      '.$default_form_data.'
                   5305:      <input type="hidden" name="command" value="scantron_download" />
                   5306:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5307:        '.&Apache::loncommon::start_data_table_header_row().'
                   5308:               <th>
1.492     albertel 5309:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5310:               </th>
                   5311:        '.&Apache::loncommon::end_data_table_header_row().'
                   5312:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5313:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5314:                 <br />
1.492     albertel 5315:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5316:        '.&Apache::loncommon::end_data_table_row().'
                   5317:      '.&Apache::loncommon::end_data_table().'
                   5318:    </form>
                   5319:    <br />
                   5320: ');
1.162     albertel 5321: 
1.457     banghart 5322:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5323: 
1.528     raeburn  5324:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5325:              $default_form_data."\n".
                   5326:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5327:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5328:              '<th colspan="2">
1.572     www      5329:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5330:              '</th>'."\n".
                   5331:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5332:               &Apache::loncommon::start_data_table_row()."\n".
                   5333:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5334:               '<td> '.$sequence_selector.' </td>'.
                   5335:               &Apache::loncommon::end_data_table_row()."\n".
                   5336:               &Apache::loncommon::start_data_table_row()."\n".
                   5337:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5338:               '<td> '.$file_selector.' </td>'."\n".
                   5339:               &Apache::loncommon::end_data_table_row()."\n".
                   5340:               &Apache::loncommon::start_data_table_row()."\n".
                   5341:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5342:               '<td> '.$format_selector.' </td>'."\n".
                   5343:               &Apache::loncommon::end_data_table_row()."\n".
                   5344:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5345:               '<td> '.&mt('Options').' </td>'."\n".
                   5346:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5347:               &Apache::loncommon::end_data_table_row()."\n".
                   5348:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5349:               '<td colspan="2">'."\n".
                   5350:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5351:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5352:               '</td>'."\n".
                   5353:               &Apache::loncommon::end_data_table_row()."\n".
                   5354:               &Apache::loncommon::end_data_table()."\n".
                   5355:               '</form><br />');
                   5356:     return;
1.75      albertel 5357: }
                   5358: 
1.423     albertel 5359: =pod
                   5360: 
                   5361: =item get_scantron_config
                   5362: 
                   5363:    Parse and return the scantron configuration line selected as a
                   5364:    hash of configuration file fields.
                   5365: 
                   5366:  Arguments:
                   5367:     which - the name of the configuration to parse from the file.
                   5368: 
                   5369: 
                   5370:  Returns:
                   5371:             If the named configuration is not in the file, an empty
                   5372:             hash is returned.
                   5373:     a hash with the fields
                   5374:       name         - internal name for the this configuration setup
                   5375:       description  - text to display to operator that describes this config
                   5376:       CODElocation - if 0 or the string 'none'
                   5377:                           - no CODE exists for this config
                   5378:                      if -1 || the string 'letter'
                   5379:                           - a CODE exists for this config and is
                   5380:                             a string of letters
                   5381:                      Unsupported value (but planned for future support)
                   5382:                           if a positive integer
                   5383:                                - The CODE exists as the first n items from
                   5384:                                  the question section of the form
                   5385:                           if the string 'number'
                   5386:                                - The CODE exists for this config and is
                   5387:                                  a string of numbers
                   5388:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5389:                      the CODE starts
                   5390:       CODElength  - length of the CODE
1.573     bisitz   5391:       IDstart     - column where the student/employee ID starts
1.556     weissno  5392:       IDlength    - length of the student/employee ID info
1.423     albertel 5393:       Qstart      - column where the information from the bubbled
                   5394:                     'questions' start
                   5395:       Qlength     - number of columns comprising a single bubble line from
                   5396:                     the sheet. (usually either 1 or 10)
1.424     albertel 5397:       Qon         - either a single character representing the character used
1.423     albertel 5398:                     to signal a bubble was chosen in the positional setup, or
                   5399:                     the string 'letter' if the letter of the chosen bubble is
                   5400:                     in the final, or 'number' if a number representing the
                   5401:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5402:       Qoff        - the character used to represent that a bubble was
                   5403:                     left blank
1.423     albertel 5404:       PaperID     - if the scanning process generates a unique number for each
                   5405:                     sheet scanned the column that this ID number starts in
                   5406:       PaperIDlength - number of columns that comprise the unique ID number
                   5407:                       for the sheet of paper
1.424     albertel 5408:       FirstName   - column that the first name starts in
1.423     albertel 5409:       FirstNameLength - number of columns that the first name spans
                   5410:  
                   5411:       LastName    - column that the last name starts in
                   5412:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5413:       BubblesPerRow - number of bubbles available in each row used to 
                   5414:                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5415: =cut
1.422     foxr     5416: 
1.82      albertel 5417: sub get_scantron_config {
                   5418:     my ($which) = @_;
1.518     raeburn  5419:     my @lines = &get_scantronformat_file();
1.82      albertel 5420:     my %config;
1.157     albertel 5421:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5422:     foreach my $line (@lines) {
1.82      albertel 5423: 	my ($name,$descrip)=split(/:/,$line);
                   5424: 	if ($name ne $which ) { next; }
                   5425: 	chomp($line);
                   5426: 	my @config=split(/:/,$line);
                   5427: 	$config{'name'}=$config[0];
                   5428: 	$config{'description'}=$config[1];
                   5429: 	$config{'CODElocation'}=$config[2];
                   5430: 	$config{'CODEstart'}=$config[3];
                   5431: 	$config{'CODElength'}=$config[4];
                   5432: 	$config{'IDstart'}=$config[5];
                   5433: 	$config{'IDlength'}=$config[6];
                   5434: 	$config{'Qstart'}=$config[7];
1.497     foxr     5435:  	$config{'Qlength'}=$config[8];
1.82      albertel 5436: 	$config{'Qoff'}=$config[9];
                   5437: 	$config{'Qon'}=$config[10];
1.157     albertel 5438: 	$config{'PaperID'}=$config[11];
                   5439: 	$config{'PaperIDlength'}=$config[12];
                   5440: 	$config{'FirstName'}=$config[13];
                   5441: 	$config{'FirstNamelength'}=$config[14];
                   5442: 	$config{'LastName'}=$config[15];
                   5443: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5444:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5445: 	last;
                   5446:     }
                   5447:     return %config;
                   5448: }
                   5449: 
1.423     albertel 5450: =pod 
                   5451: 
                   5452: =item username_to_idmap
                   5453: 
1.556     weissno  5454:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5455:     student username:domain.
                   5456: 
                   5457:   Arguments:
                   5458: 
                   5459:     $classlist - reference to the class list hash. This is a hash
                   5460:                  keyed by student name:domain  whose elements are references
1.424     albertel 5461:                  to arrays containing various chunks of information
1.423     albertel 5462:                  about the student. (See loncoursedata for more info).
                   5463: 
                   5464:   Returns
                   5465:     %idmap - the constructed hash
                   5466: 
                   5467: =cut
                   5468: 
1.82      albertel 5469: sub username_to_idmap {
                   5470:     my ($classlist)= @_;
                   5471:     my %idmap;
                   5472:     foreach my $student (keys(%$classlist)) {
                   5473: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5474: 	    $student;
                   5475:     }
                   5476:     return %idmap;
                   5477: }
1.423     albertel 5478: 
                   5479: =pod
                   5480: 
1.424     albertel 5481: =item scantron_fixup_scanline
1.423     albertel 5482: 
                   5483:    Process a requested correction to a scanline.
                   5484: 
                   5485:   Arguments:
                   5486:     $scantron_config   - hash from &get_scantron_config()
                   5487:     $scan_data         - hash of correction information 
                   5488:                           (see &scantron_getfile())
                   5489:     $line              - existing scanline
                   5490:     $whichline         - line number of the passed in scanline
                   5491:     $field             - type of change to process 
                   5492:                          (either 
1.573     bisitz   5493:                           'ID'     -> correct the student/employee ID
1.423     albertel 5494:                           'CODE'   -> correct the CODE
                   5495:                           'answer' -> fixup the submitted answers)
                   5496:     
                   5497:    $args               - hash of additional info,
                   5498:                           - 'ID' 
                   5499:                                'newid' -> studentID to use in replacement
1.424     albertel 5500:                                           of existing one
1.423     albertel 5501:                           - 'CODE' 
                   5502:                                'CODE_ignore_dup' - set to true if duplicates
                   5503:                                                    should be ignored.
                   5504: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5505:                                         if the existing unfound code should
1.423     albertel 5506:                                         be used as is
                   5507:                           - 'answer'
                   5508:                                'response' - new answer or 'none' if blank
                   5509:                                'question' - the bubble line to change
1.503     raeburn  5510:                                'questionnum' - the question identifier,
                   5511:                                                may include subquestion. 
1.423     albertel 5512: 
                   5513:   Returns:
                   5514:     $line - the modified scanline
                   5515: 
                   5516:   Side effects: 
                   5517:     $scan_data - may be updated
                   5518: 
                   5519: =cut
                   5520: 
1.82      albertel 5521: 
1.157     albertel 5522: sub scantron_fixup_scanline {
                   5523:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5524:     if ($field eq 'ID') {
                   5525: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5526: 	    return ($line,1,'New value too large');
1.157     albertel 5527: 	}
                   5528: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5529: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5530: 				     $args->{'newid'});
                   5531: 	}
                   5532: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5533: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5534: 	if ($args->{'newid'}=~/^\s*$/) {
                   5535: 	    &scan_data($scan_data,"$whichline.user",
                   5536: 		       $args->{'username'}.':'.$args->{'domain'});
                   5537: 	}
1.186     albertel 5538:     } elsif ($field eq 'CODE') {
1.192     albertel 5539: 	if ($args->{'CODE_ignore_dup'}) {
                   5540: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5541: 	}
                   5542: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5543: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5544: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5545: 		return ($line,1,'New CODE value too large');
                   5546: 	    }
                   5547: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5548: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5549: 	    }
                   5550: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5551: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5552: 	}
1.157     albertel 5553:     } elsif ($field eq 'answer') {
1.497     foxr     5554: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5555: 	my $off=$scantron_config->{'Qoff'};
                   5556: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5557: 	my $answer=${off}x$length;
                   5558: 	if ($args->{'response'} eq 'none') {
                   5559: 	    &scan_data($scan_data,
1.503     raeburn  5560: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5561: 	} else {
                   5562: 	    if ($on eq 'letter') {
                   5563: 		my @alphabet=('A'..'Z');
                   5564: 		$answer=$alphabet[$args->{'response'}];
                   5565: 	    } elsif ($on eq 'number') {
                   5566: 		$answer=$args->{'response'}+1;
                   5567: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5568: 	    } else {
1.497     foxr     5569: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5570: 	    }
1.497     foxr     5571: 	    &scan_data($scan_data,
1.503     raeburn  5572: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5573: 	}
1.497     foxr     5574: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5575: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5576:     }
                   5577:     return $line;
                   5578: }
1.423     albertel 5579: 
                   5580: =pod
                   5581: 
                   5582: =item scan_data
                   5583: 
                   5584:     Edit or look up  an item in the scan_data hash.
                   5585: 
                   5586:   Arguments:
                   5587:     $scan_data  - The hash (see scantron_getfile)
                   5588:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5589:                   scantronfilename_key).
1.423     albertel 5590:     $data        - New value of the hash entry.
                   5591:     $delete      - If true, the entry is removed from the hash.
                   5592: 
                   5593:   Returns:
                   5594:     The new value of the hash table field (undefined if deleted).
                   5595: 
                   5596: =cut
                   5597: 
                   5598: 
1.157     albertel 5599: sub scan_data {
                   5600:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5601:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5602:     if (defined($value)) {
                   5603: 	$scan_data->{$filename.'_'.$key} = $value;
                   5604:     }
                   5605:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5606:     return $scan_data->{$filename.'_'.$key};
                   5607: }
1.423     albertel 5608: 
1.495     albertel 5609: # ----- These first few routines are general use routines.----
                   5610: 
                   5611: # Return the number of occurences of a pattern in a string.
                   5612: 
                   5613: sub occurence_count {
                   5614:     my ($string, $pattern) = @_;
                   5615: 
                   5616:     my @matches = ($string =~ /$pattern/g);
                   5617: 
                   5618:     return scalar(@matches);
                   5619: }
                   5620: 
                   5621: 
                   5622: # Take a string known to have digits and convert all the
                   5623: # digits into letters in the range J,A..I.
                   5624: 
                   5625: sub digits_to_letters {
                   5626:     my ($input) = @_;
                   5627: 
                   5628:     my @alphabet = ('J', 'A'..'I');
                   5629: 
                   5630:     my @input    = split(//, $input);
                   5631:     my $output ='';
                   5632:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5633: 	if ($input[$i] =~ /\d/) {
                   5634: 	    $output .= $alphabet[$input[$i]];
                   5635: 	} else {
                   5636: 	    $output .= $input[$i];
                   5637: 	}
                   5638:     }
                   5639:     return $output;
                   5640: }
                   5641: 
1.423     albertel 5642: =pod 
                   5643: 
                   5644: =item scantron_parse_scanline
                   5645: 
                   5646:   Decodes a scanline from the selected scantron file
                   5647: 
                   5648:  Arguments:
                   5649:     line             - The text of the scantron file line to process
                   5650:     whichline        - Line number
                   5651:     scantron_config  - Hash describing the format of the scantron lines.
                   5652:     scan_data        - Hash of extra information about the scanline
                   5653:                        (see scantron_getfile for more information)
                   5654:     just_header      - True if should not process question answers but only
                   5655:                        the stuff to the left of the answers.
                   5656:  Returns:
                   5657:    Hash containing the result of parsing the scanline
                   5658: 
                   5659:    Keys are all proceeded by the string 'scantron.'
                   5660: 
                   5661:        CODE    - the CODE in use for this scanline
                   5662:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5663:                  by the operator
                   5664:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5665:                             CODEs were selected, but the usage has been
                   5666:                             forced by the operator
1.556     weissno  5667:        ID  - student/employee ID
1.423     albertel 5668:        PaperID - if used, the ID number printed on the sheet when the 
                   5669:                  paper was scanned
                   5670:        FirstName - first name from the sheet
                   5671:        LastName  - last name from the sheet
                   5672: 
                   5673:      if just_header was not true these key may also exist
                   5674: 
1.447     foxr     5675:        missingerror - a list of bubble ranges that are considered to be answers
                   5676:                       to a single question that don't have any bubbles filled in.
                   5677:                       Of the form questionnumber:firstbubblenumber:count.
                   5678:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5679:                       to a single question that have more than one bubble filled in.
                   5680:                       Of the form questionnumber::firstbubblenumber:count
                   5681:    
                   5682:                 In the above, count is the number of bubble responses in the
                   5683:                 input line needed to represent the possible answers to the question.
                   5684:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5685:                 per line would have count = 2.
                   5686: 
1.423     albertel 5687:        maxquest     - the number of the last bubble line that was parsed
                   5688: 
                   5689:        (<number> starts at 1)
                   5690:        <number>.answer - zero or more letters representing the selected
                   5691:                          letters from the scanline for the bubble line 
                   5692:                          <number>.
                   5693:                          if blank there was either no bubble or there where
                   5694:                          multiple bubbles, (consult the keys missingerror and
                   5695:                          doubleerror if this is an error condition)
                   5696: 
                   5697: =cut
                   5698: 
1.82      albertel 5699: sub scantron_parse_scanline {
1.423     albertel 5700:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5701: 
1.82      albertel 5702:     my %record;
1.550     raeburn  5703:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5704:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5705:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5706:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5707: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5708: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5709: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5710: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5711: 	    $record{'scantron.CODE'}=substr($data,
                   5712: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5713: 					    $$scantron_config{'CODElength'});
1.191     albertel 5714: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5715: 		$record{'scantron.useCODE'}=1;
                   5716: 	    }
1.192     albertel 5717: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5718: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5719: 	    }
1.82      albertel 5720: 	} else {
                   5721: 	    #FIXME interpret first N questions
                   5722: 	}
                   5723:     }
1.83      albertel 5724:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5725: 				  $$scantron_config{'IDlength'});
1.157     albertel 5726:     $record{'scantron.PaperID'}=
                   5727: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5728: 	       $$scantron_config{'PaperIDlength'});
                   5729:     $record{'scantron.FirstName'}=
                   5730: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5731: 	       $$scantron_config{'FirstNamelength'});
                   5732:     $record{'scantron.LastName'}=
                   5733: 	substr($data,$$scantron_config{'LastName'}-1,
                   5734: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5735:     if ($just_header) { return \%record; }
1.194     albertel 5736: 
1.82      albertel 5737:     my @alphabet=('A'..'Z');
                   5738:     my $questnum=0;
1.447     foxr     5739:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5740: 
1.470     foxr     5741:     chomp($questions);		# Get rid of any trailing \n.
                   5742:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5743:     while (length($questions)) {
1.447     foxr     5744: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5745:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5746:                              || 1;
                   5747:         $questnum++;
                   5748:         my $quest_id = $questnum;
                   5749:         my $currentquest = substr($questions,0,$answer_length);
                   5750:         $questions       = substr($questions,$answer_length);
                   5751:         if (length($currentquest) < $answer_length) { next; }
                   5752: 
                   5753:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5754:             my $subquestnum = 1;
                   5755:             my $subquestions = $currentquest;
                   5756:             my @subanswers_needed = 
                   5757:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5758:             foreach my $subans (@subanswers_needed) {
                   5759:                 my $subans_length =
                   5760:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5761:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5762:                 $subquestions   = substr($subquestions,$subans_length);
                   5763:                 $quest_id = "$questnum.$subquestnum";
                   5764:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5765:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5766:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5767:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5768:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5769:                 } else {
                   5770:                     $ansnum = &scantron_validator_positional($ansnum,
                   5771:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5772:                 }
                   5773:                 $subquestnum ++;
                   5774:             }
                   5775:         } else {
                   5776:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5777:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5778:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5779:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5780:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5781:             } else {
                   5782:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5783:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5784:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5785:             }
                   5786:         }
                   5787:     }
                   5788:     $record{'scantron.maxquest'}=$questnum;
                   5789:     return \%record;
                   5790: }
1.447     foxr     5791: 
1.503     raeburn  5792: sub scantron_validator_lettnum {
                   5793:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5794:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5795: 
                   5796:     # Qon 'letter' implies for each slot in currquest we have:
                   5797:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5798:     #    about anything else (esp. a value of Qoff) for missing
                   5799:     #    bubbles.
                   5800:     #
                   5801:     # Qon 'number' implies each slot gives a digit that indexes the
                   5802:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5803:     #    and * or ? for double bubbles on a single line.
                   5804:     #
1.447     foxr     5805: 
1.503     raeburn  5806:     my $matchon;
                   5807:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5808:         $matchon = '[A-Z]';
                   5809:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5810:         $matchon = '\d';
                   5811:     }
                   5812:     my $occurrences = 0;
                   5813:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5814:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5815:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5816:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5817:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5818:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5819:         my @singlelines = split('',$currquest);
                   5820:         foreach my $entry (@singlelines) {
                   5821:             $occurrences = &occurence_count($entry,$matchon);
                   5822:             if ($occurrences > 1) {
                   5823:                 last;
                   5824:             }
                   5825:         } 
                   5826:     } else {
                   5827:         $occurrences = &occurence_count($currquest,$matchon); 
                   5828:     }
                   5829:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5830:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5831:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5832:             my $bubble = substr($currquest,$ans,1);
                   5833:             if ($bubble =~ /$matchon/ ) {
                   5834:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5835:                     if ($bubble == 0) {
                   5836:                         $bubble = 10; 
                   5837:                     }
                   5838:                     $record->{"scantron.$ansnum.answer"} = 
                   5839:                         $alphabet->[$bubble-1];
                   5840:                 } else {
                   5841:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5842:                 }
                   5843:             } else {
                   5844:                 $record->{"scantron.$ansnum.answer"}='';
                   5845:             }
                   5846:             $ansnum++;
                   5847:         }
                   5848:     } elsif (!defined($currquest)
                   5849:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5850:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5851:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5852:             $record->{"scantron.$ansnum.answer"}='';
                   5853:             $ansnum++;
                   5854:         }
                   5855:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5856:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5857:         }
                   5858:     } else {
                   5859:         if ($$scantron_config{'Qon'} eq 'number') {
                   5860:             $currquest = &digits_to_letters($currquest);            
                   5861:         }
                   5862:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5863:             my $bubble = substr($currquest,$ans,1);
                   5864:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5865:             $ansnum++;
                   5866:         }
                   5867:     }
                   5868:     return $ansnum;
                   5869: }
1.447     foxr     5870: 
1.503     raeburn  5871: sub scantron_validator_positional {
                   5872:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5873:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5874: 
1.503     raeburn  5875:     # Otherwise there's a positional notation;
                   5876:     # each bubble line requires Qlength items, and there are filled in
                   5877:     # bubbles for each case where there 'Qon' characters.
                   5878:     #
1.447     foxr     5879: 
1.503     raeburn  5880:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5881: 
1.503     raeburn  5882:     # If the split only gives us one element.. the full length of the
                   5883:     # answer string, no bubbles are filled in:
1.447     foxr     5884: 
1.507     raeburn  5885:     if ($answers_needed eq '') {
                   5886:         return;
                   5887:     }
                   5888: 
1.503     raeburn  5889:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5890:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5891:             $record->{"scantron.$ansnum.answer"}='';
                   5892:             $ansnum++;
                   5893:         }
                   5894:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5895:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5896:         }
                   5897:     } elsif (scalar(@array) == 2) {
                   5898:         my $location = length($array[0]);
                   5899:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5900:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5901:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5902:             if ($ans eq $line_num) {
                   5903:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5904:             } else {
                   5905:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5906:             }
                   5907:             $ansnum++;
                   5908:          }
                   5909:     } else {
                   5910:         #  If there's more than one instance of a bubble character
                   5911:         #  That's a double bubble; with positional notation we can
                   5912:         #  record all the bubbles filled in as well as the
                   5913:         #  fact this response consists of multiple bubbles.
                   5914:         #
                   5915:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5916:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5917:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5918:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5919:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5920:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5921:             my $doubleerror = 0;
                   5922:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5923:                    (!$doubleerror)) {
                   5924:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5925:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5926:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5927:                if (length(@currarray) > 2) {
                   5928:                    $doubleerror = 1;
                   5929:                } 
                   5930:             }
                   5931:             if ($doubleerror) {
                   5932:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5933:             }
                   5934:         } else {
                   5935:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5936:         }
                   5937:         my $item = $ansnum;
                   5938:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5939:             $record->{"scantron.$item.answer"} = '';
                   5940:             $item ++;
                   5941:         }
1.447     foxr     5942: 
1.503     raeburn  5943:         my @ans=@array;
                   5944:         my $i=0;
                   5945:         my $increment = 0;
                   5946:         while ($#ans) {
                   5947:             $i+=length($ans[0]) + $increment;
                   5948:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5949:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5950:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5951:             shift(@ans);
                   5952:             $increment = 1;
                   5953:         }
                   5954:         $ansnum += $answers_needed;
1.82      albertel 5955:     }
1.503     raeburn  5956:     return $ansnum;
1.82      albertel 5957: }
                   5958: 
1.423     albertel 5959: =pod
                   5960: 
                   5961: =item scantron_add_delay
                   5962: 
                   5963:    Adds an error message that occurred during the grading phase to a
                   5964:    queue of messages to be shown after grading pass is complete
                   5965: 
                   5966:  Arguments:
1.424     albertel 5967:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5968:    $scanline    - the scanline that caused the error
                   5969:    $errormesage - the error message
                   5970:    $errorcode   - a numeric code for the error
                   5971: 
                   5972:  Side Effects:
1.424     albertel 5973:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5974: 
                   5975: =cut
                   5976: 
1.82      albertel 5977: sub scantron_add_delay {
1.140     albertel 5978:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5979:     push(@$delayqueue,
                   5980: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5981: 	  'ecode' => $errorcode }
                   5982: 	 );
1.82      albertel 5983: }
                   5984: 
1.423     albertel 5985: =pod
                   5986: 
                   5987: =item scantron_find_student
                   5988: 
1.424     albertel 5989:    Finds the username for the current scanline
                   5990: 
                   5991:   Arguments:
                   5992:    $scantron_record - hash result from scantron_parse_scanline
                   5993:    $scan_data       - hash of correction information 
                   5994:                       (see &scantron_getfile() form more information)
                   5995:    $idmap           - hash from &username_to_idmap()
                   5996:    $line            - number of current scanline
                   5997:  
                   5998:   Returns:
                   5999:    Either 'username:domain' or undef if unknown
                   6000: 
1.423     albertel 6001: =cut
                   6002: 
1.82      albertel 6003: sub scantron_find_student {
1.157     albertel 6004:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6005:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6006:     if ($scanID =~ /^\s*$/) {
                   6007:  	return &scan_data($scan_data,"$line.user");
                   6008:     }
1.83      albertel 6009:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6010:  	if (lc($id) eq lc($scanID)) {
                   6011:  	    return $$idmap{$id};
                   6012:  	}
1.83      albertel 6013:     }
                   6014:     return undef;
                   6015: }
                   6016: 
1.423     albertel 6017: =pod
                   6018: 
                   6019: =item scantron_filter
                   6020: 
1.424     albertel 6021:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6022:    hidden resources was selected
                   6023: 
1.423     albertel 6024: =cut
                   6025: 
1.83      albertel 6026: sub scantron_filter {
                   6027:     my ($curres)=@_;
1.331     albertel 6028: 
                   6029:     if (ref($curres) && $curres->is_problem()) {
                   6030: 	# if the user has asked to not have either hidden
                   6031: 	# or 'randomout' controlled resources to be graded
                   6032: 	# don't include them
                   6033: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6034: 	    && $curres->randomout) {
                   6035: 	    return 0;
                   6036: 	}
1.83      albertel 6037: 	return 1;
                   6038:     }
                   6039:     return 0;
1.82      albertel 6040: }
                   6041: 
1.423     albertel 6042: =pod
                   6043: 
                   6044: =item scantron_process_corrections
                   6045: 
1.424     albertel 6046:    Gets correction information out of submitted form data and corrects
                   6047:    the scanline
                   6048: 
1.423     albertel 6049: =cut
                   6050: 
1.157     albertel 6051: sub scantron_process_corrections {
                   6052:     my ($r) = @_;
1.257     albertel 6053:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6054:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6055:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6056:     my $which=$env{'form.scantron_line'};
1.200     albertel 6057:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6058:     my ($skip,$err,$errmsg);
1.257     albertel 6059:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6060: 	$skip=1;
1.257     albertel 6061:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6062: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6063: 	    $env{'form.scantron_domain'};
1.157     albertel 6064: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6065: 	($line,$err,$errmsg)=
                   6066: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6067: 				     'ID',{'newid'=>$newid,
1.257     albertel 6068: 				    'username'=>$env{'form.scantron_username'},
                   6069: 				    'domain'=>$env{'form.scantron_domain'}});
                   6070:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6071: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6072: 	my $newCODE;
1.192     albertel 6073: 	my %args;
1.190     albertel 6074: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6075: 	    $newCODE='use_unfound';
1.190     albertel 6076: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6077: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6078: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6079: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6080: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6081: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6082: 	}
1.257     albertel 6083: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6084: 	    $args{'CODE_ignore_dup'}=1;
                   6085: 	}
                   6086: 	$args{'CODE'}=$newCODE;
1.186     albertel 6087: 	($line,$err,$errmsg)=
                   6088: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6089: 				     'CODE',\%args);
1.257     albertel 6090:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6091: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6092: 	    ($line,$err,$errmsg)=
                   6093: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6094: 					 $which,'answer',
                   6095: 					 { 'question'=>$question,
1.503     raeburn  6096: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6097:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6098: 	    if ($err) { last; }
                   6099: 	}
                   6100:     }
                   6101:     if ($err) {
1.398     albertel 6102: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6103:     } else {
1.200     albertel 6104: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6105: 	&scantron_putfile($scanlines,$scan_data);
                   6106:     }
                   6107: }
                   6108: 
1.423     albertel 6109: =pod
                   6110: 
                   6111: =item reset_skipping_status
                   6112: 
1.424     albertel 6113:    Forgets the current set of remember skipped scanlines (and thus
                   6114:    reverts back to considering all lines in the
                   6115:    scantron_skipped_<filename> file)
                   6116: 
1.423     albertel 6117: =cut
                   6118: 
1.200     albertel 6119: sub reset_skipping_status {
                   6120:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6121:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6122:     &scantron_putfile(undef,$scan_data);
                   6123: }
                   6124: 
1.423     albertel 6125: =pod
                   6126: 
                   6127: =item start_skipping
                   6128: 
1.424     albertel 6129:    Marks a scanline to be skipped. 
                   6130: 
1.423     albertel 6131: =cut
                   6132: 
1.376     albertel 6133: sub start_skipping {
1.200     albertel 6134:     my ($scan_data,$i)=@_;
                   6135:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6136:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6137: 	$remembered{$i}=2;
                   6138:     } else {
                   6139: 	$remembered{$i}=1;
                   6140:     }
1.200     albertel 6141:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6142: }
                   6143: 
1.423     albertel 6144: =pod
                   6145: 
                   6146: =item should_be_skipped
                   6147: 
1.424     albertel 6148:    Checks whether a scanline should be skipped.
                   6149: 
1.423     albertel 6150: =cut
                   6151: 
1.200     albertel 6152: sub should_be_skipped {
1.376     albertel 6153:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6154:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6155: 	# not redoing old skips
1.376     albertel 6156: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6157: 	return 0;
                   6158:     }
                   6159:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6160: 
                   6161:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6162: 	return 0;
                   6163:     }
1.200     albertel 6164:     return 1;
                   6165: }
                   6166: 
1.423     albertel 6167: =pod
                   6168: 
                   6169: =item remember_current_skipped
                   6170: 
1.424     albertel 6171:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6172:    file and remembers them into scan_data for later use.
                   6173: 
1.423     albertel 6174: =cut
                   6175: 
1.200     albertel 6176: sub remember_current_skipped {
                   6177:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6178:     my %to_remember;
                   6179:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6180: 	if ($scanlines->{'skipped'}[$i]) {
                   6181: 	    $to_remember{$i}=1;
                   6182: 	}
                   6183:     }
1.376     albertel 6184: 
1.200     albertel 6185:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6186:     &scantron_putfile(undef,$scan_data);
                   6187: }
                   6188: 
1.423     albertel 6189: =pod
                   6190: 
                   6191: =item check_for_error
                   6192: 
1.424     albertel 6193:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6194:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6195:     something went wrong.
                   6196: 
1.423     albertel 6197: =cut
                   6198: 
1.200     albertel 6199: sub check_for_error {
                   6200:     my ($r,$result)=@_;
                   6201:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6202: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6203:     }
                   6204: }
1.157     albertel 6205: 
1.423     albertel 6206: =pod
                   6207: 
                   6208: =item scantron_warning_screen
                   6209: 
1.424     albertel 6210:    Interstitial screen to make sure the operator has selected the
                   6211:    correct options before we start the validation phase.
                   6212: 
1.423     albertel 6213: =cut
                   6214: 
1.203     albertel 6215: sub scantron_warning_screen {
1.650     raeburn  6216:     my ($button_text,$symb)=@_;
1.257     albertel 6217:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6218:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6219:     my $CODElist;
1.284     albertel 6220:     if ($scantron_config{'CODElocation'} &&
                   6221: 	$scantron_config{'CODEstart'} &&
                   6222: 	$scantron_config{'CODElength'}) {
                   6223: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6224: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6225: 	$CODElist=
1.492     albertel 6226: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6227: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6228:     }
1.492     albertel 6229:     return ('
1.203     albertel 6230: <p>
1.492     albertel 6231: <span class="LC_warning">
                   6232: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6233: </p>
                   6234: <table>
1.492     albertel 6235: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6236: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6237: '.$CODElist.'
1.203     albertel 6238: </table>
1.650     raeburn  6239: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6240: '.&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 6241: 
                   6242: <br />
1.492     albertel 6243: ');
1.203     albertel 6244: }
                   6245: 
1.423     albertel 6246: =pod
                   6247: 
                   6248: =item scantron_do_warning
                   6249: 
1.424     albertel 6250:    Check if the operator has picked something for all required
                   6251:    fields. Error out if something is missing.
                   6252: 
1.423     albertel 6253: =cut
                   6254: 
1.203     albertel 6255: sub scantron_do_warning {
1.608     www      6256:     my ($r,$symb)=@_;
1.203     albertel 6257:     if (!$symb) {return '';}
1.324     albertel 6258:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6259:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6260:     if ( $env{'form.selectpage'} eq '' ||
                   6261: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6262: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6263: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6264: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6265: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6266: 	} 
1.257     albertel 6267: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6268: 	    $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 6269: 	} 
1.257     albertel 6270: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6271: 	    $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 6272: 	} 
                   6273:     } else {
1.650     raeburn  6274: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.492     albertel 6275: 	$r->print('
                   6276: '.$warning.'
                   6277: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6278: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6279: ');
1.237     albertel 6280:     }
1.614     www      6281:     $r->print("</form><br />");
1.203     albertel 6282:     return '';
                   6283: }
                   6284: 
1.423     albertel 6285: =pod
                   6286: 
                   6287: =item scantron_form_start
                   6288: 
1.424     albertel 6289:     html hidden input for remembering all selected grading options
                   6290: 
1.423     albertel 6291: =cut
                   6292: 
1.203     albertel 6293: sub scantron_form_start {
                   6294:     my ($max_bubble)=@_;
                   6295:     my $result= <<SCANTRONFORM;
                   6296: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6297:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6298:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6299:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6300:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6301:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6302:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6303:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6304:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6305:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6306: SCANTRONFORM
1.447     foxr     6307: 
                   6308:   my $line = 0;
                   6309:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6310:        my $chunk =
                   6311: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6312:        $chunk .=
                   6313: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6314:        $chunk .= 
                   6315:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6316:        $chunk .=
                   6317:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6318:        $result .= $chunk;
                   6319:        $line++;
                   6320:    }
1.203     albertel 6321:     return $result;
                   6322: }
                   6323: 
1.423     albertel 6324: =pod
                   6325: 
                   6326: =item scantron_validate_file
                   6327: 
1.659     raeburn  6328:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6329: 
                   6330:     Also processes any necessary information resets that need to
                   6331:     occur before validation begins (ignore previous corrections,
                   6332:     restarting the skipped records processing)
                   6333: 
1.423     albertel 6334: =cut
                   6335: 
1.157     albertel 6336: sub scantron_validate_file {
1.608     www      6337:     my ($r,$symb) = @_;
1.157     albertel 6338:     if (!$symb) {return '';}
1.324     albertel 6339:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6340:     
                   6341:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6342:     # them when doing the corrections reset
1.257     albertel 6343:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6344: 	&reset_skipping_status();
                   6345:     }
1.257     albertel 6346:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6347: 	&remember_current_skipped();
1.257     albertel 6348: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6349:     }
                   6350: 
1.257     albertel 6351:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6352: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6353: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6354: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6355: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6356:     }
1.200     albertel 6357: 
1.257     albertel 6358:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6359: 	&scantron_process_corrections($r);
                   6360:     }
1.503     raeburn  6361:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6362:     #get the student pick code ready
                   6363:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6364:     my $nav_error;
1.649     raeburn  6365:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6366:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6367:     if ($nav_error) {
                   6368:         $r->print(&navmap_errormsg());
                   6369:         return '';
                   6370:     }
1.203     albertel 6371:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6372:     $r->print($result);
                   6373:     
1.334     albertel 6374:     my @validate_phases=( 'sequence',
                   6375: 			  'ID',
1.157     albertel 6376: 			  'CODE',
                   6377: 			  'doublebubble',
                   6378: 			  'missingbubbles');
1.257     albertel 6379:     if (!$env{'form.validatepass'}) {
                   6380: 	$env{'form.validatepass'} = 0;
1.157     albertel 6381:     }
1.257     albertel 6382:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6383: 
1.448     foxr     6384: 
1.157     albertel 6385:     my $stop=0;
                   6386:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6387: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6388: 	$r->rflush();
                   6389: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6390: 	{
                   6391: 	    no strict 'refs';
                   6392: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6393: 	}
                   6394:     }
                   6395:     if (!$stop) {
1.650     raeburn  6396: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6397: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6398:                   $warning.
                   6399:                   &mt('Perform verification for each student after storage of submissions?').
                   6400:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6401:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6402:                   ('&nbsp;'x3).'<label>'.
                   6403:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6404:                   '</label></span><br />'.
                   6405:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6406:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6407:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6408:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6409:     } else {
                   6410: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6411: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6412:     }
                   6413:     if ($stop) {
1.334     albertel 6414: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6415: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6416: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6417: 
1.650     raeburn  6418: 	    $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 6419: 	} else {
1.503     raeburn  6420:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6421: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6422:             } else {
1.539     riegler  6423:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6424:             }
1.492     albertel 6425: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6426: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6427: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6428: 	}
1.157     albertel 6429:     }
1.614     www      6430:     $r->print(" </form><br />");
1.157     albertel 6431:     return '';
                   6432: }
                   6433: 
1.423     albertel 6434: 
                   6435: =pod
                   6436: 
                   6437: =item scantron_remove_file
                   6438: 
1.659     raeburn  6439:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6440:    scantron_original_<filename> is never removed
                   6441: 
                   6442: 
1.423     albertel 6443: =cut
                   6444: 
1.200     albertel 6445: sub scantron_remove_file {
1.192     albertel 6446:     my ($which)=@_;
1.257     albertel 6447:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6448:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6449:     my $file='scantron_';
1.200     albertel 6450:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6451: 	$file.=$which.'_';
1.192     albertel 6452:     } else {
                   6453: 	return 'refused';
                   6454:     }
1.257     albertel 6455:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6456:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6457: }
                   6458: 
1.423     albertel 6459: 
                   6460: =pod
                   6461: 
                   6462: =item scantron_remove_scan_data
                   6463: 
1.659     raeburn  6464:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6465:    data file.  (In the case that both the are doing skipped records we need
                   6466:    to remember the old skipped lines for the time being so that element
                   6467:    persists for a while.)
                   6468: 
1.423     albertel 6469: =cut
                   6470: 
1.200     albertel 6471: sub scantron_remove_scan_data {
1.257     albertel 6472:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6473:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6474:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6475:     my @todelete;
1.257     albertel 6476:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6477:     foreach my $key (@keys) {
                   6478: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6479: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6480: 		$key=~/remember_skipping/) {
                   6481: 		next;
                   6482: 	    }
1.192     albertel 6483: 	    push(@todelete,$key);
                   6484: 	}
                   6485:     }
1.200     albertel 6486:     my $result;
1.192     albertel 6487:     if (@todelete) {
1.491     albertel 6488: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6489: 				       \@todelete,$cdom,$cname);
                   6490:     } else {
                   6491: 	$result = 'ok';
1.192     albertel 6492:     }
                   6493:     return $result;
                   6494: }
                   6495: 
1.423     albertel 6496: 
                   6497: =pod
                   6498: 
                   6499: =item scantron_getfile
                   6500: 
1.659     raeburn  6501:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6502:     the scan_data hash
                   6503:   
                   6504:   Arguments:
                   6505:     None
                   6506: 
                   6507:   Returns:
                   6508:     2 hash references
                   6509: 
                   6510:      - first one has 
                   6511:          orig      -
                   6512:          corrected -
                   6513:          skipped   -  each of which points to an array ref of the specified
                   6514:                       file broken up into individual lines
                   6515:          count     - number of scanlines
                   6516:  
                   6517:      - second is the scan_data hash possible keys are
1.425     albertel 6518:        ($number refers to scanline numbered $number and thus the key affects
                   6519:         only that scanline
                   6520:         $bubline refers to the specific bubble line element and the aspects
                   6521:         refers to that specific bubble line element)
                   6522: 
                   6523:        $number.user - username:domain to use
                   6524:        $number.CODE_ignore_dup 
                   6525:                     - ignore the duplicate CODE error 
                   6526:        $number.useCODE
                   6527:                     - use the CODE in the scanline as is
                   6528:        $number.no_bubble.$bubline
                   6529:                     - it is valid that there is no bubbled in bubble
                   6530:                       at $number $bubline
                   6531:        remember_skipping
                   6532:                     - a frozen hash containing keys of $number and values
                   6533:                       of either 
                   6534:                         1 - we are on a 'do skipped records pass' and plan
                   6535:                             on processing this line
                   6536:                         2 - we are on a 'do skipped records pass' and this
                   6537:                             scanline has been marked to skip yet again
1.424     albertel 6538: 
1.423     albertel 6539: =cut
                   6540: 
1.157     albertel 6541: sub scantron_getfile {
1.200     albertel 6542:     #FIXME really would prefer a scantron directory
1.257     albertel 6543:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6544:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6545:     my $lines;
                   6546:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6547: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6548:     my %scanlines;
                   6549:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6550:     my $temp=$scanlines{'orig'};
                   6551:     $scanlines{'count'}=$#$temp;
                   6552: 
                   6553:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6554: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6555:     if ($lines eq '-1') {
                   6556: 	$scanlines{'corrected'}=[];
                   6557:     } else {
                   6558: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6559:     }
                   6560:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6561: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6562:     if ($lines eq '-1') {
                   6563: 	$scanlines{'skipped'}=[];
                   6564:     } else {
                   6565: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6566:     }
1.175     albertel 6567:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6568:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6569:     my %scan_data = @tmp;
                   6570:     return (\%scanlines,\%scan_data);
                   6571: }
                   6572: 
1.423     albertel 6573: =pod
                   6574: 
                   6575: =item lonnet_putfile
                   6576: 
1.424     albertel 6577:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6578: 
                   6579:  Arguments:
                   6580:    $contents - data to store
                   6581:    $filename - filename to store $contents into
                   6582: 
                   6583:  Returns:
                   6584:    result value from &Apache::lonnet::finishuserfileupload
                   6585: 
1.423     albertel 6586: =cut
                   6587: 
1.157     albertel 6588: sub lonnet_putfile {
                   6589:     my ($contents,$filename)=@_;
1.257     albertel 6590:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6591:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6592:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6593:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6594: 
                   6595: }
                   6596: 
1.423     albertel 6597: =pod
                   6598: 
                   6599: =item scantron_putfile
                   6600: 
1.659     raeburn  6601:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6602:     scan_data hash. (Does not modify the original version only the
                   6603:     corrected and skipped versions.
                   6604: 
                   6605:  Arguments:
                   6606:     $scanlines - hash ref that looks like the first return value from
                   6607:                  &scantron_getfile()
                   6608:     $scan_data - hash ref that looks like the second return value from
                   6609:                  &scantron_getfile()
                   6610: 
1.423     albertel 6611: =cut
                   6612: 
1.157     albertel 6613: sub scantron_putfile {
                   6614:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6615:     #FIXME really would prefer a scantron directory
1.257     albertel 6616:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6617:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6618:     if ($scanlines) {
                   6619: 	my $prefix='scantron_';
1.157     albertel 6620: # no need to update orig, shouldn't change
                   6621: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6622: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6623: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6624: 			$prefix.'corrected_'.
1.257     albertel 6625: 			$env{'form.scantron_selectfile'});
1.200     albertel 6626: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6627: 			$prefix.'skipped_'.
1.257     albertel 6628: 			$env{'form.scantron_selectfile'});
1.200     albertel 6629:     }
1.175     albertel 6630:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6631: }
                   6632: 
1.423     albertel 6633: =pod
                   6634: 
                   6635: =item scantron_get_line
                   6636: 
1.424     albertel 6637:    Returns the correct version of the scanline
                   6638: 
                   6639:  Arguments:
                   6640:     $scanlines - hash ref that looks like the first return value from
                   6641:                  &scantron_getfile()
                   6642:     $scan_data - hash ref that looks like the second return value from
                   6643:                  &scantron_getfile()
                   6644:     $i         - number of the requested line (starts at 0)
                   6645: 
                   6646:  Returns:
                   6647:    A scanline, (either the original or the corrected one if it
                   6648:    exists), or undef if the requested scanline should be
                   6649:    skipped. (Either because it's an skipped scanline, or it's an
                   6650:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6651:    pass.
                   6652: 
1.423     albertel 6653: =cut
                   6654: 
1.157     albertel 6655: sub scantron_get_line {
1.200     albertel 6656:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6657:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6658:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6659:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6660:     return $scanlines->{'orig'}[$i]; 
                   6661: }
                   6662: 
1.423     albertel 6663: =pod
                   6664: 
                   6665: =item scantron_todo_count
                   6666: 
1.424     albertel 6667:     Counts the number of scanlines that need processing.
                   6668: 
                   6669:  Arguments:
                   6670:     $scanlines - hash ref that looks like the first return value from
                   6671:                  &scantron_getfile()
                   6672:     $scan_data - hash ref that looks like the second return value from
                   6673:                  &scantron_getfile()
                   6674: 
                   6675:  Returns:
                   6676:     $count - number of scanlines to process
                   6677: 
1.423     albertel 6678: =cut
                   6679: 
1.200     albertel 6680: sub get_todo_count {
                   6681:     my ($scanlines,$scan_data)=@_;
                   6682:     my $count=0;
                   6683:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6684: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6685: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6686: 	$count++;
                   6687:     }
                   6688:     return $count;
                   6689: }
                   6690: 
1.423     albertel 6691: =pod
                   6692: 
                   6693: =item scantron_put_line
                   6694: 
1.659     raeburn  6695:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 6696:     data file.
                   6697: 
                   6698:  Arguments:
                   6699:     $scanlines - hash ref that looks like the first return value from
                   6700:                  &scantron_getfile()
                   6701:     $scan_data - hash ref that looks like the second return value from
                   6702:                  &scantron_getfile()
                   6703:     $i         - line number to update
                   6704:     $newline   - contents of the updated scanline
                   6705:     $skip      - if true make the line for skipping and update the
                   6706:                  'skipped' file
                   6707: 
1.423     albertel 6708: =cut
                   6709: 
1.157     albertel 6710: sub scantron_put_line {
1.200     albertel 6711:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6712:     if ($skip) {
                   6713: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6714: 	&start_skipping($scan_data,$i);
1.157     albertel 6715: 	return;
                   6716:     }
                   6717:     $scanlines->{'corrected'}[$i]=$newline;
                   6718: }
                   6719: 
1.423     albertel 6720: =pod
                   6721: 
                   6722: =item scantron_clear_skip
                   6723: 
1.424     albertel 6724:    Remove a line from the 'skipped' file
                   6725: 
                   6726:  Arguments:
                   6727:     $scanlines - hash ref that looks like the first return value from
                   6728:                  &scantron_getfile()
                   6729:     $scan_data - hash ref that looks like the second return value from
                   6730:                  &scantron_getfile()
                   6731:     $i         - line number to update
                   6732: 
1.423     albertel 6733: =cut
                   6734: 
1.376     albertel 6735: sub scantron_clear_skip {
                   6736:     my ($scanlines,$scan_data,$i)=@_;
                   6737:     if (exists($scanlines->{'skipped'}[$i])) {
                   6738: 	undef($scanlines->{'skipped'}[$i]);
                   6739: 	return 1;
                   6740:     }
                   6741:     return 0;
                   6742: }
                   6743: 
1.423     albertel 6744: =pod
                   6745: 
                   6746: =item scantron_filter_not_exam
                   6747: 
1.424     albertel 6748:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6749:    filter out resources that are not marked as 'exam' mode
                   6750: 
1.423     albertel 6751: =cut
                   6752: 
1.334     albertel 6753: sub scantron_filter_not_exam {
                   6754:     my ($curres)=@_;
                   6755:     
                   6756:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6757: 	# if the user has asked to not have either hidden
                   6758: 	# or 'randomout' controlled resources to be graded
                   6759: 	# don't include them
                   6760: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6761: 	    && $curres->randomout) {
                   6762: 	    return 0;
                   6763: 	}
                   6764: 	return 1;
                   6765:     }
                   6766:     return 0;
                   6767: }
                   6768: 
1.423     albertel 6769: =pod
                   6770: 
                   6771: =item scantron_validate_sequence
                   6772: 
1.424     albertel 6773:     Validates the selected sequence, checking for resource that are
                   6774:     not set to exam mode.
                   6775: 
1.423     albertel 6776: =cut
                   6777: 
1.334     albertel 6778: sub scantron_validate_sequence {
                   6779:     my ($r,$currentphase) = @_;
                   6780: 
                   6781:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6782:     unless (ref($navmap)) {
                   6783:         $r->print(&navmap_errormsg());
                   6784:         return (1,$currentphase);
                   6785:     }
1.334     albertel 6786:     my (undef,undef,$sequence)=
                   6787: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6788: 
                   6789:     my $map=$navmap->getResourceByUrl($sequence);
                   6790: 
                   6791:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6792:                                     value="ignore" />');
                   6793:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6794: 	my @resources=
                   6795: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6796: 	if (@resources) {
1.357     banghart 6797: 	    $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 6798: 	    return (1,$currentphase);
                   6799: 	}
                   6800:     }
                   6801: 
                   6802:     return (0,$currentphase+1);
                   6803: }
                   6804: 
1.423     albertel 6805: 
                   6806: 
1.157     albertel 6807: sub scantron_validate_ID {
                   6808:     my ($r,$currentphase) = @_;
                   6809:     
                   6810:     #get student info
                   6811:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6812:     my %idmap=&username_to_idmap($classlist);
                   6813: 
                   6814:     #get scantron line setup
1.257     albertel 6815:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6816:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6817: 
                   6818:     my $nav_error;
1.649     raeburn  6819:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6820:     if ($nav_error) {
                   6821:         $r->print(&navmap_errormsg());
                   6822:         return(1,$currentphase);
                   6823:     }
1.157     albertel 6824: 
                   6825:     my %found=('ids'=>{},'usernames'=>{});
                   6826:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6827: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6828: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6829: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6830: 						 $scan_data);
                   6831: 	my $id=$$scan_record{'scantron.ID'};
                   6832: 	my $found;
                   6833: 	foreach my $checkid (keys(%idmap)) {
                   6834: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6835: 	}
                   6836: 	if ($found) {
                   6837: 	    my $username=$idmap{$found};
                   6838: 	    if ($found{'ids'}{$found}) {
                   6839: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6840: 					 $line,'duplicateID',$found);
1.194     albertel 6841: 		return(1,$currentphase);
1.157     albertel 6842: 	    } elsif ($found{'usernames'}{$username}) {
                   6843: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6844: 					 $line,'duplicateID',$username);
1.194     albertel 6845: 		return(1,$currentphase);
1.157     albertel 6846: 	    }
1.186     albertel 6847: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6848: 	    $found{'ids'}{$found}++;
                   6849: 	    $found{'usernames'}{$username}++;
                   6850: 	} else {
                   6851: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6852: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6853: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6854: 		    &scantron_get_correction($r,$i,$scan_record,
                   6855: 					     \%scantron_config,
                   6856: 					     $line,'duplicateID',$username);
1.194     albertel 6857: 		    return(1,$currentphase);
1.157     albertel 6858: 		} elsif (!defined($username)) {
                   6859: 		    &scantron_get_correction($r,$i,$scan_record,
                   6860: 					     \%scantron_config,
                   6861: 					     $line,'incorrectID');
1.194     albertel 6862: 		    return(1,$currentphase);
1.157     albertel 6863: 		}
                   6864: 		$found{'usernames'}{$username}++;
                   6865: 	    } else {
                   6866: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6867: 					 $line,'incorrectID');
1.194     albertel 6868: 		return(1,$currentphase);
1.157     albertel 6869: 	    }
                   6870: 	}
                   6871:     }
                   6872: 
                   6873:     return (0,$currentphase+1);
                   6874: }
                   6875: 
1.423     albertel 6876: 
1.157     albertel 6877: sub scantron_get_correction {
                   6878:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6879: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6880: #to show both the current line and the previous one and allow skipping
                   6881: #the previous one or the current one
                   6882: 
1.333     albertel 6883:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   6884:         $r->print(
                   6885:             '<p class="LC_warning">'
                   6886:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   6887:                 "<b>$error</b>",
                   6888:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   6889:            ."</p> \n");
1.157     albertel 6890:     } else {
1.658     bisitz   6891:         $r->print(
                   6892:             '<p class="LC_warning">'
                   6893:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   6894:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   6895:            ."</p> \n");
                   6896:     }
                   6897:     my $message =
                   6898:         '<p>'
                   6899:        .&mt('The ID on the form is [_1]',
                   6900:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   6901:        .'<br />'
                   6902:        .&mt('The name on the paper is [_2], [_3]',
                   6903:             $$scan_record{'scantron.LastName'},
                   6904:             $$scan_record{'scantron.FirstName'})
                   6905:        .'</p>';
1.242     albertel 6906: 
1.157     albertel 6907:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6908:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6909:                            # Array populated for doublebubble or
                   6910:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6911:                            # to validate radio button checking   
                   6912: 
1.157     albertel 6913:     if ($error =~ /ID$/) {
1.186     albertel 6914: 	if ($error eq 'incorrectID') {
1.658     bisitz   6915:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 6916: 		      "</p>\n");
1.157     albertel 6917: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   6918:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6919: 	}
1.242     albertel 6920: 	$r->print($message);
1.492     albertel 6921: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6922: 	$r->print("\n<ul><li> ");
                   6923: 	#FIXME it would be nice if this sent back the user ID and
                   6924: 	#could do partial userID matches
                   6925: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6926: 				       'scantron_username','scantron_domain'));
                   6927: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6928: 	$r->print("\n@".
1.257     albertel 6929: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6930: 
                   6931: 	$r->print('</li>');
1.186     albertel 6932:     } elsif ($error =~ /CODE$/) {
                   6933: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   6934: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6935: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   6936: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6937: 	}
1.658     bisitz   6938: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   6939: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   6940:                  ."</p>\n");
1.242     albertel 6941: 	$r->print($message);
1.658     bisitz   6942: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 6943: 	$r->print("\n<br /> ");
1.194     albertel 6944: 	my $i=0;
1.273     albertel 6945: 	if ($error eq 'incorrectCODE' 
                   6946: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6947: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6948: 	    if ($closest > 0) {
                   6949: 		foreach my $testcode (@{$closest}) {
                   6950: 		    my $checked='';
1.569     bisitz   6951: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6952: 		    $r->print("
                   6953:    <label>
1.569     bisitz   6954:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6955:        ".&mt("Use the similar CODE [_1] instead.",
                   6956: 	    "<b><tt>".$testcode."</tt></b>")."
                   6957:     </label>
                   6958:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6959: 		    $r->print("\n<br />");
                   6960: 		    $i++;
                   6961: 		}
1.194     albertel 6962: 	    }
                   6963: 	}
1.273     albertel 6964: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6965: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6966: 	    $r->print("
                   6967:     <label>
1.569     bisitz   6968:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  6969:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 6970: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6971:     </label>");
1.273     albertel 6972: 	    $r->print("\n<br />");
                   6973: 	}
1.194     albertel 6974: 
1.597     wenzelju 6975: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6976: function change_radio(field) {
1.190     albertel 6977:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6978:     var i;
                   6979:     for (i=0;i<slct.length;i++) {
                   6980:         if (slct[i].value==field) { slct[i].checked=true; }
                   6981:     }
                   6982: }
                   6983: ENDSCRIPT
1.187     albertel 6984: 	my $href="/adm/pickcode?".
1.359     www      6985: 	   "form=".&escape("scantronupload").
                   6986: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6987: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6988: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6989: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6990: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6991: 	    $r->print("
                   6992:     <label>
                   6993:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6994:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6995: 	     "<a target='_blank' href='$href'>","</a>")."
                   6996:     </label> 
1.558     bisitz   6997:     ".&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 6998: 	    $r->print("\n<br />");
                   6999: 	}
1.492     albertel 7000: 	$r->print("
                   7001:     <label>
                   7002:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7003:        ".&mt("Use [_1] as the CODE.",
                   7004: 	     "</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 7005: 	$r->print("\n<br /><br />");
1.157     albertel 7006:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7007: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7008: 
                   7009: 	# The form field scantron_questions is acutally a list of line numbers.
                   7010: 	# represented by this form so:
                   7011: 
                   7012: 	my $line_list = &questions_to_line_list($arg);
                   7013: 
1.157     albertel 7014: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7015: 		  $line_list.'" />');
1.242     albertel 7016: 	$r->print($message);
1.492     albertel 7017: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7018: 	foreach my $question (@{$arg}) {
1.503     raeburn  7019: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7020:                                                    $scan_record, $error);
1.524     raeburn  7021:             push(@lines_to_correct,@linenums);
1.157     albertel 7022: 	}
1.503     raeburn  7023:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7024:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7025: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
1.242     albertel 7026: 	$r->print($message);
1.492     albertel 7027: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7028: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7029: 
1.503     raeburn  7030: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7031: 	# a list of question numbers. Therefore:
                   7032: 	#
                   7033: 	
                   7034: 	my $line_list = &questions_to_line_list($arg);
                   7035: 
1.157     albertel 7036: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7037: 		  $line_list.'" />');
1.157     albertel 7038: 	foreach my $question (@{$arg}) {
1.503     raeburn  7039: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7040:                                                    $scan_record, $error);
1.524     raeburn  7041:             push(@lines_to_correct,@linenums);
1.157     albertel 7042: 	}
1.503     raeburn  7043:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7044:     } else {
                   7045: 	$r->print("\n<ul>");
                   7046:     }
                   7047:     $r->print("\n</li></ul>");
1.497     foxr     7048: }
                   7049: 
1.503     raeburn  7050: sub verify_bubbles_checked {
                   7051:     my (@ansnums) = @_;
                   7052:     my $ansnumstr = join('","',@ansnums);
                   7053:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7054:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7055: function verify_bubble_radio(form) {
                   7056:     var ansnumArray = new Array ("$ansnumstr");
                   7057:     var need_bubble_count = 0;
                   7058:     for (var i=0; i<ansnumArray.length; i++) {
                   7059:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7060:             var bubble_picked = 0; 
                   7061:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7062:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7063:                     bubble_picked = 1;
                   7064:                 }
                   7065:             }
                   7066:             if (bubble_picked == 0) {
                   7067:                 need_bubble_count ++;
                   7068:             }
                   7069:         }
                   7070:     }
                   7071:     if (need_bubble_count) {
                   7072:         alert("$warning");
                   7073:         return;
                   7074:     }
                   7075:     form.submit(); 
                   7076: }
                   7077: ENDSCRIPT
                   7078:     return $output;
                   7079: }
                   7080: 
1.497     foxr     7081: =pod
                   7082: 
                   7083: =item  questions_to_line_list
1.157     albertel 7084: 
1.497     foxr     7085: Converts a list of questions into a string of comma separated
                   7086: line numbers in the answer sheet used by the questions.  This is
                   7087: used to fill in the scantron_questions form field.
                   7088: 
                   7089:   Arguments:
                   7090:      questions    - Reference to an array of questions.
                   7091: 
                   7092: =cut
                   7093: 
                   7094: 
                   7095: sub questions_to_line_list {
                   7096:     my ($questions) = @_;
                   7097:     my @lines;
                   7098: 
1.503     raeburn  7099:     foreach my $item (@{$questions}) {
                   7100:         my $question = $item;
                   7101:         my ($first,$count,$last);
                   7102:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7103:             $question = $1;
                   7104:             my $subquestion = $2;
                   7105:             $first = $first_bubble_line{$question-1} + 1;
                   7106:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7107:             my $subcount = 1;
                   7108:             while ($subcount<$subquestion) {
                   7109:                 $first += $subans[$subcount-1];
                   7110:                 $subcount ++;
                   7111:             }
                   7112:             $count = $subans[$subquestion-1];
                   7113:         } else {
                   7114: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7115: 	    $count   = $bubble_lines_per_response{$question-1};
                   7116:         }
1.506     raeburn  7117:         $last = $first+$count-1;
1.503     raeburn  7118:         push(@lines, ($first..$last));
1.497     foxr     7119:     }
                   7120:     return join(',', @lines);
                   7121: }
                   7122: 
                   7123: =pod 
                   7124: 
                   7125: =item prompt_for_corrections
                   7126: 
                   7127: Prompts for a potentially multiline correction to the
                   7128: user's bubbling (factors out common code from scantron_get_correction
                   7129: for multi and missing bubble cases).
                   7130: 
                   7131:  Arguments:
                   7132:    $r           - Apache request object.
                   7133:    $question    - The question number to prompt for.
                   7134:    $scan_config - The scantron file configuration hash.
                   7135:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7136:    $error       - Type of error
1.497     foxr     7137: 
                   7138:  Implicit inputs:
                   7139:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7140:                                   Numbered from 0 (but question numbers are from
                   7141:                                   1.
                   7142:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7143:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7144:                                   type problems render as separate sub-questions, 
1.503     raeburn  7145:                                   in exam mode. This hash contains a 
                   7146:                                   comma-separated list of the lines per 
                   7147:                                   sub-question.
1.510     raeburn  7148:    %responsetype_per_response   - essayresponse, formularesponse,
                   7149:                                   stringresponse, imageresponse, reactionresponse,
                   7150:                                   and organicresponse type problem parts can have
1.503     raeburn  7151:                                   multiple lines per response if the weight
                   7152:                                   assigned exceeds 10.  In this case, only
                   7153:                                   one bubble per line is permitted, but more 
                   7154:                                   than one line might contain bubbles, e.g.
                   7155:                                   bubbling of: line 1 - J, line 2 - J, 
                   7156:                                   line 3 - B would assign 22 points.  
1.497     foxr     7157: 
                   7158: =cut
                   7159: 
                   7160: sub prompt_for_corrections {
1.503     raeburn  7161:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7162:     my ($current_line,$lines);
                   7163:     my @linenums;
                   7164:     my $questionnum = $question;
                   7165:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7166:         $question = $1;
                   7167:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7168:         my $subquestion = $2;
                   7169:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7170:         my $subcount = 1;
                   7171:         while ($subcount<$subquestion) {
                   7172:             $current_line += $subans[$subcount-1];
                   7173:             $subcount ++;
                   7174:         }
                   7175:         $lines = $subans[$subquestion-1];
                   7176:     } else {
                   7177:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7178:         $lines        = $bubble_lines_per_response{$question-1};
                   7179:     }
1.497     foxr     7180:     if ($lines > 1) {
1.503     raeburn  7181:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7182:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7183:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7184:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7185:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7186:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7187:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7188:             $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  7189:         } else {
                   7190:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7191:         }
1.497     foxr     7192:     }
                   7193:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7194:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7195: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7196: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7197:         push(@linenums,$current_line);
1.497     foxr     7198: 	$current_line++;
                   7199:     }
                   7200:     if ($lines > 1) {
                   7201: 	$r->print("<hr /><br />");
                   7202:     }
1.503     raeburn  7203:     return @linenums;
1.157     albertel 7204: }
1.423     albertel 7205: 
                   7206: =pod
                   7207: 
                   7208: =item scantron_bubble_selector
                   7209:   
                   7210:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7211:    possibly showing the existing the selected bubbles if known
1.423     albertel 7212: 
                   7213:  Arguments:
                   7214:     $r           - Apache request object
                   7215:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7216:     $line        - Number of the line being displayed.
1.503     raeburn  7217:     $questionnum - Question number (may include subquestion)
                   7218:     $error       - Type of error.
1.497     foxr     7219:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7220: 
                   7221: =cut
                   7222: 
1.157     albertel 7223: sub scantron_bubble_selector {
1.503     raeburn  7224:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7225:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7226: 
                   7227:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7228:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7229:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7230:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7231:             $max=$$scan_config{'BubblesPerRow'};
                   7232:             if (($scmode eq 'number') && ($max > 10)) {
                   7233:                 $max = 10;
                   7234:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7235:                 $max = 26;
                   7236:             }
                   7237:         } else {
                   7238:             $max = 10;
                   7239:         }
                   7240:     }
1.274     albertel 7241: 
1.157     albertel 7242:     my @alphabet=('A'..'Z');
1.503     raeburn  7243:     $r->print(&Apache::loncommon::start_data_table().
                   7244:               &Apache::loncommon::start_data_table_row());
                   7245:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7246:     for (my $i=0;$i<$max+1;$i++) {
                   7247: 	$r->print("\n".'<td align="center">');
                   7248: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7249: 	else { $r->print('&nbsp;'); }
                   7250: 	$r->print('</td>');
                   7251:     }
1.503     raeburn  7252:     $r->print(&Apache::loncommon::end_data_table_row().
                   7253:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7254:     for (my $i=0;$i<$max;$i++) {
                   7255: 	$r->print("\n".
                   7256: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7257: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7258:     }
1.503     raeburn  7259:     my $nobub_checked = ' ';
                   7260:     if ($error eq 'missingbubble') {
                   7261:         $nobub_checked = ' checked = "checked" ';
                   7262:     }
                   7263:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7264: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7265:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7266:               $line.'" value="'.$questionnum.'" /></td>');
                   7267:     $r->print(&Apache::loncommon::end_data_table_row().
                   7268:               &Apache::loncommon::end_data_table());
1.157     albertel 7269: }
                   7270: 
1.423     albertel 7271: =pod
                   7272: 
                   7273: =item num_matches
                   7274: 
1.424     albertel 7275:    Counts the number of characters that are the same between the two arguments.
                   7276: 
                   7277:  Arguments:
                   7278:    $orig - CODE from the scanline
                   7279:    $code - CODE to match against
                   7280: 
                   7281:  Returns:
                   7282:    $count - integer count of the number of same characters between the
                   7283:             two arguments
                   7284: 
1.423     albertel 7285: =cut
                   7286: 
1.194     albertel 7287: sub num_matches {
                   7288:     my ($orig,$code) = @_;
                   7289:     my @code=split(//,$code);
                   7290:     my @orig=split(//,$orig);
                   7291:     my $same=0;
                   7292:     for (my $i=0;$i<scalar(@code);$i++) {
                   7293: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7294:     }
                   7295:     return $same;
                   7296: }
                   7297: 
1.423     albertel 7298: =pod
                   7299: 
                   7300: =item scantron_get_closely_matching_CODEs
                   7301: 
1.424     albertel 7302:    Cycles through all CODEs and finds the set that has the greatest
                   7303:    number of same characters as the provided CODE
                   7304: 
                   7305:  Arguments:
                   7306:    $allcodes - hash ref returned by &get_codes()
                   7307:    $CODE     - CODE from the current scanline
                   7308: 
                   7309:  Returns:
                   7310:    2 element list
                   7311:     - first elements is number of how closely matching the best fit is 
                   7312:       (5 means best set has 5 matching characters)
                   7313:     - second element is an arrary ref containing the set of valid CODEs
                   7314:       that best fit the passed in CODE
                   7315: 
1.423     albertel 7316: =cut
                   7317: 
1.194     albertel 7318: sub scantron_get_closely_matching_CODEs {
                   7319:     my ($allcodes,$CODE)=@_;
                   7320:     my @CODEs;
                   7321:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7322: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7323:     }
                   7324: 
                   7325:     return ($#CODEs,$CODEs[-1]);
                   7326: }
                   7327: 
1.423     albertel 7328: =pod
                   7329: 
                   7330: =item get_codes
                   7331: 
1.424     albertel 7332:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7333:    set of remembered CODEs.
                   7334: 
                   7335:  Arguments:
                   7336:   $old_name - name of the set of remembered CODEs
                   7337:   $cdom     - domain of the course
                   7338:   $cnum     - internal course name
                   7339: 
                   7340:  Returns:
                   7341:   %allcodes - keys are the valid CODEs, values are all 1
                   7342: 
1.423     albertel 7343: =cut
                   7344: 
1.194     albertel 7345: sub get_codes {
1.280     foxr     7346:     my ($old_name, $cdom, $cnum) = @_;
                   7347:     if (!$old_name) {
                   7348: 	$old_name=$env{'form.scantron_CODElist'};
                   7349:     }
                   7350:     if (!$cdom) {
                   7351: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7352:     }
                   7353:     if (!$cnum) {
                   7354: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7355:     }
1.278     albertel 7356:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7357: 				    $cdom,$cnum);
                   7358:     my %allcodes;
                   7359:     if ($result{"type\0$old_name"} eq 'number') {
                   7360: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7361:     } else {
                   7362: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7363:     }
1.194     albertel 7364:     return %allcodes;
                   7365: }
                   7366: 
1.423     albertel 7367: =pod
                   7368: 
                   7369: =item scantron_validate_CODE
                   7370: 
1.424     albertel 7371:    Validates all scanlines in the selected file to not have any
                   7372:    invalid or underspecified CODEs and that none of the codes are
                   7373:    duplicated if this was requested.
                   7374: 
1.423     albertel 7375: =cut
                   7376: 
1.157     albertel 7377: sub scantron_validate_CODE {
                   7378:     my ($r,$currentphase) = @_;
1.257     albertel 7379:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7380:     if ($scantron_config{'CODElocation'} &&
                   7381: 	$scantron_config{'CODEstart'} &&
                   7382: 	$scantron_config{'CODElength'}) {
1.257     albertel 7383: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7384: 	    &FIXME_blow_up()
                   7385: 	}
                   7386:     } else {
                   7387: 	return (0,$currentphase+1);
                   7388:     }
                   7389:     
                   7390:     my %usedCODEs;
                   7391: 
1.194     albertel 7392:     my %allcodes=&get_codes();
1.186     albertel 7393: 
1.582     raeburn  7394:     my $nav_error;
1.649     raeburn  7395:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7396:     if ($nav_error) {
                   7397:         $r->print(&navmap_errormsg());
                   7398:         return(1,$currentphase);
                   7399:     }
1.447     foxr     7400: 
1.186     albertel 7401:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7402:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7403: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7404: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7405: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7406: 						 $scan_data);
                   7407: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7408: 	my $error=0;
1.224     albertel 7409: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7410: 	    &scantron_get_correction($r,$i,$scan_record,
                   7411: 				     \%scantron_config,
                   7412: 				     $line,'incorrectCODE',\%allcodes);
                   7413: 	    return(1,$currentphase);
                   7414: 	}
1.221     albertel 7415: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7416: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7417: 	    &scantron_get_correction($r,$i,$scan_record,
                   7418: 				     \%scantron_config,
1.194     albertel 7419: 				     $line,'incorrectCODE',\%allcodes);
                   7420: 	    return(1,$currentphase);
1.186     albertel 7421: 	}
1.214     albertel 7422: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7423: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7424: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7425: 	    &scantron_get_correction($r,$i,$scan_record,
                   7426: 				     \%scantron_config,
1.194     albertel 7427: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7428: 	    return(1,$currentphase);
1.186     albertel 7429: 	}
1.524     raeburn  7430: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7431:     }
1.157     albertel 7432:     return (0,$currentphase+1);
                   7433: }
                   7434: 
1.423     albertel 7435: =pod
                   7436: 
                   7437: =item scantron_validate_doublebubble
                   7438: 
1.424     albertel 7439:    Validates all scanlines in the selected file to not have any
                   7440:    bubble lines with multiple bubbles marked.
                   7441: 
1.423     albertel 7442: =cut
                   7443: 
1.157     albertel 7444: sub scantron_validate_doublebubble {
                   7445:     my ($r,$currentphase) = @_;
                   7446:     #get student info
                   7447:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7448:     my %idmap=&username_to_idmap($classlist);
                   7449: 
                   7450:     #get scantron line setup
1.257     albertel 7451:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7452:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7453:     my $nav_error;
1.649     raeburn  7454:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7455:     if ($nav_error) {
                   7456:         $r->print(&navmap_errormsg());
                   7457:         return(1,$currentphase);
                   7458:     }
1.447     foxr     7459: 
1.157     albertel 7460:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7461: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7462: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7463: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7464: 						 $scan_data);
                   7465: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7466: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7467: 				 'doublebubble',
                   7468: 				 $$scan_record{'scantron.doubleerror'});
                   7469:     	return (1,$currentphase);
                   7470:     }
                   7471:     return (0,$currentphase+1);
                   7472: }
                   7473: 
1.423     albertel 7474: 
1.503     raeburn  7475: sub scantron_get_maxbubble {
1.649     raeburn  7476:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7477:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7478: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7479: 	&restore_bubble_lines();
1.257     albertel 7480: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7481:     }
1.330     albertel 7482: 
1.447     foxr     7483:     my (undef, undef, $sequence) =
1.257     albertel 7484: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7485: 
1.447     foxr     7486:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7487:     unless (ref($navmap)) {
                   7488:         if (ref($nav_error)) {
                   7489:             $$nav_error = 1;
                   7490:         }
1.591     raeburn  7491:         return;
1.582     raeburn  7492:     }
1.191     albertel 7493:     my $map=$navmap->getResourceByUrl($sequence);
                   7494:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7495:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7496: 
                   7497:     &Apache::lonxml::clear_problem_counter();
                   7498: 
1.557     raeburn  7499:     my $uname       = $env{'user.name'};
                   7500:     my $udom        = $env{'user.domain'};
1.435     foxr     7501:     my $cid         = $env{'request.course.id'};
                   7502:     my $total_lines = 0;
                   7503:     %bubble_lines_per_response = ();
1.447     foxr     7504:     %first_bubble_line         = ();
1.503     raeburn  7505:     %subdivided_bubble_lines   = ();
                   7506:     %responsetype_per_response = ();
1.554     raeburn  7507: 
1.447     foxr     7508:     my $response_number = 0;
                   7509:     my $bubble_line     = 0;
1.191     albertel 7510:     foreach my $resource (@resources) {
1.649     raeburn  7511:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
1.542     raeburn  7512:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7513: 	    foreach my $part_id (@{$parts}) {
                   7514:                 my $lines;
                   7515: 
                   7516: 	        # TODO - make this a persistent hash not an array.
                   7517: 
                   7518:                 # optionresponse, matchresponse and rankresponse type items 
                   7519:                 # render as separate sub-questions in exam mode.
                   7520:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7521:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7522:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7523:                     my ($numbub,$numshown);
                   7524:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7525:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7526:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7527:                         }
                   7528:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7529:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7530:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7531:                         }
                   7532:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7533:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7534:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7535:                         }
                   7536:                     }
                   7537:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7538:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7539:                     }
1.649     raeburn  7540:                     my $bubbles_per_row =
                   7541:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7542:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7543:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7544:                         $inner_bubble_lines++;
                   7545:                     }
                   7546:                     for (my $i=0; $i<$numshown; $i++) {
                   7547:                         $subdivided_bubble_lines{$response_number} .= 
                   7548:                             $inner_bubble_lines.',';
                   7549:                     }
                   7550:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7551:                     $lines = $numshown * $inner_bubble_lines;
                   7552:                 } else {
                   7553:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7554:                 }
1.542     raeburn  7555: 
                   7556:                 $first_bubble_line{$response_number} = $bubble_line;
                   7557: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7558:                 $responsetype_per_response{$response_number} = 
                   7559:                     $analysis->{$part_id.'.type'};
                   7560: 	        $response_number++;
                   7561: 
                   7562: 	        $bubble_line +=  $lines;
                   7563: 	        $total_lines +=  $lines;
                   7564: 	    }
                   7565:         }
                   7566:     }
1.552     raeburn  7567:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7568: 
                   7569:     &save_bubble_lines();
                   7570:     $env{'form.scantron_maxbubble'} =
                   7571: 	$total_lines;
                   7572:     return $env{'form.scantron_maxbubble'};
                   7573: }
1.523     raeburn  7574: 
1.649     raeburn  7575: sub bubblesheet_bubbles_per_row {
                   7576:     my ($scantron_config) = @_;
                   7577:     my $bubbles_per_row;
                   7578:     if (ref($scantron_config) eq 'HASH') {
                   7579:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7580:     }
                   7581:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7582:         $bubbles_per_row = 10;
                   7583:     }
                   7584:     return $bubbles_per_row;
                   7585: }
                   7586: 
1.157     albertel 7587: sub scantron_validate_missingbubbles {
                   7588:     my ($r,$currentphase) = @_;
                   7589:     #get student info
                   7590:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7591:     my %idmap=&username_to_idmap($classlist);
                   7592: 
                   7593:     #get scantron line setup
1.257     albertel 7594:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7595:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7596:     my $nav_error;
1.649     raeburn  7597:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7598:     if ($nav_error) {
                   7599:         return(1,$currentphase);
                   7600:     }
1.157     albertel 7601:     if (!$max_bubble) { $max_bubble=2**31; }
                   7602:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7603: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7604: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7605: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7606: 						 $scan_data);
                   7607: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7608: 	my @to_correct;
1.470     foxr     7609: 	
                   7610: 	# Probably here's where the error is...
                   7611: 
1.157     albertel 7612: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7613:             my $lastbubble;
                   7614:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7615:                my $question = $1;
                   7616:                my $subquestion = $2;
                   7617:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7618:                my $first = $first_bubble_line{$question-1};
                   7619:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7620:                my $subcount = 1;
                   7621:                while ($subcount<$subquestion) {
                   7622:                    $first += $subans[$subcount-1];
                   7623:                    $subcount ++;
                   7624:                }
                   7625:                my $count = $subans[$subquestion-1];
                   7626:                $lastbubble = $first + $count;
                   7627:             } else {
                   7628:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7629:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7630:             }
                   7631:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7632: 	    push(@to_correct,$missing);
                   7633: 	}
                   7634: 	if (@to_correct) {
                   7635: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7636: 				     $line,'missingbubble',\@to_correct);
                   7637: 	    return (1,$currentphase);
                   7638: 	}
                   7639: 
                   7640:     }
                   7641:     return (0,$currentphase+1);
                   7642: }
                   7643: 
1.423     albertel 7644: 
1.82      albertel 7645: sub scantron_process_students {
1.608     www      7646:     my ($r,$symb) = @_;
1.513     foxr     7647: 
1.257     albertel 7648:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7649:     if (!$symb) {
                   7650: 	return '';
                   7651:     }
1.324     albertel 7652:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7653: 
1.257     albertel 7654:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7655:     my $bubbles_per_row =
                   7656:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7657:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7658:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7659:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7660:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7661:     unless (ref($navmap)) {
                   7662:         $r->print(&navmap_errormsg());
                   7663:         return '';
                   7664:     }  
1.83      albertel 7665:     my $map=$navmap->getResourceByUrl($sequence);
                   7666:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7667:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7668:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7669:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7670:     my $resource_error;
1.557     raeburn  7671:     foreach my $resource (@resources) {
1.586     raeburn  7672:         my $ressymb;
                   7673:         if (ref($resource)) {
                   7674:             $ressymb = $resource->symb();
                   7675:         } else {
                   7676:             $resource_error = 1;
                   7677:             last;
                   7678:         }
1.557     raeburn  7679:         my ($analysis,$parts) =
                   7680:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7681:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7682:         $grader_partids_by_symb{$ressymb} = $parts;
                   7683:         if (ref($analysis) eq 'HASH') {
                   7684:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7685:                 $grader_randomlists_by_symb{$ressymb} = 
                   7686:                     $analysis->{'parts_withrandomlist'};
                   7687:             }
                   7688:         }
                   7689:     }
1.586     raeburn  7690:     if ($resource_error) {
                   7691:         $r->print(&navmap_errormsg());
                   7692:         return '';
                   7693:     }
1.557     raeburn  7694: 
1.554     raeburn  7695:     my ($uname,$udom);
1.82      albertel 7696:     my $result= <<SCANTRONFORM;
1.81      albertel 7697: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7698:   <input type="hidden" name="command" value="scantron_configphase" />
                   7699:   $default_form_data
                   7700: SCANTRONFORM
1.82      albertel 7701:     $r->print($result);
                   7702: 
                   7703:     my @delayqueue;
1.542     raeburn  7704:     my (%completedstudents,%scandata);
1.140     albertel 7705:     
1.520     www      7706:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7707:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7708:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7709:  				    'Bubblesheet Progress',$count,
1.195     albertel 7710: 				    'inline',undef,'scantronupload');
1.140     albertel 7711:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7712: 					  'Processing first student');
1.542     raeburn  7713:     $r->print('<br />');
1.140     albertel 7714:     my $start=&Time::HiRes::time();
1.158     albertel 7715:     my $i=-1;
1.542     raeburn  7716:     my $started;
1.447     foxr     7717: 
1.582     raeburn  7718:     my $nav_error;
1.649     raeburn  7719:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7720:     if ($nav_error) {
                   7721:         $r->print(&navmap_errormsg());
                   7722:         return '';
                   7723:     }
                   7724: 
1.513     foxr     7725:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7726:     # the user and return.
                   7727: 
                   7728:     if ($ssi_error) {
                   7729: 	$r->print("</form>");
                   7730: 	&ssi_print_error($r);
1.520     www      7731:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7732: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7733:     }
1.447     foxr     7734: 
1.542     raeburn  7735:     my %lettdig = &letter_to_digits();
                   7736:     my $numletts = scalar(keys(%lettdig));
                   7737: 
1.157     albertel 7738:     while ($i<$scanlines->{'count'}) {
                   7739:  	($uname,$udom)=('','');
                   7740:  	$i++;
1.200     albertel 7741:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7742:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7743: 	if ($started) {
                   7744: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7745: 						     'last student');
                   7746: 	}
                   7747: 	$started=1;
1.157     albertel 7748:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7749:  						 $scan_data);
                   7750:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7751:  					      \%idmap,$i)) {
                   7752:   	    &scantron_add_delay(\@delayqueue,$line,
                   7753:  				'Unable to find a student that matches',1);
                   7754:  	    next;
                   7755:   	}
                   7756:  	if (exists $completedstudents{$uname}) {
                   7757:  	    &scantron_add_delay(\@delayqueue,$line,
                   7758:  				'Student '.$uname.' has multiple sheets',2);
                   7759:  	    next;
                   7760:  	}
                   7761:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7762: 
1.586     raeburn  7763:         my (%partids_by_symb,$res_error);
1.554     raeburn  7764:         foreach my $resource (@resources) {
1.586     raeburn  7765:             my $ressymb;
                   7766:             if (ref($resource)) {
                   7767:                 $ressymb = $resource->symb();
                   7768:             } else {
                   7769:                 $res_error = 1;
                   7770:                 last;
                   7771:             }
1.557     raeburn  7772:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7773:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7774:                 my ($analysis,$parts) =
1.649     raeburn  7775:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7776:                 $partids_by_symb{$ressymb} = $parts;
                   7777:             } else {
                   7778:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7779:             }
1.554     raeburn  7780:         }
                   7781: 
1.586     raeburn  7782:         if ($res_error) {
                   7783:             &scantron_add_delay(\@delayqueue,$line,
                   7784:                                 'An error occurred while grading student '.$uname,2);
                   7785:             next;
                   7786:         }
                   7787: 
1.330     albertel 7788: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7789:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7790: 
                   7791: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7792: 	    &scantron_putfile($scanlines,$scan_data);
                   7793: 	}
1.161     albertel 7794: 	
1.542     raeburn  7795:         my $scancode;
                   7796:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7797:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7798:             $scancode = $scan_record->{'scantron.CODE'};
                   7799:         } else {
                   7800:             $scancode = '';
                   7801:         }
                   7802: 
                   7803:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7804:                                    \@resources,\%partids_by_symb,
                   7805:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  7806:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7807:             $r->print("</form>");
                   7808:             &ssi_print_error($r);
                   7809:             &Apache::lonnet::remove_lock($lock);
                   7810:             return '';      # Why return ''?  Beats me.
                   7811:         }
1.513     foxr     7812: 
1.140     albertel 7813: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7814:         if ($env{'form.verifyrecord'}) {
                   7815:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7816:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7817:             chomp($studentdata);
                   7818:             $studentdata =~ s/\r$//;
                   7819:             my $studentrecord = '';
                   7820:             my $counter = -1;
                   7821:             foreach my $resource (@resources) {
1.554     raeburn  7822:                 my $ressymb = $resource->symb();
1.542     raeburn  7823:                 ($counter,my $recording) =
                   7824:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7825:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7826:                                              \%scantron_config,\%lettdig,$numletts);
                   7827:                 $studentrecord .= $recording;
                   7828:             }
                   7829:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7830:                 &Apache::lonxml::clear_problem_counter();
                   7831:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7832:                                            \@resources,\%partids_by_symb,
                   7833:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  7834:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7835:                     $r->print("</form>");
                   7836:                     &ssi_print_error($r);
                   7837:                     &Apache::lonnet::remove_lock($lock);
                   7838:                     delete($completedstudents{$uname});
                   7839:                     return '';
                   7840:                 }
1.542     raeburn  7841:                 $counter = -1;
                   7842:                 $studentrecord = '';
                   7843:                 foreach my $resource (@resources) {
1.554     raeburn  7844:                     my $ressymb = $resource->symb();
1.542     raeburn  7845:                     ($counter,my $recording) =
                   7846:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7847:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7848:                                                  \%scantron_config,\%lettdig,$numletts);
                   7849:                     $studentrecord .= $recording;
                   7850:                 }
                   7851:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   7852:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  7853:                     if ($scancode eq '') {
1.658     bisitz   7854:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  7855:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7856:                     } else {
1.658     bisitz   7857:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  7858:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7859:                     }
                   7860:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7861:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7862:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7863:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7864:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   7865:                               '<td>'.&mt('Bubblesheet').'</td>'.
                   7866:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  7867:                               &Apache::loncommon::end_data_table_row().
                   7868:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   7869:                               '<td>'.&mt('Stored submissions').'</td>'.
                   7870:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  7871:                               &Apache::loncommon::end_data_table_row().
                   7872:                               &Apache::loncommon::end_data_table().'</p>');
                   7873:                 } else {
                   7874:                     $r->print('<br /><span class="LC_warning">'.
                   7875:                              &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 />'.
                   7876:                              &mt("As a consequence, this user's submission history records two tries.").
                   7877:                                  '</span><br />');
                   7878:                 }
                   7879:             }
                   7880:         }
1.543     raeburn  7881:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7882:     } continue {
1.330     albertel 7883: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7884: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7885:     }
1.140     albertel 7886:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7887:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7888: #    my $lasttime = &Time::HiRes::time()-$start;
                   7889: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7890: 
1.200     albertel 7891:     $r->print("</form>");
1.157     albertel 7892:     return '';
1.75      albertel 7893: }
1.157     albertel 7894: 
1.557     raeburn  7895: sub graders_resources_pass {
1.649     raeburn  7896:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   7897:         $bubbles_per_row) = @_;
1.557     raeburn  7898:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7899:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7900:         foreach my $resource (@{$resources}) {
                   7901:             my $ressymb = $resource->symb();
                   7902:             my ($analysis,$parts) =
                   7903:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7904:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7905:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7906:             if (ref($analysis) eq 'HASH') {
                   7907:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7908:                     $grader_randomlists_by_symb->{$ressymb} =
                   7909:                         $analysis->{'parts_withrandomlist'};
                   7910:                 }
                   7911:             }
                   7912:         }
                   7913:     }
                   7914:     return;
                   7915: }
                   7916: 
1.542     raeburn  7917: sub grade_student_bubbles {
1.649     raeburn  7918:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   7919: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  7920:     if (ref($resources) eq 'ARRAY') {
                   7921:         my $count = 0;
                   7922:         foreach my $resource (@{$resources}) {
                   7923:             my $ressymb = $resource->symb();
                   7924:             my %form = ('submitted'      => 'scantron',
                   7925:                         'grade_target'   => 'grade',
                   7926:                         'grade_username' => $uname,
                   7927:                         'grade_domain'   => $udom,
                   7928:                         'grade_courseid' => $env{'request.course.id'},
                   7929:                         'grade_symb'     => $ressymb,
                   7930:                         'CODE'           => $scancode
                   7931:                        );
1.649     raeburn  7932:             if ($bubbles_per_row ne '') {
                   7933:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   7934:             }
1.554     raeburn  7935:             if (ref($parts) eq 'HASH') {
                   7936:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7937:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7938:                         $form{'scantron_questnum_start.'.$part} =
                   7939:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7940:                         $count++;
                   7941:                     }
                   7942:                 }
                   7943:             }
                   7944:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7945:             return 'ssi_error' if ($ssi_error);
                   7946:             last if (&Apache::loncommon::connection_aborted($r));
                   7947:         }
1.542     raeburn  7948:     }
                   7949:     return;
                   7950: }
                   7951: 
1.157     albertel 7952: sub scantron_upload_scantron_data {
1.608     www      7953:     my ($r,$symb)=@_;
1.565     raeburn  7954:     my $dom = $env{'request.role.domain'};
                   7955:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7956:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7957:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7958: 							  'domainid',
1.565     raeburn  7959: 							  'coursename',$dom);
                   7960:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7961:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7962:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7963:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7964:     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 7965:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7966:     function checkUpload(formname) {
                   7967: 	if (formname.upfile.value == "") {
1.579     raeburn  7968: 	    alert("'.$nofile_alert.'");
1.157     albertel 7969: 	    return false;
                   7970: 	}
1.565     raeburn  7971:         if (formname.courseid.value == "") {
1.579     raeburn  7972:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7973:             return false;
                   7974:         }
1.157     albertel 7975: 	formname.submit();
                   7976:     }
1.565     raeburn  7977: 
                   7978:     function ToSyllabus() {
                   7979:         var cdom = '."'$dom'".';
                   7980:         var cnum = document.rules.courseid.value;
                   7981:         if (cdom == "" || cdom == null) {
                   7982:             return;
                   7983:         }
                   7984:         if (cnum == "" || cnum == null) {
                   7985:            return;
                   7986:         }
                   7987:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7988:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7989:         return;
                   7990:     }
                   7991: 
1.597     wenzelju 7992: '));
                   7993:     $r->print('
1.648     bisitz   7994: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  7995: 
1.492     albertel 7996: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7997: '.$default_form_data.
                   7998:   &Apache::lonhtmlcommon::start_pick_box().
                   7999:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8000:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8001:   &Apache::lonhtmlcommon::row_closure().
                   8002:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8003:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8004:   &Apache::lonhtmlcommon::row_closure().
                   8005:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8006:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8007:   &Apache::lonhtmlcommon::row_closure().
                   8008:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8009:   '<input type="file" name="upfile" size="50" />'.
                   8010:   &Apache::lonhtmlcommon::row_closure(1).
                   8011:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8012: 
1.492     albertel 8013: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8014: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8015: </form>
1.492     albertel 8016: ');
1.157     albertel 8017:     return '';
                   8018: }
                   8019: 
1.423     albertel 8020: 
1.157     albertel 8021: sub scantron_upload_scantron_data_save {
1.608     www      8022:     my($r,$symb)=@_;
1.182     albertel 8023:     my $doanotherupload=
                   8024: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8025: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8026: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8027: 	'</form>'."\n";
1.257     albertel 8028:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8029: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8030: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8031: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8032: 	unless ($symb) {
1.182     albertel 8033: 	    $r->print($doanotherupload);
                   8034: 	}
1.162     albertel 8035: 	return '';
                   8036:     }
1.257     albertel 8037:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8038:     my $uploadedfile;
1.567     raeburn  8039:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8040:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8041:         $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 8042:     } else {
1.568     raeburn  8043:         my $result = 
                   8044:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8045:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8046: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8047: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8048:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8049: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8050:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8051:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8052:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8053: 	} else {
1.567     raeburn  8054: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8055:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8056: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8057: 	}
                   8058:     }
1.174     albertel 8059:     if ($symb) {
1.612     www      8060: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8061:     } else {
1.182     albertel 8062: 	$r->print($doanotherupload);
1.174     albertel 8063:     }
1.157     albertel 8064:     return '';
                   8065: }
                   8066: 
1.567     raeburn  8067: sub validate_uploaded_scantron_file {
                   8068:     my ($cdom,$cname,$fname) = @_;
                   8069:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8070:     my @lines;
                   8071:     if ($scanlines ne '-1') {
                   8072:         @lines=split("\n",$scanlines,-1);
                   8073:     }
                   8074:     my $output;
                   8075:     if (@lines) {
                   8076:         my (%counts,$max_match_format);
                   8077:         my ($max_match_count,$max_match_pct) = (0,0);
                   8078:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8079:         my %idmap = &username_to_idmap($classlist);
                   8080:         foreach my $key (keys(%idmap)) {
                   8081:             my $lckey = lc($key);
                   8082:             $idmap{$lckey} = $idmap{$key};
                   8083:         }
                   8084:         my %unique_formats;
                   8085:         my @formatlines = &get_scantronformat_file();
                   8086:         foreach my $line (@formatlines) {
                   8087:             chomp($line);
                   8088:             my @config = split(/:/,$line);
                   8089:             my $idstart = $config[5];
                   8090:             my $idlength = $config[6];
                   8091:             if (($idstart ne '') && ($idlength > 0)) {
                   8092:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8093:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8094:                 } else {
                   8095:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8096:                 }
                   8097:             }
                   8098:         }
                   8099:         foreach my $key (keys(%unique_formats)) {
                   8100:             my ($idstart,$idlength) = split(':',$key);
                   8101:             %{$counts{$key}} = (
                   8102:                                'found'   => 0,
                   8103:                                'total'   => 0,
                   8104:                               );
                   8105:             foreach my $line (@lines) {
                   8106:                 next if ($line =~ /^#/);
                   8107:                 next if ($line =~ /^[\s\cz]*$/);
                   8108:                 my $id = substr($line,$idstart-1,$idlength);
                   8109:                 $id = lc($id);
                   8110:                 if (exists($idmap{$id})) {
                   8111:                     $counts{$key}{'found'} ++;
                   8112:                 }
                   8113:                 $counts{$key}{'total'} ++;
                   8114:             }
                   8115:             if ($counts{$key}{'total'}) {
                   8116:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8117:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8118:                     $max_match_pct = $percent_match;
                   8119:                     $max_match_format = $key;
                   8120:                     $max_match_count = $counts{$key}{'total'};
                   8121:                 }
                   8122:             }
                   8123:         }
                   8124:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8125:             my $format_descs;
                   8126:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8127:             for (my $i=0; $i<$numwithformat; $i++) {
                   8128:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8129:                 if ($i<$numwithformat-2) {
                   8130:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8131:                 } elsif ($i==$numwithformat-2) {
                   8132:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8133:                 } elsif ($i==$numwithformat-1) {
                   8134:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8135:                 }
                   8136:             }
                   8137:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8138:             $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).
                   8139:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8140:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8141:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8142:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8143:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8144:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8145:                        '</ul>';
                   8146:         }
                   8147:     } else {
                   8148:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8149:     }
                   8150:     return $output;
                   8151: }
                   8152: 
1.202     albertel 8153: sub valid_file {
                   8154:     my ($requested_file)=@_;
                   8155:     foreach my $filename (sort(&scantron_filenames())) {
                   8156: 	if ($requested_file eq $filename) { return 1; }
                   8157:     }
                   8158:     return 0;
                   8159: }
                   8160: 
                   8161: sub scantron_download_scantron_data {
1.608     www      8162:     my ($r,$symb)=@_;
                   8163:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8164:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8165:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8166:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8167:     if (! &valid_file($file)) {
1.492     albertel 8168: 	$r->print('
1.202     albertel 8169: 	<p>
1.492     albertel 8170: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8171:         </p>
1.492     albertel 8172: ');
1.202     albertel 8173: 	return;
                   8174:     }
                   8175:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8176:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8177:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8178:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8179:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8180:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8181:     $r->print('
1.202     albertel 8182:     <p>
1.492     albertel 8183: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8184: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8185:     </p>
                   8186:     <p>
1.492     albertel 8187: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8188: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8189:     </p>
                   8190:     <p>
1.492     albertel 8191: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8192: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8193:     </p>
1.492     albertel 8194: ');
1.202     albertel 8195:     return '';
                   8196: }
1.157     albertel 8197: 
1.523     raeburn  8198: sub checkscantron_results {
1.608     www      8199:     my ($r,$symb) = @_;
1.523     raeburn  8200:     if (!$symb) {return '';}
                   8201:     my $cid = $env{'request.course.id'};
1.542     raeburn  8202:     my %lettdig = &letter_to_digits();
1.523     raeburn  8203:     my $numletts = scalar(keys(%lettdig));
                   8204:     my $cnum = $env{'course.'.$cid.'.num'};
                   8205:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8206:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8207:     my %record;
                   8208:     my %scantron_config =
                   8209:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8210:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8211:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8212:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8213:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8214:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8215:     unless (ref($navmap)) {
                   8216:         $r->print(&navmap_errormsg());
                   8217:         return '';
                   8218:     }
1.523     raeburn  8219:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8220:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8221:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8222:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8223: 
1.554     raeburn  8224:     my ($uname,$udom);
1.523     raeburn  8225:     my (%scandata,%lastname,%bylast);
                   8226:     $r->print('
                   8227: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8228: 
                   8229:     my @delayqueue;
                   8230:     my %completedstudents;
                   8231: 
                   8232:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8233:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8234:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8235:                                     'inline',undef,'checkscantron');
1.546     raeburn  8236:     my ($username,$domain,$started);
1.582     raeburn  8237:     my $nav_error;
1.649     raeburn  8238:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8239:     if ($nav_error) {
                   8240:         $r->print(&navmap_errormsg());
                   8241:         return '';
                   8242:     }
1.523     raeburn  8243: 
                   8244:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8245:                                           'Processing first student');
                   8246:     my $start=&Time::HiRes::time();
                   8247:     my $i=-1;
                   8248: 
                   8249:     while ($i<$scanlines->{'count'}) {
                   8250:         ($username,$domain,$uname)=('','','');
                   8251:         $i++;
                   8252:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8253:         if ($line=~/^[\s\cz]*$/) { next; }
                   8254:         if ($started) {
                   8255:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8256:                                                      'last student');
                   8257:         }
                   8258:         $started=1;
                   8259:         my $scan_record=
                   8260:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8261:                                                      $scan_data);
                   8262:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8263:                                                               \%idmap,$i)) {
                   8264:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8265:                                 'Unable to find a student that matches',1);
                   8266:             next;
                   8267:         }
                   8268:         if (exists $completedstudents{$uname}) {
                   8269:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8270:                                 'Student '.$uname.' has multiple sheets',2);
                   8271:             next;
                   8272:         }
                   8273:         my $pid = $scan_record->{'scantron.ID'};
                   8274:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8275:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8276:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8277:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8278:         chomp($scandata{$pid});
                   8279:         $scandata{$pid} =~ s/\r$//;
                   8280:         ($username,$domain)=split(/:/,$uname);
                   8281:         my $counter = -1;
                   8282:         foreach my $resource (@resources) {
1.557     raeburn  8283:             my $parts;
1.554     raeburn  8284:             my $ressymb = $resource->symb();
1.557     raeburn  8285:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8286:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8287:                 (my $analysis,$parts) =
1.649     raeburn  8288:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
1.557     raeburn  8289:             } else {
                   8290:                 $parts = $grader_partids_by_symb{$ressymb};
                   8291:             }
1.542     raeburn  8292:             ($counter,my $recording) =
                   8293:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8294:                                          $scandata{$pid},$parts,
1.542     raeburn  8295:                                          \%scantron_config,\%lettdig,$numletts);
                   8296:             $record{$pid} .= $recording;
1.523     raeburn  8297:         }
                   8298:     }
                   8299:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8300:     $r->print('<br />');
                   8301:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8302:     $passed = 0;
                   8303:     $failed = 0;
                   8304:     $numstudents = 0;
                   8305:     foreach my $last (sort(keys(%bylast))) {
                   8306:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8307:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8308:                 my $showscandata = $scandata{$pid};
                   8309:                 my $showrecord = $record{$pid};
                   8310:                 $showscandata =~ s/\s/&nbsp;/g;
                   8311:                 $showrecord =~ s/\s/&nbsp;/g;
                   8312:                 if ($scandata{$pid} eq $record{$pid}) {
                   8313:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8314:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8315: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8316: '</tr>'."\n".
                   8317: '<tr class="'.$css_class.'">'."\n".
                   8318: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8319:                     $passed ++;
                   8320:                 } else {
                   8321:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8322:                     $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  8323: '</tr>'."\n".
                   8324: '<tr class="'.$css_class.'">'."\n".
                   8325: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8326: '</tr>'."\n";
                   8327:                     $failed ++;
                   8328:                 }
                   8329:                 $numstudents ++;
                   8330:             }
                   8331:         }
                   8332:     }
1.648     bisitz   8333:     $r->print(
                   8334:         '<p>'
                   8335:        .&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).',
                   8336:             '<b>',
                   8337:             $numstudents,
                   8338:             '</b>',
                   8339:             $env{'form.scantron_maxbubble'})
                   8340:        .'</p>'
                   8341:     );
1.523     raeburn  8342:     $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>');
                   8343:     if ($passed) {
1.572     www      8344:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8345:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8346:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8347:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8348:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8349:                  $okstudents."\n".
                   8350:                  &Apache::loncommon::end_data_table().'<br />');
                   8351:     }
                   8352:     if ($failed) {
1.572     www      8353:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8354:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8355:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8356:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8357:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8358:                  $badstudents."\n".
                   8359:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8360:                  &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  8361:     }
1.614     www      8362:     $r->print('</form><br />');
1.523     raeburn  8363:     return;
                   8364: }
                   8365: 
1.542     raeburn  8366: sub verify_scantron_grading {
1.554     raeburn  8367:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8368:         $scantron_config,$lettdig,$numletts) = @_;
                   8369:     my ($record,%expected,%startpos);
                   8370:     return ($counter,$record) if (!ref($resource));
                   8371:     return ($counter,$record) if (!$resource->is_problem());
                   8372:     my $symb = $resource->symb();
1.554     raeburn  8373:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8374:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8375:         $counter ++;
                   8376:         $expected{$part_id} = 0;
                   8377:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8378:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8379:             foreach my $item (@sub_lines) {
                   8380:                 $expected{$part_id} += $item;
                   8381:             }
                   8382:         } else {
                   8383:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8384:         }
                   8385:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8386:     }
                   8387:     if ($symb) {
                   8388:         my %recorded;
                   8389:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8390:         if ($returnhash{'version'}) {
                   8391:             my %lasthash=();
                   8392:             my $version;
                   8393:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8394:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8395:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8396:                 }
                   8397:             }
                   8398:             foreach my $key (keys(%lasthash)) {
                   8399:                 if ($key =~ /\.scantron$/) {
                   8400:                     my $value = &unescape($lasthash{$key});
                   8401:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8402:                     if ($value eq '') {
                   8403:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8404:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8405:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8406:                             }
                   8407:                         }
                   8408:                     } else {
                   8409:                         my @tocheck;
                   8410:                         my @items = split(//,$value);
                   8411:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8412:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8413:                             if (@items < $expected{$part_id}) {
                   8414:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8415:                                 my @singles = split(//,$fragment);
                   8416:                                 foreach my $pos (@singles) {
                   8417:                                     if ($pos eq ' ') {
                   8418:                                         push(@tocheck,$pos);
                   8419:                                     } else {
                   8420:                                         my $next = shift(@items);
                   8421:                                         push(@tocheck,$next);
                   8422:                                     }
                   8423:                                 }
                   8424:                             } else {
                   8425:                                 @tocheck = @items;
                   8426:                             }
                   8427:                             foreach my $letter (@tocheck) {
                   8428:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8429:                                     if ($letter !~ /^[A-J]$/) {
                   8430:                                         $letter = $scantron_config->{'Qoff'};
                   8431:                                     }
                   8432:                                     $recorded{$part_id} .= $letter;
                   8433:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8434:                                     my $digit;
                   8435:                                     if ($letter !~ /^[A-J]$/) {
                   8436:                                         $digit = $scantron_config->{'Qoff'};
                   8437:                                     } else {
                   8438:                                         $digit = $lettdig->{$letter};
                   8439:                                     }
                   8440:                                     $recorded{$part_id} .= $digit;
                   8441:                                 }
                   8442:                             }
                   8443:                         } else {
                   8444:                             @tocheck = @items;
                   8445:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8446:                                 my $curr_sub = shift(@tocheck);
                   8447:                                 my $digit;
                   8448:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8449:                                     $digit = $lettdig->{$curr_sub}-1;
                   8450:                                 }
                   8451:                                 if ($curr_sub eq 'J') {
                   8452:                                     $digit += scalar($numletts);
                   8453:                                 }
                   8454:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8455:                                     if ($j == $digit) {
                   8456:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8457:                                     } else {
                   8458:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8459:                                     }
                   8460:                                 }
                   8461:                             }
                   8462:                         }
                   8463:                     }
                   8464:                 }
                   8465:             }
                   8466:         }
1.554     raeburn  8467:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8468:             if ($recorded{$part_id} eq '') {
                   8469:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8470:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8471:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8472:                     }
                   8473:                 }
                   8474:             }
                   8475:             $record .= $recorded{$part_id};
                   8476:         }
                   8477:     }
                   8478:     return ($counter,$record);
                   8479: }
                   8480: 
                   8481: sub letter_to_digits { 
                   8482:     my %lettdig = (
                   8483:                     A => 1,
                   8484:                     B => 2,
                   8485:                     C => 3,
                   8486:                     D => 4,
                   8487:                     E => 5,
                   8488:                     F => 6,
                   8489:                     G => 7,
                   8490:                     H => 8,
                   8491:                     I => 9,
                   8492:                     J => 0,
                   8493:                   );
                   8494:     return %lettdig;
                   8495: }
                   8496: 
1.423     albertel 8497: 
1.75      albertel 8498: #-------- end of section for handling grading scantron forms -------
                   8499: #
                   8500: #-------------------------------------------------------------------
                   8501: 
1.72      ng       8502: #-------------------------- Menu interface -------------------------
                   8503: #
1.614     www      8504: #--- Href with symb and command ---
                   8505: 
                   8506: sub href_symb_cmd {
                   8507:     my ($symb,$cmd)=@_;
                   8508:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8509: }
                   8510: 
1.443     banghart 8511: sub grading_menu {
1.608     www      8512:     my ($request,$symb) = @_;
1.443     banghart 8513:     if (!$symb) {return '';}
                   8514: 
                   8515:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8516:                   'command'=>'individual');
1.538     schulted 8517:     
1.598     www      8518:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8519: 
                   8520:     $fields{'command'}='ungraded';
                   8521:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8522: 
                   8523:     $fields{'command'}='table';
                   8524:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8525: 
                   8526:     $fields{'command'}='all_for_one';
                   8527:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8528: 
1.621     www      8529:     $fields{'command'}='downloadfilesselect';
                   8530:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8531: 
1.443     banghart 8532:     $fields{'command'} = 'csvform';
1.538     schulted 8533:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8534:     
1.443     banghart 8535:     $fields{'command'} = 'processclicker';
1.538     schulted 8536:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8537:     
1.443     banghart 8538:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8539:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8540: 
                   8541:     $fields{'command'} = 'initialverifyreceipt';
                   8542:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8543:     
1.598     www      8544:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8545:             items =>[
1.598     www      8546:                         {	linktext => 'Select individual students to grade',
                   8547:                     		url => $url1a,
1.538     schulted 8548:                     		permission => 'F',
1.636     wenzelju 8549:                     		icon => 'grade_students.png',
1.598     www      8550:                     		linktitle => 'Grade current resource for a selection of students.'
                   8551:                         }, 
                   8552:                         {       linktext => 'Grade ungraded submissions.',
                   8553:                                 url => $url1b,
                   8554:                                 permission => 'F',
1.636     wenzelju 8555:                                 icon => 'ungrade_sub.png',
1.598     www      8556:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8557:                         },
1.598     www      8558: 
                   8559:                         {       linktext => 'Grading table',
                   8560:                                 url => $url1c,
                   8561:                                 permission => 'F',
1.636     wenzelju 8562:                                 icon => 'grading_table.png',
1.598     www      8563:                                 linktitle => 'Grade current resource for all students.'
                   8564:                         },
1.615     www      8565:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8566:                                 url => $url1d,
                   8567:                                 permission => 'F',
1.636     wenzelju 8568:                                 icon => 'grade_PageFolder.png',
1.598     www      8569:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8570:                         },
                   8571:                         {       linktext => 'Download submissions',
                   8572:                                 url => $url1e,
                   8573:                                 permission => 'F',
1.636     wenzelju 8574:                                 icon => 'download_sub.png',
1.621     www      8575:                                 linktitle => 'Download all students submissions.'
1.598     www      8576:                         }]},
                   8577:                          { categorytitle=>'Automated Grading',
                   8578:                items =>[
                   8579: 
1.538     schulted 8580:                 	    {	linktext => 'Upload Scores',
                   8581:                     		url => $url2,
                   8582:                     		permission => 'F',
                   8583:                     		icon => 'uploadscores.png',
                   8584:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8585:                 	    },
                   8586:                 	    {	linktext => 'Process Clicker',
                   8587:                     		url => $url3,
                   8588:                     		permission => 'F',
                   8589:                     		icon => 'addClickerInfoFile.png',
                   8590:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8591:                 	    },
1.587     raeburn  8592:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8593:                     		url => $url4,
                   8594:                     		permission => 'F',
1.636     wenzelju 8595:                     		icon => 'bubblesheet.png',
1.648     bisitz   8596:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8597:                 	    },
1.616     www      8598:                             {   linktext => 'Verify Receipt Number',
1.602     www      8599:                                 url => $url5,
                   8600:                                 permission => 'F',
1.636     wenzelju 8601:                                 icon => 'receipt_number.png',
1.602     www      8602:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8603:                             }
                   8604: 
1.538     schulted 8605:                     ]
                   8606:             });
                   8607: 
1.443     banghart 8608:     # Create the menu
                   8609:     my $Str;
1.445     banghart 8610:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8611:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8612:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8613: 
1.602     www      8614:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8615:     return $Str;    
                   8616: }
                   8617: 
1.598     www      8618: 
                   8619: sub ungraded {
                   8620:     my ($request)=@_;
                   8621:     &submit_options($request);
                   8622: }
                   8623: 
1.599     www      8624: sub submit_options_sequence {
1.608     www      8625:     my ($request,$symb) = @_;
1.599     www      8626:     if (!$symb) {return '';}
1.600     www      8627:     &commonJSfunctions($request);
                   8628:     my $result;
1.599     www      8629: 
1.600     www      8630:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8631:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8632:     $result.=&selectfield(0).
1.601     www      8633:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8634:             <div>
                   8635:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8636:             </div>
                   8637:         </div>
                   8638:   </form>';
                   8639:     return $result;
                   8640: }
                   8641: 
                   8642: sub submit_options_table {
1.608     www      8643:     my ($request,$symb) = @_;
1.600     www      8644:     if (!$symb) {return '';}
1.599     www      8645:     &commonJSfunctions($request);
                   8646:     my $result;
                   8647: 
                   8648:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8649:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8650: 
1.632     www      8651:     $result.=&selectfield(0).
1.601     www      8652:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8653:             <div>
                   8654:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8655:             </div>
                   8656:         </div>
                   8657:   </form>';
                   8658:     return $result;
                   8659: }
1.443     banghart 8660: 
1.621     www      8661: sub submit_options_download {
                   8662:     my ($request,$symb) = @_;
                   8663:     if (!$symb) {return '';}
                   8664: 
                   8665:     &commonJSfunctions($request);
                   8666: 
                   8667:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8668:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8669:     $result.='
                   8670: <h2>
                   8671:   '.&mt('Select Students for Which to Download Submissions').'
                   8672: </h2>'.&selectfield(1).'
                   8673:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8674:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8675:             </div>
                   8676:           </div>
1.600     www      8677: 
                   8678: 
1.621     www      8679:   </form>';
                   8680:     return $result;
                   8681: }
                   8682: 
1.443     banghart 8683: #--- Displays the submissions first page -------
                   8684: sub submit_options {
1.608     www      8685:     my ($request,$symb) = @_;
1.72      ng       8686:     if (!$symb) {return '';}
                   8687: 
1.118     ng       8688:     &commonJSfunctions($request);
1.473     albertel 8689:     my $result;
1.533     bisitz   8690: 
1.72      ng       8691:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8692: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8693:     $result.=&selectfield(1).'
1.601     www      8694:                 <input type="hidden" name="command" value="submission" /> 
                   8695: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8696:             </div>
                   8697:           </div>
                   8698: 
                   8699: 
                   8700:   </form>';
                   8701:     return $result;
                   8702: }
1.533     bisitz   8703: 
1.601     www      8704: sub selectfield {
                   8705:    my ($full)=@_;
1.635     raeburn  8706:    my %options = 
                   8707:           (&Apache::lonlocal::texthash(
                   8708:              'yes'       => 'with submissions',
                   8709:              'queued'    => 'in grading queue',
                   8710:              'graded'    => 'with ungraded submissions',
                   8711:              'incorrect' => 'with incorrect submissions',
                   8712:              'all'       => 'with any status'),
                   8713:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8714:    my $result='<div class="LC_columnSection">
1.537     harmsja  8715:   
1.533     bisitz   8716:     <fieldset>
                   8717:       <legend>
                   8718:        '.&mt('Sections').'
                   8719:       </legend>
1.601     www      8720:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8721:     </fieldset>
1.537     harmsja  8722:   
1.533     bisitz   8723:     <fieldset>
                   8724:       <legend>
                   8725:         '.&mt('Groups').'
                   8726:       </legend>
                   8727:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8728:     </fieldset>
1.537     harmsja  8729:   
1.533     bisitz   8730:     <fieldset>
                   8731:       <legend>
                   8732:         '.&mt('Access Status').'
                   8733:       </legend>
1.601     www      8734:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8735:     </fieldset>';
                   8736:     if ($full) {
                   8737:        $result.='
1.533     bisitz   8738:     <fieldset>
                   8739:       <legend>
                   8740:         '.&mt('Submission Status').'
1.601     www      8741:       </legend>'.
1.635     raeburn  8742:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8743:    '</fieldset>';
                   8744:     }
                   8745:     $result.='</div><br />';
1.44      ng       8746:     return $result;
1.2       albertel 8747: }
                   8748: 
1.285     albertel 8749: sub reset_perm {
                   8750:     undef(%perm);
                   8751: }
                   8752: 
                   8753: sub init_perm {
                   8754:     &reset_perm();
1.300     albertel 8755:     foreach my $test_perm ('vgr','mgr','opa') {
                   8756: 
                   8757: 	my $scope = $env{'request.course.id'};
                   8758: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8759: 
                   8760: 	    $scope .= '/'.$env{'request.course.sec'};
                   8761: 	    if ( $perm{$test_perm}=
                   8762: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8763: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8764: 	    } else {
                   8765: 		delete($perm{$test_perm});
                   8766: 	    }
1.285     albertel 8767: 	}
                   8768:     }
                   8769: }
                   8770: 
1.400     www      8771: sub gather_clicker_ids {
1.408     albertel 8772:     my %clicker_ids;
1.400     www      8773: 
                   8774:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8775: 
                   8776:     # Set up a couple variables.
1.407     albertel 8777:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8778:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8779:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8780: 
1.407     albertel 8781:     foreach my $student (keys(%$classlist)) {
1.438     www      8782:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8783:         my $username = $classlist->{$student}->[$username_idx];
                   8784:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8785:         my $clickers =
1.408     albertel 8786: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8787:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8788:             $id=~s/^[\#0]+//;
1.421     www      8789:             $id=~s/[\-\:]//g;
1.407     albertel 8790:             if (exists($clicker_ids{$id})) {
1.408     albertel 8791: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8792:             } else {
1.408     albertel 8793: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8794:             }
                   8795:         }
                   8796:     }
1.407     albertel 8797:     return %clicker_ids;
1.400     www      8798: }
                   8799: 
1.402     www      8800: sub gather_adv_clicker_ids {
1.408     albertel 8801:     my %clicker_ids;
1.402     www      8802:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8803:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8804:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8805:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8806:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8807:             my ($puname,$pudom)=split(/\:/,$person);
                   8808:             my $clickers =
1.408     albertel 8809: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8810:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8811: 		$id=~s/^[\#0]+//;
1.421     www      8812:                 $id=~s/[\-\:]//g;
1.408     albertel 8813: 		if (exists($clicker_ids{$id})) {
                   8814: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8815: 		} else {
                   8816: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8817: 		}
1.405     www      8818:             }
1.402     www      8819:         }
                   8820:     }
1.407     albertel 8821:     return %clicker_ids;
1.402     www      8822: }
                   8823: 
1.413     www      8824: sub clicker_grading_parameters {
                   8825:     return ('gradingmechanism' => 'scalar',
                   8826:             'upfiletype' => 'scalar',
                   8827:             'specificid' => 'scalar',
                   8828:             'pcorrect' => 'scalar',
                   8829:             'pincorrect' => 'scalar');
                   8830: }
                   8831: 
1.400     www      8832: sub process_clicker {
1.608     www      8833:     my ($r,$symb)=@_;
1.400     www      8834:     if (!$symb) {return '';}
                   8835:     my $result=&checkforfile_js();
1.632     www      8836:     $result.=&Apache::loncommon::start_data_table().
                   8837:              &Apache::loncommon::start_data_table_header_row().
                   8838:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8839:              &Apache::loncommon::end_data_table_header_row().
                   8840:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8841: # Attempt to restore parameters from last session, set defaults if not present
                   8842:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8843:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8844:                                                  \%Saveable_Parameters);
                   8845:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8846:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8847:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8848:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8849: 
                   8850:     my %checked;
1.521     www      8851:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8852:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8853:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8854:        }
                   8855:     }
                   8856: 
1.632     www      8857:     my $upload=&mt("Evaluate File");
1.400     www      8858:     my $type=&mt("Type");
1.402     www      8859:     my $attendance=&mt("Award points just for participation");
                   8860:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8861:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8862:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8863:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8864:     my $pcorrect=&mt("Percentage points for correct solution");
                   8865:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8866:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8867: 						   {'iclicker' => 'i>clicker',
                   8868:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8869:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8870:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8871: function sanitycheck() {
                   8872: // Accept only integer percentages
                   8873:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8874:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8875: // Find out grading choice
                   8876:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8877:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8878:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8879:       }
                   8880:    }
                   8881: // By default, new choice equals user selection
                   8882:    newgradingchoice=gradingchoice;
                   8883: // Not good to give more points for false answers than correct ones
                   8884:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8885:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8886:    }
                   8887: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8888:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8889:       document.forms.gradesupload.pcorrect.value=100;
                   8890:       document.forms.gradesupload.pincorrect.value=100;
                   8891:    }
                   8892: // If the values are different, cannot be attendance only
                   8893:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8894:        (gradingchoice=='attendance')) {
                   8895:        newgradingchoice='personnel';
                   8896:    }
                   8897: // Change grading choice to new one
                   8898:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8899:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8900:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8901:       } else {
                   8902:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8903:       }
                   8904:    }
                   8905: // Remember the old state
                   8906:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8907: }
1.597     wenzelju 8908: ENDUPFORM
                   8909:     $result.= <<ENDUPFORM;
1.400     www      8910: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8911: <input type="hidden" name="symb" value="$symb" />
                   8912: <input type="hidden" name="command" value="processclickerfile" />
                   8913: <input type="file" name="upfile" size="50" />
                   8914: <br /><label>$type: $selectform</label>
1.632     www      8915: ENDUPFORM
                   8916:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8917:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8918:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8919: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8920: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8921: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8922: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8923: <br />&nbsp;&nbsp;&nbsp;
                   8924: <input type="text" name="givenanswer" size="50" />
1.413     www      8925: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8926: ENDGRADINGFORM
                   8927:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8928:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8929:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8930: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8931: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8932: </form>'
1.632     www      8933: ENDPERCFORM
                   8934:     $result.='</td>'.
                   8935:              &Apache::loncommon::end_data_table_row().
                   8936:              &Apache::loncommon::end_data_table();
1.400     www      8937:     return $result;
                   8938: }
                   8939: 
                   8940: sub process_clicker_file {
1.608     www      8941:     my ($r,$symb)=@_;
1.400     www      8942:     if (!$symb) {return '';}
1.413     www      8943: 
                   8944:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8945:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8946:                                               \%Saveable_Parameters);
1.598     www      8947:     my $result='';
1.404     www      8948:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8949: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8950: 	return $result;
1.404     www      8951:     }
1.522     www      8952:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8953:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8954:         return $result;
1.521     www      8955:     }
1.522     www      8956:     my $foundgiven=0;
1.521     www      8957:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8958:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8959:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      8960:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      8961:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8962:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8963:         $foundgiven=$#answers+1;
1.521     www      8964:     }
1.407     albertel 8965:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8966:     my %correct_ids;
1.404     www      8967:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8968: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8969:     }
                   8970:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8971: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8972: 	   $correct_id=~tr/a-z/A-Z/;
                   8973: 	   $correct_id=~s/\s//gs;
                   8974: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8975:            $correct_id=~s/[\-\:]//g;
1.414     www      8976:            if ($correct_id) {
                   8977: 	      $correct_ids{$correct_id}='specified';
                   8978:            }
                   8979:         }
1.400     www      8980:     }
1.404     www      8981:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8982: 	$result.=&mt('Score based on attendance only');
1.521     www      8983:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8984:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8985:     } else {
1.408     albertel 8986: 	my $number=0;
1.411     www      8987: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8988: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8989: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8990: 	    if ($correct_ids{$id} eq 'specified') {
                   8991: 		$result.=&mt('specified');
                   8992: 	    } else {
                   8993: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8994: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8995: 	    }
                   8996: 	    $number++;
                   8997: 	}
1.411     www      8998:         $result.="</p>\n";
1.408     albertel 8999: 	if ($number==0) {
                   9000: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      9001: 	    return $result;
1.408     albertel 9002: 	}
1.404     www      9003:     }
1.405     www      9004:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9005:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9006: 		     '<span class="LC_error">',
                   9007: 		     '</span>',
                   9008: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      9009:         return $result;
1.405     www      9010:     }
1.410     www      9011: 
                   9012: # Were able to get all the info needed, now analyze the file
                   9013: 
1.411     www      9014:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9015:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9016:     $result.=&Apache::loncommon::start_data_table().
                   9017:              &Apache::loncommon::start_data_table_header_row().
                   9018:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9019:              &Apache::loncommon::end_data_table_header_row().
                   9020:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9021: <td>
1.410     www      9022: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9023: <input type="hidden" name="symb" value="$symb" />
                   9024: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9025: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9026: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9027: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9028: ENDHEADER
1.522     www      9029:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9030:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9031:     } 
1.408     albertel 9032:     my %responses;
                   9033:     my @questiontitles;
1.405     www      9034:     my $errormsg='';
                   9035:     my $number=0;
                   9036:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9037: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9038:     }
1.419     www      9039:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9040:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9041:     }
1.411     www      9042:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9043:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9044:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9045:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9046:              '<br />';
1.522     www      9047:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9048:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9049:        return $result;
1.522     www      9050:     } 
1.414     www      9051: # Remember Question Titles
                   9052: # FIXME: Possibly need delimiter other than ":"
                   9053:     for (my $i=0;$i<$number;$i++) {
                   9054:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9055:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9056:     }
1.411     www      9057:     my $correct_count=0;
                   9058:     my $student_count=0;
                   9059:     my $unknown_count=0;
1.414     www      9060: # Match answers with usernames
                   9061: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9062:     foreach my $id (keys(%responses)) {
1.410     www      9063:        if ($correct_ids{$id}) {
1.414     www      9064:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9065:           $correct_count++;
1.410     www      9066:        } elsif ($clicker_ids{$id}) {
1.437     www      9067:           if ($clicker_ids{$id}=~/\,/) {
                   9068: # More than one user with the same clicker!
1.632     www      9069:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9070:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9071:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9072:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9073:                            "<select name='multi".$id."'>";
                   9074:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9075:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9076:              }
                   9077:              $result.='</select>';
                   9078:              $unknown_count++;
                   9079:           } else {
                   9080: # Good: found one and only one user with the right clicker
                   9081:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9082:              $student_count++;
                   9083:           }
1.410     www      9084:        } else {
1.632     www      9085:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9086:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9087:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9088:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9089:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9090:                    "\n".&mt("Domain").": ".
                   9091:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9092:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9093:           $unknown_count++;
1.410     www      9094:        }
1.405     www      9095:     }
1.412     www      9096:     $result.='<hr />'.
                   9097:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9098:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9099:        if ($correct_count==0) {
                   9100:           $errormsg.="Found no correct answers answers for grading!";
                   9101:        } elsif ($correct_count>1) {
1.414     www      9102:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9103:        }
                   9104:     }
1.428     www      9105:     if ($number<1) {
                   9106:        $errormsg.="Found no questions.";
                   9107:     }
1.412     www      9108:     if ($errormsg) {
                   9109:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9110:     } else {
                   9111:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9112:     }
1.632     www      9113:     $result.='</form></td>'.
                   9114:              &Apache::loncommon::end_data_table_row().
                   9115:              &Apache::loncommon::end_data_table();
1.614     www      9116:     return $result;
1.400     www      9117: }
                   9118: 
1.405     www      9119: sub iclicker_eval {
1.406     www      9120:     my ($questiontitles,$responses)=@_;
1.405     www      9121:     my $number=0;
                   9122:     my $errormsg='';
                   9123:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9124:         my %components=&Apache::loncommon::record_sep($line);
                   9125:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9126: 	if ($entries[0] eq 'Question') {
                   9127: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9128: 		$$questiontitles[$number]=$entries[$i];
                   9129: 		$number++;
                   9130: 	    }
                   9131: 	}
                   9132: 	if ($entries[0]=~/^\#/) {
                   9133: 	    my $id=$entries[0];
                   9134: 	    my @idresponses;
                   9135: 	    $id=~s/^[\#0]+//;
                   9136: 	    for (my $i=0;$i<$number;$i++) {
                   9137: 		my $idx=3+$i*6;
1.644     www      9138:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9139: 		push(@idresponses,$entries[$idx]);
                   9140: 	    }
                   9141: 	    $$responses{$id}=join(',',@idresponses);
                   9142: 	}
1.405     www      9143:     }
                   9144:     return ($errormsg,$number);
                   9145: }
                   9146: 
1.419     www      9147: sub interwrite_eval {
                   9148:     my ($questiontitles,$responses)=@_;
                   9149:     my $number=0;
                   9150:     my $errormsg='';
1.420     www      9151:     my $skipline=1;
                   9152:     my $questionnumber=0;
                   9153:     my %idresponses=();
1.419     www      9154:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9155:         my %components=&Apache::loncommon::record_sep($line);
                   9156:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9157:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9158:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9159:         next if $skipline;
                   9160:         if ($entries[0]!=$questionnumber) {
                   9161:            $questionnumber=$entries[0];
                   9162:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9163:            $number++;
1.419     www      9164:         }
1.420     www      9165:         my $id=$entries[4];
                   9166:         $id=~s/^[\#0]+//;
1.421     www      9167:         $id=~s/^v\d*\://i;
                   9168:         $id=~s/[\-\:]//g;
1.420     www      9169:         $idresponses{$id}[$number]=$entries[6];
                   9170:     }
1.524     raeburn  9171:     foreach my $id (keys(%idresponses)) {
1.420     www      9172:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9173:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9174:     }
                   9175:     return ($errormsg,$number);
                   9176: }
                   9177: 
1.414     www      9178: sub assign_clicker_grades {
1.608     www      9179:     my ($r,$symb)=@_;
1.414     www      9180:     if (!$symb) {return '';}
1.416     www      9181: # See which part we are saving to
1.582     raeburn  9182:     my $res_error;
                   9183:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9184:     if ($res_error) {
                   9185:         return &navmap_errormsg();
                   9186:     }
1.416     www      9187: # FIXME: This should probably look for the first handgradeable part
                   9188:     my $part=$$partlist[0];
                   9189: # Start screen output
1.632     www      9190:     my $result=&Apache::loncommon::start_data_table().
                   9191:              &Apache::loncommon::start_data_table_header_row().
                   9192:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9193:              &Apache::loncommon::end_data_table_header_row().
                   9194:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9195: # Get correct result
                   9196: # FIXME: Possibly need delimiter other than ":"
                   9197:     my @correct=();
1.415     www      9198:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9199:     my $number=$env{'form.number'};
                   9200:     if ($gradingmechanism ne 'attendance') {
1.414     www      9201:        foreach my $key (keys(%env)) {
                   9202:           if ($key=~/^form\.correct\:/) {
                   9203:              my @input=split(/\,/,$env{$key});
                   9204:              for (my $i=0;$i<=$#input;$i++) {
                   9205:                  if (($correct[$i]) && ($input[$i]) &&
                   9206:                      ($correct[$i] ne $input[$i])) {
                   9207:                     $result.='<br /><span class="LC_warning">'.
                   9208:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9209:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9210:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9211:                     $correct[$i]=$input[$i];
                   9212:                  }
                   9213:              }
                   9214:           }
                   9215:        }
1.415     www      9216:        for (my $i=0;$i<$number;$i++) {
1.644     www      9217:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9218:              $result.='<br /><span class="LC_error">'.
                   9219:                       &mt('No correct result given for question "[_1]"!',
                   9220:                           $env{'form.question:'.$i}).'</span>';
                   9221:           }
                   9222:        }
1.644     www      9223:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9224:     }
                   9225: # Start grading
1.415     www      9226:     my $pcorrect=$env{'form.pcorrect'};
                   9227:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9228:     my $storecount=0;
1.632     www      9229:     my %users=();
1.415     www      9230:     foreach my $key (keys(%env)) {
1.420     www      9231:        my $user='';
1.415     www      9232:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9233:           $user=$1;
                   9234:        }
                   9235:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9236:           my $id=$1;
                   9237:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9238:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9239:           } elsif ($env{'form.multi'.$id}) {
                   9240:              $user=$env{'form.multi'.$id};
1.420     www      9241:           }
                   9242:        }
1.632     www      9243:        if ($user) {
                   9244:           if ($users{$user}) {
                   9245:              $result.='<br /><span class="LC_warning">'.
                   9246:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9247:                       '</span><br />';
                   9248:           }
                   9249:           $users{$user}=1; 
1.415     www      9250:           my @answer=split(/\,/,$env{$key});
                   9251:           my $sum=0;
1.522     www      9252:           my $realnumber=$number;
1.415     www      9253:           for (my $i=0;$i<$number;$i++) {
1.576     www      9254:              if  ($correct[$i] eq '-') {
                   9255:                 $realnumber--;
1.644     www      9256:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9257:                 if ($gradingmechanism eq 'attendance') {
                   9258:                    $sum+=$pcorrect;
1.576     www      9259:                 } elsif ($correct[$i] eq '*') {
1.522     www      9260:                    $sum+=$pcorrect;
1.415     www      9261:                 } else {
1.644     www      9262: # We actually grade if correct or not
                   9263:                    my $increment=$pincorrect;
                   9264: # Special case: numerical answer "0"
                   9265:                    if ($correct[$i] eq '0') {
                   9266:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9267:                          $increment=$pcorrect;
                   9268:                       }
                   9269: # General numerical answer, both evaluate to something non-zero
                   9270:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9271:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9272:                          $increment=$pcorrect;
                   9273:                       }
                   9274: # Must be just alphanumeric
                   9275:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9276:                       $increment=$pcorrect;
1.415     www      9277:                    }
1.644     www      9278:                    $sum+=$increment;
1.415     www      9279:                 }
                   9280:              }
                   9281:           }
1.522     www      9282:           my $ave=$sum/(100*$realnumber);
1.416     www      9283: # Store
                   9284:           my ($username,$domain)=split(/\:/,$user);
                   9285:           my %grades=();
                   9286:           $grades{"resource.$part.solved"}='correct_by_override';
                   9287:           $grades{"resource.$part.awarded"}=$ave;
                   9288:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9289:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9290:                                                  $env{'request.course.id'},
                   9291:                                                  $domain,$username);
                   9292:           if ($returncode ne 'ok') {
                   9293:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9294:           } else {
                   9295:              $storecount++;
                   9296:           }
1.415     www      9297:        }
                   9298:     }
                   9299: # We are done
1.549     hauer    9300:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9301:              '</td>'.
                   9302:              &Apache::loncommon::end_data_table_row().
                   9303:              &Apache::loncommon::end_data_table();
1.614     www      9304:     return $result;
1.414     www      9305: }
                   9306: 
1.582     raeburn  9307: sub navmap_errormsg {
                   9308:     return '<div class="LC_error">'.
                   9309:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9310:            &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  9311:            '</div>';
                   9312: }
1.607     droeschl 9313: 
1.609     www      9314: sub startpage {
1.613     www      9315:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9316:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9317:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9318:                                           {'bread_crumbs' => $crumbs}));
1.645     www      9319:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
1.613     www      9320:     unless ($nodisplayflag) {
                   9321:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9322:     }
1.607     droeschl 9323: }
1.582     raeburn  9324: 
1.622     www      9325: sub select_problem {
                   9326:     my ($r)=@_;
1.632     www      9327:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9328:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9329:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9330:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9331: }
                   9332: 
1.1       albertel 9333: sub handler {
1.41      ng       9334:     my $request=$_[0];
1.434     albertel 9335:     &reset_caches();
1.646     raeburn  9336:     if ($request->header_only) {
                   9337:         &Apache::loncommon::content_type($request,'text/html');
                   9338:         $request->send_http_header;
                   9339:         return OK;
                   9340:     }
                   9341:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9342: 
                   9343:     &init_perm();
                   9344:     if (!$env{'request.course.id'}) {
                   9345:         # Not in a course.
                   9346:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9347:         return HTTP_NOT_ACCEPTABLE;
                   9348:     } elsif (!%perm) {
                   9349:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9350:     }
1.646     raeburn  9351:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9352:     $request->send_http_header;
1.646     raeburn  9353: 
1.608     www      9354: 
                   9355: # see what command we need to execute
                   9356: 
1.160     albertel 9357:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9358:     my $command=$commands[0];
1.447     foxr     9359: 
1.160     albertel 9360:     if ($#commands > 0) {
                   9361: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9362:     }
1.608     www      9363: 
                   9364: # see what the symb is
                   9365: 
                   9366:     my $symb=$env{'form.symb'};
                   9367:     unless ($symb) {
                   9368:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9369:        $symb=&Apache::lonnet::symbread($url);
                   9370:     }
1.646     raeburn  9371:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9372: 
1.513     foxr     9373:     $ssi_error = 0;
1.637     www      9374:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9375: #
1.637     www      9376: # Not called from a resource, but inside a course
1.601     www      9377: #    
1.622     www      9378:         &startpage($request,undef,[],1,1);
                   9379:         &select_problem($request);
1.41      ng       9380:     } else {
1.104     albertel 9381: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9382:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9383: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9384: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9385:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9386:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9387: 	    &pickStudentPage($request,$symb);
1.103     albertel 9388: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9389:             &startpage($request,$symb,
                   9390:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9391:                                        {href=>'',text=>'Select student'},
                   9392:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9393: 	    &displayPage($request,$symb);
1.104     albertel 9394: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9395:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9396:                                        {href=>'',text=>'Select student'},
                   9397:                                        {href=>'',text=>'Grade student'},
                   9398:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9399: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9400: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9401:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9402:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9403: 	    &processGroup($request,$symb);
1.104     albertel 9404: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9405:             &startpage($request,$symb);
                   9406: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9407: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9408:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9409: 	    $request->print(&submit_options($request,$symb));
1.598     www      9410:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9411:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9412:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9413:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9414:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9415:             $request->print(&submit_options_table($request,$symb));
1.598     www      9416:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9417:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9418:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9419: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9420:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9421: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9422: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9423:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9424:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9425: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9426: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9427:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9428:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9429:                                                                              text=>"Modify grades"},
                   9430:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9431: 	    $request->print(&editgrades($request,$symb));
1.602     www      9432:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9433:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9434:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9435: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9436:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9437:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9438: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9439:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9440:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9441:             $request->print(&process_clicker($request,$symb));
1.400     www      9442:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9443:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9444:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9445:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9446:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9447:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9448:                                        {href=>'', text=>'Process clicker file'},
                   9449:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9450:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9451: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9452:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9453: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9454: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9455:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9456: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9457: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9458:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9459: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9460: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9461: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9462:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9463: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9464: 	    } else {
1.257     albertel 9465: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9466: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9467: 		} else {
1.257     albertel 9468: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9469: 		}
1.627     www      9470:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9471: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9472: 	    }
1.246     albertel 9473: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9474:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9475: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9476: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9477:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9478: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9479:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9480:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9481:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9482: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9483:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9484: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9485: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9486:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9487: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9488:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9489:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9490: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9491:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9492:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9493:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9494:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9495: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9496:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9497:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9498:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9499: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9500:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9501:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9502:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9503:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9504:             $request->print(&checkscantron_results($request,$symb));
                   9505:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9506:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9507:             $request->print(&submit_options_download($request,$symb));
                   9508:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9509:             &startpage($request,$symb,
                   9510:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9511:     {href=>'', text=>'Download submissions'}]);
                   9512:             &submit_download_link($request,$symb);
1.106     albertel 9513: 	} elsif ($command) {
1.620     www      9514:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9515: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9516: 	}
1.2       albertel 9517:     }
1.513     foxr     9518:     if ($ssi_error) {
                   9519: 	&ssi_print_error($request);
                   9520:     }
1.639     www      9521:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9522:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9523:     &reset_caches();
1.646     raeburn  9524:     return OK;
1.44      ng       9525: }
                   9526: 
1.1       albertel 9527: 1;
                   9528: 
1.13      albertel 9529: __END__;
1.531     jms      9530: 
                   9531: 
                   9532: =head1 NAME
                   9533: 
                   9534: Apache::grades
                   9535: 
                   9536: =head1 SYNOPSIS
                   9537: 
                   9538: Handles the viewing of grades.
                   9539: 
                   9540: This is part of the LearningOnline Network with CAPA project
                   9541: described at http://www.lon-capa.org.
                   9542: 
                   9543: =head1 OVERVIEW
                   9544: 
                   9545: Do an ssi with retries:
                   9546: While I'd love to factor out this with the vesrion in lonprintout,
                   9547: 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
                   9548: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9549: 
                   9550: At least the logic that drives this has been pulled out into loncommon.
                   9551: 
                   9552: 
                   9553: 
                   9554: ssi_with_retries - Does the server side include of a resource.
                   9555:                      if the ssi call returns an error we'll retry it up to
                   9556:                      the number of times requested by the caller.
                   9557:                      If we still have a proble, no text is appended to the
                   9558:                      output and we set some global variables.
                   9559:                      to indicate to the caller an SSI error occurred.  
                   9560:                      All of this is supposed to deal with the issues described
                   9561:                      in LonCAPA BZ 5631 see:
                   9562:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9563:                      by informing the user that this happened.
                   9564: 
                   9565: Parameters:
                   9566:   resource   - The resource to include.  This is passed directly, without
                   9567:                interpretation to lonnet::ssi.
                   9568:   form       - The form hash parameters that guide the interpretation of the resource
                   9569:                
                   9570:   retries    - Number of retries allowed before giving up completely.
                   9571: Returns:
                   9572:   On success, returns the rendered resource identified by the resource parameter.
                   9573: Side Effects:
                   9574:   The following global variables can be set:
                   9575:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9576:                               It is up to the caller to initialize this to false
                   9577:                               if desired.
                   9578:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9579:                               of the resource that could not be rendered by the ssi
                   9580:                               call.
                   9581:    ssi_error_message   - The error string fetched from the ssi response
                   9582:                               in the event of an error.
                   9583: 
                   9584: 
                   9585: =head1 HANDLER SUBROUTINE
                   9586: 
                   9587: ssi_with_retries()
                   9588: 
                   9589: =head1 SUBROUTINES
                   9590: 
                   9591: =over
                   9592: 
                   9593: =item scantron_get_correction() : 
                   9594: 
                   9595:    Builds the interface screen to interact with the operator to fix a
                   9596:    specific error condition in a specific scanline
                   9597: 
                   9598:  Arguments:
                   9599:     $r           - Apache request object
                   9600:     $i           - number of the current scanline
                   9601:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9602:     $scan_config - hash ref as returned from &get_scantron_config()
                   9603:     $line        - full contents of the current scanline
                   9604:     $error       - error condition, valid values are
                   9605:                    'incorrectCODE', 'duplicateCODE',
                   9606:                    'doublebubble', 'missingbubble',
                   9607:                    'duplicateID', 'incorrectID'
                   9608:     $arg         - extra information needed
                   9609:        For errors:
                   9610:          - duplicateID   - paper number that this studentID was seen before on
                   9611:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9612:                            seen on before
                   9613:          - incorrectCODE - current incorrect CODE 
                   9614:          - doublebubble  - array ref of the bubble lines that have double
                   9615:                            bubble errors
                   9616:          - missingbubble - array ref of the bubble lines that have missing
                   9617:                            bubble errors
                   9618: 
                   9619: =item  scantron_get_maxbubble() : 
                   9620: 
1.582     raeburn  9621:    Arguments:
                   9622:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9623:                       failure to retrieve a navmap object.
                   9624:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9625:        calling routine should trap the error condition and display the warning
                   9626:        found in &navmap_errormsg().
                   9627: 
1.649     raeburn  9628:        $scantron_config - Reference to bubblesheet format configuration hash.
                   9629: 
1.531     jms      9630:    Returns the maximum number of bubble lines that are expected to
                   9631:    occur. Does this by walking the selected sequence rendering the
                   9632:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9633:    for what the current value of the problem counter is.
                   9634: 
                   9635:    Caches the results to $env{'form.scantron_maxbubble'},
                   9636:    $env{'form.scantron.bubble_lines.n'}, 
                   9637:    $env{'form.scantron.first_bubble_line.n'} and
                   9638:    $env{"form.scantron.sub_bubblelines.n"}
                   9639:    which are the total number of bubble, lines, the number of bubble
                   9640:    lines for response n and number of the first bubble line for response n,
                   9641:    and a comma separated list of numbers of bubble lines for sub-questions
                   9642:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9643: 
                   9644: 
                   9645: =item  scantron_validate_missingbubbles() : 
                   9646: 
                   9647:    Validates all scanlines in the selected file to not have any
                   9648:     answers that don't have bubbles that have not been verified
                   9649:     to be bubble free.
                   9650: 
                   9651: =item  scantron_process_students() : 
                   9652: 
1.659     raeburn  9653:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      9654: 
                   9655:    The parsed scanline hash is added to %env 
                   9656: 
                   9657:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9658:    foreach resource , with the form data of
                   9659: 
                   9660: 	'submitted'     =>'scantron' 
                   9661: 	'grade_target'  =>'grade',
                   9662: 	'grade_username'=> username of student
                   9663: 	'grade_domain'  => domain of student
                   9664: 	'grade_courseid'=> of course
                   9665: 	'grade_symb'    => symb of resource to grade
                   9666: 
                   9667:     This triggers a grading pass. The problem grading code takes care
                   9668:     of converting the bubbled letter information (now in %env) into a
                   9669:     valid submission.
                   9670: 
                   9671: =item  scantron_upload_scantron_data() :
                   9672: 
1.659     raeburn  9673:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      9674: 
                   9675: =item  scantron_upload_scantron_data_save() : 
                   9676: 
                   9677:    Adds a provided bubble information data file to the course if user
                   9678:    has the correct privileges to do so. 
                   9679: 
                   9680: =item  valid_file() :
                   9681: 
                   9682:    Validates that the requested bubble data file exists in the course.
                   9683: 
                   9684: =item  scantron_download_scantron_data() : 
                   9685: 
                   9686:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  9687:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      9688:    course.
                   9689: 
                   9690: =item  scantron_validate_ID() : 
                   9691: 
                   9692:    Validates all scanlines in the selected file to not have any
1.556     weissno  9693:    invalid or underspecified student/employee IDs
1.531     jms      9694: 
1.582     raeburn  9695: =item navmap_errormsg() :
                   9696: 
                   9697:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9698:    Should be called whenever the request to instantiate a navmap object fails.  
                   9699: 
1.531     jms      9700: =back
                   9701: 
                   9702: =cut

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