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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.659   ! raeburn     4: # $Id: grades.pm,v 1.658 2011/10/10 10:13:17 bisitz 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.148     albertel  344: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    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.148     albertel  366: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    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.597     wenzelju  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',
                   2030:                           high => 'Hightlight Attribute',
                   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;
                   2908: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2909: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2910:                     # fix file name
                   2911:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2912:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  2913:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 2914:             	                                $save_file_name);
1.337     banghart 2915:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2916:                         $request->print('<br /><span class="LC_error">'.
                   2917:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  2918:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  2919:                                         '</span>');
1.356     banghart 2920:                     } else {
1.360     banghart 2921:                         # mark the file as read only
1.654     raeburn  2922:                         push(@handedback,$save_file_name);
1.367     albertel 2923: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2924: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2925: 			}
                   2926:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  2927: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 2928:                     }
1.654     raeburn  2929:                     $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 2930:                 }
                   2931:             }
                   2932:         }
1.654     raeburn  2933:     }
                   2934:     if (@handedback > 0) {
                   2935:         $request->print('<br />');
                   2936:         my @what = ($symb,$env{'request.course.id'},'handback');
                   2937:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   2938:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   2939:         my ($subject,$message);
                   2940:         if (scalar(@handedback) == 1) {
                   2941:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   2942:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   2943:         } else {
                   2944:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   2945:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   2946:         }
                   2947:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   2948:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   2949:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   2950:         my ($feedurl,$showsymb) =
                   2951:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   2952:         my $restitle = &Apache::lonnet::gettitle($symb);
                   2953:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   2954:         my $msgstatus =
                   2955:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   2956:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   2957:                  $restitle);
                   2958:         if ($msgstatus) {
                   2959:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   2960:         }
                   2961:     }
1.338     banghart 2962:     return;
1.337     banghart 2963: }
                   2964: 
1.418     albertel 2965: sub get_feedurl_and_symb {
                   2966:     my ($symb,$uname,$udom) = @_;
                   2967:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2968:     $url = &Apache::lonnet::clutter($url);
                   2969:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2970: 					$symb,$udom,$uname);
                   2971:     if ($encrypturl =~ /^yes$/i) {
                   2972: 	&Apache::lonenc::encrypted(\$url,1);
                   2973: 	&Apache::lonenc::encrypted(\$symb,1);
                   2974:     }
                   2975:     return ($url,$symb);
                   2976: }
                   2977: 
1.313     banghart 2978: sub get_submitted_files {
                   2979:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2980:     my @files;
                   2981:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2982:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2983:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2984:     	    push(@files,$file_url.$file);
                   2985:         }
                   2986:     }
                   2987:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2988:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2989:     }
                   2990:     return (\@files);
                   2991: }
1.322     albertel 2992: 
1.269     raeburn  2993: # ----------- Provides number of tries since last reset.
                   2994: sub get_num_tries {
                   2995:     my ($record,$last_reset,$part) = @_;
                   2996:     my $timestamp = '';
                   2997:     my $num_tries = 0;
                   2998:     if ($$record{'version'}) {
                   2999:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3000:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3001:                 $timestamp = $$record{$version.':timestamp'};
                   3002:                 if ($timestamp > $last_reset) {
                   3003:                     $num_tries ++;
                   3004:                 } else {
                   3005:                     last;
                   3006:                 }
                   3007:             }
                   3008:         }
                   3009:     }
                   3010:     return $num_tries;
                   3011: }
                   3012: 
                   3013: # ----------- Determine decrements required in aggregate totals 
                   3014: sub decrement_aggs {
                   3015:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3016:     my %decrement = (
                   3017:                         attempts => 0,
                   3018:                         users => 0,
                   3019:                         correct => 0
                   3020:                     );
                   3021:     $decrement{'attempts'} = $aggtries;
                   3022:     if ($solvedstatus =~ /^correct/) {
                   3023:         $decrement{'correct'} = 1;
                   3024:     }
                   3025:     if ($aggtries == $totaltries) {
                   3026:         $decrement{'users'} = 1;
                   3027:     }
1.524     raeburn  3028:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3029:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3030:     }
                   3031:     return;
                   3032: }
                   3033: 
                   3034: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3035: sub get_last_resets {
1.270     albertel 3036:     my ($symb,$courseid,$partids) =@_;
                   3037:     my %last_resets;
1.269     raeburn  3038:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3039:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3040:     my @keys;
                   3041:     foreach my $part (@{$partids}) {
                   3042: 	push(@keys,"$symb\0$part\0resettime");
                   3043:     }
                   3044:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3045: 				     $cdom,$cname);
                   3046:     foreach my $part (@{$partids}) {
                   3047: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3048:     }
1.270     albertel 3049:     return %last_resets;
1.269     raeburn  3050: }
                   3051: 
1.251     banghart 3052: # ----------- Handles creating versions for portfolio files as answers
                   3053: sub version_portfiles {
1.343     banghart 3054:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3055:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3056:     my @returned_keys;
1.255     banghart 3057:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3058:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3059:     foreach my $key (keys(%$record)) {
1.259     banghart 3060:         my $new_portfiles;
1.263     banghart 3061:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3062:             my @versioned_portfiles;
1.367     albertel 3063:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3064:             foreach my $file (@portfiles) {
1.306     banghart 3065:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3066:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3067: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3068: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3069:                 my $getpropath = 1;    
                   3070:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3071:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3072:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3073:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3074:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3075:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3076:                         [$directory.$new_answer],
1.306     banghart 3077:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3078:                 }
1.252     banghart 3079:             }
1.343     banghart 3080:             $$record{$key} = join(',',@versioned_portfiles);
                   3081:             push(@returned_keys,$key);
1.251     banghart 3082:         }
                   3083:     } 
1.343     banghart 3084:     return (@returned_keys);   
1.305     banghart 3085: }
                   3086: 
1.307     banghart 3087: sub get_next_version {
1.341     banghart 3088:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3089:     my $version;
                   3090:     foreach my $row (@$dir_list) {
                   3091:         my ($file) = split(/\&/,$row,2);
                   3092:         my ($file_name,$file_version,$file_ext) =
                   3093: 	    &file_name_version_ext($file);
                   3094:         if (($file_name eq $answer_name) && 
                   3095: 	    ($file_ext eq $answer_ext)) {
                   3096:                 # gets here if filename and extension match, regardless of version
                   3097:                 if ($file_version ne '') {
                   3098:                 # a versioned file is found  so save it for later
                   3099:                 if ($file_version > $version) {
                   3100: 		    $version = $file_version;
                   3101: 	        }
                   3102:             }
                   3103:         }
                   3104:     } 
                   3105:     $version ++;
                   3106:     return($version);
                   3107: }
                   3108: 
1.305     banghart 3109: sub version_selected_portfile {
1.306     banghart 3110:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3111:     my ($answer_name,$answer_ver,$answer_ext) =
                   3112:         &file_name_version_ext($file_name);
                   3113:     my $new_answer;
                   3114:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3115:     if($env{'form.copy'} eq '-1') {
                   3116:         $new_answer = 'problem getting file';
                   3117:     } else {
                   3118:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3119:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3120:                             $stu_name,$domain,'copy',
                   3121: 		        '/portfolio'.$directory.$new_answer);
                   3122:     }    
                   3123:     return ($new_answer);
1.251     banghart 3124: }
                   3125: 
1.304     albertel 3126: sub file_name_version_ext {
                   3127:     my ($file)=@_;
                   3128:     my @file_parts = split(/\./, $file);
                   3129:     my ($name,$version,$ext);
                   3130:     if (@file_parts > 1) {
                   3131: 	$ext=pop(@file_parts);
                   3132: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3133: 	    $version=pop(@file_parts);
                   3134: 	}
                   3135: 	$name=join('.',@file_parts);
                   3136:     } else {
                   3137: 	$name=join('.',@file_parts);
                   3138:     }
                   3139:     return($name,$version,$ext);
                   3140: }
                   3141: 
1.44      ng       3142: #--------------------------------------------------------------------------------------
                   3143: #
                   3144: #-------------------------- Next few routines handles grading by section or whole class
                   3145: #
                   3146: #--- Javascript to handle grading by section or whole class
1.42      ng       3147: sub viewgrades_js {
                   3148:     my ($request) = shift;
                   3149: 
1.539     riegler  3150:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3151:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3152:    function writePoint(partid,weight,point) {
1.125     ng       3153: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3154: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3155: 	if (point == "textval") {
1.125     ng       3156: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3157: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3158: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3159: 		var resetbox = false;
                   3160: 		for (var i=0; i<radioButton.length; i++) {
                   3161: 		    if (radioButton[i].checked) {
                   3162: 			textbox.value = i;
                   3163: 			resetbox = true;
                   3164: 		    }
                   3165: 		}
                   3166: 		if (!resetbox) {
                   3167: 		    textbox.value = "";
                   3168: 		}
                   3169: 		return;
                   3170: 	    }
1.109     matthew  3171: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3172: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3173: 				   ") greater than the weight for the part. Accept?");
                   3174: 		if (resp == false) {
                   3175: 		    textbox.value = "";
                   3176: 		    return;
                   3177: 		}
                   3178: 	    }
1.42      ng       3179: 	    for (var i=0; i<radioButton.length; i++) {
                   3180: 		radioButton[i].checked=false;
1.109     matthew  3181: 		if (parseFloat(point) == i) {
1.42      ng       3182: 		    radioButton[i].checked=true;
                   3183: 		}
                   3184: 	    }
1.41      ng       3185: 
1.42      ng       3186: 	} else {
1.125     ng       3187: 	    textbox.value = parseFloat(point);
1.42      ng       3188: 	}
1.41      ng       3189: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3190: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3191: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3192: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3193: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3194: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3195: 	    if (saveval != "correct") {
                   3196: 		scorename.value = point;
1.43      ng       3197: 		if (selname[0].selected != true) {
                   3198: 		    selname[0].selected = true;
                   3199: 		}
1.42      ng       3200: 	    }
                   3201: 	}
1.125     ng       3202: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3203:     }
                   3204: 
                   3205:     function writeRadText(partid,weight) {
1.125     ng       3206: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3207: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3208:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3209: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3210: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3211: 	    for (var i=0; i<radioButton.length; i++) {
                   3212: 		radioButton[i].checked=false;
                   3213: 
                   3214: 	    }
                   3215: 	    textbox.value = "";
                   3216: 
                   3217: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3218: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3219: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3220: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3221: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3222: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3223: 		if ((saveval != "correct") || override) {
1.42      ng       3224: 		    scorename.value = "";
1.125     ng       3225: 		    if (selval[1].selected) {
                   3226: 			selname[1].selected = true;
                   3227: 		    } else {
                   3228: 			selname[2].selected = true;
                   3229: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3230: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3231: 		    }
1.42      ng       3232: 		}
                   3233: 	    }
1.43      ng       3234: 	} else {
                   3235: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3236: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3237: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3238: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3239: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3240: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3241: 		if ((saveval != "correct") || override) {
1.125     ng       3242: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3243: 		    selname[0].selected = true;
                   3244: 		}
                   3245: 	    }
                   3246: 	}	    
1.42      ng       3247:     }
                   3248: 
                   3249:     function changeSelect(partid,user) {
1.125     ng       3250: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3251: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3252: 	var point  = textbox.value;
1.125     ng       3253: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3254: 
1.109     matthew  3255: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3256: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3257: 	    textbox.value = "";
                   3258: 	    return;
                   3259: 	}
1.109     matthew  3260: 	if (parseFloat(point) > parseFloat(weight)) {
                   3261: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3262: 			       ") greater than the weight of the part. Accept?");
                   3263: 	    if (resp == false) {
                   3264: 		textbox.value = "";
                   3265: 		return;
                   3266: 	    }
                   3267: 	}
1.42      ng       3268: 	selval[0].selected = true;
                   3269:     }
                   3270: 
                   3271:     function changeOneScore(partid,user) {
1.125     ng       3272: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3273: 	if (selval[1].selected || selval[2].selected) {
                   3274: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3275: 	    if (selval[2].selected) {
                   3276: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3277: 	    }
1.269     raeburn  3278:         }
1.42      ng       3279:     }
                   3280: 
                   3281:     function resetEntry(numpart) {
                   3282: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3283: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3284: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3285: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3286: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3287: 	    for (var i=0; i<radioButton.length; i++) {
                   3288: 		radioButton[i].checked=false;
                   3289: 
                   3290: 	    }
                   3291: 	    textbox.value = "";
                   3292: 	    selval[0].selected = true;
                   3293: 
                   3294: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3295: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3296: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3297: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3298: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3299: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3300: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3301: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3302: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3303: 		if (saveselval == "excused") {
1.43      ng       3304: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3305: 		} else {
1.43      ng       3306: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3307: 		}
                   3308: 	    }
1.41      ng       3309: 	}
1.42      ng       3310:     }
                   3311: 
1.41      ng       3312: VIEWJAVASCRIPT
1.42      ng       3313: }
                   3314: 
1.44      ng       3315: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3316: sub viewgrades {
1.608     www      3317:     my ($request,$symb) = @_;
1.42      ng       3318:     &viewgrades_js($request);
1.41      ng       3319: 
1.168     albertel 3320:     #need to make sure we have the correct data for later EXT calls, 
                   3321:     #thus invalidate the cache
                   3322:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3323:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3324:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3325:     &Apache::lonnet::clear_EXT_cache_status();
                   3326: 
1.398     albertel 3327:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3328: 
                   3329:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3330:     $result.=&jscriptNform($symb);
1.41      ng       3331: 
1.44      ng       3332:     #beginning of class grading form
1.442     banghart 3333:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3334:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3335: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3336: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3337: 	&build_section_inputs().
1.442     banghart 3338: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3339: 
1.560     raeburn  3340:     my ($common_header,$specific_header);
1.257     albertel 3341:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3342: 	$common_header = &mt('Assign Common Grade to Class');
                   3343:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3344:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3345:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3346: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3347:     } else {
1.560     raeburn  3348:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3349:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3350: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3351:     }
1.560     raeburn  3352:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3353:     #radio buttons/text box for assigning points for a section or class.
                   3354:     #handles different parts of a problem
1.582     raeburn  3355:     my $res_error;
                   3356:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3357:     if ($res_error) {
                   3358:         return &navmap_errormsg();
                   3359:     }
1.42      ng       3360:     my %weight = ();
                   3361:     my $ctsparts = 0;
1.45      ng       3362:     my %seen = ();
1.375     albertel 3363:     my @part_response_id = &flatten_responseType($responseType);
                   3364:     foreach my $part_response_id (@part_response_id) {
                   3365:     	my ($partid,$respid) = @{ $part_response_id };
                   3366: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3367: 	next if $seen{$partid};
                   3368: 	$seen{$partid}++;
1.375     albertel 3369: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3370: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3371: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3372: 
1.324     albertel 3373: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3374: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3375: 	my $ctr = 0;
1.42      ng       3376: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3377: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3378: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3379: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3380: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3381: 	    $ctr++;
                   3382: 	}
1.485     albertel 3383: 	$radio.='</tr></table>';
                   3384: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3385: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3386: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3387: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3388: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3389: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3390: 		$weight{$partid}.')"> '.
1.401     albertel 3391: 	    '<option selected="selected"> </option>'.
1.485     albertel 3392: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3393: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3394: 	    '</select></td>'.
                   3395:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3396: 	$line.='<input type="hidden" name="partid_'.
                   3397: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3398: 	$line.='<input type="hidden" name="weight_'.
                   3399: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3400: 
                   3401: 	$result.=
                   3402: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3403: 	    '<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 3404: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3405: 	$ctsparts++;
1.41      ng       3406:     }
1.474     albertel 3407:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3408: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3409:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3410: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3411: 
1.44      ng       3412:     #table listing all the students in a section/class
                   3413:     #header of table
1.560     raeburn  3414:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3415:               &Apache::loncommon::start_data_table().
                   3416: 	      &Apache::loncommon::start_data_table_header_row().
                   3417: 	      '<th>'.&mt('No.').'</th>'.
                   3418: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3419:     my $partserror;
                   3420:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3421:     if ($partserror) {
                   3422:         return &navmap_errormsg();
                   3423:     }
1.324     albertel 3424:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3425:     my @partids = ();
1.41      ng       3426:     foreach my $part (@parts) {
                   3427: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3428:         my $narrowtext = &mt('Tries');
                   3429: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3430: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3431: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3432:         push(@partids,$partid);
1.628     www      3433: #
                   3434: # FIXME: Looks like $display looks at English text
                   3435: #
1.324     albertel 3436: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3437: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3438: 	    $result.='<th>'.
                   3439: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3440: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3441: 	    next;
1.485     albertel 3442: 	    
1.207     albertel 3443: 	} else {
1.485     albertel 3444: 	    if ($display =~ /Problem Status/) {
                   3445: 		my $grade_status_mt = &mt('Grade Status');
                   3446: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3447: 	    }
                   3448: 	    my $part_mt = &mt('Part:');
                   3449: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3450: 	}
1.485     albertel 3451: 
1.474     albertel 3452: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3453:     }
1.474     albertel 3454:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3455: 
1.270     albertel 3456:     my %last_resets = 
                   3457: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3458: 
1.41      ng       3459:     #get info for each student
1.44      ng       3460:     #list all the students - with points and grade status
1.257     albertel 3461:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3462:     my $ctr = 0;
1.294     albertel 3463:     foreach (sort 
                   3464: 	     {
                   3465: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3466: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3467: 		 }
                   3468: 		 return $a cmp $b;
                   3469: 	     } (keys(%$fullname))) {
1.126     ng       3470: 	$ctr++;
1.324     albertel 3471: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3472: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3473:     }
1.474     albertel 3474:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3475:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3476:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3477: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3478:     if (scalar(%$fullname) eq 0) {
                   3479: 	my $colspan=3+scalar(@parts);
1.433     banghart 3480: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3481:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3482: 	$result='<span class="LC_warning">'.
1.485     albertel 3483: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3484: 	        $section_display, $stu_status).
1.433     banghart 3485: 	    '</span>';
1.96      albertel 3486:     }
1.41      ng       3487:     return $result;
                   3488: }
                   3489: 
1.44      ng       3490: #--- call by previous routine to display each student
1.41      ng       3491: sub viewstudentgrade {
1.324     albertel 3492:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3493:     my ($uname,$udom) = split(/:/,$student);
                   3494:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3495:     my %aggregates = (); 
1.474     albertel 3496:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3497: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3498: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3499: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3500: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3501: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3502:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3503:     foreach my $apart (@$parts) {
                   3504: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3505: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3506:         $result.='<td align="center">';
1.269     raeburn  3507:         my ($aggtries,$totaltries);
                   3508:         unless (exists($aggregates{$part})) {
1.270     albertel 3509: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3510: 
                   3511: 	    $aggtries = $totaltries;
1.269     raeburn  3512:             if ($$last_resets{$part}) {  
1.270     albertel 3513:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3514: 					   $part);
                   3515:             }
1.269     raeburn  3516:             $result.='<input type="hidden" name="'.
                   3517:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3518:             $result.='<input type="hidden" name="'.
                   3519:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3520:             $aggregates{$part} = 1;
                   3521:         }
1.41      ng       3522: 	if ($type eq 'awarded') {
1.320     albertel 3523: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3524: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3525: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3526: 	    $result.='<input type="text" name="'.
1.89      albertel 3527: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3528:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3529: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3530: 	} elsif ($type eq 'solved') {
                   3531: 	    my ($status,$foo)=split(/_/,$score,2);
                   3532: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3533: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3534: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3535: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3536: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3537:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3538: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3539: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3540: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3541: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3542: 	} else {
                   3543: 	    $result.='<input type="hidden" name="'.
                   3544: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3545: 		    "\n";
1.233     albertel 3546: 	    $result.='<input type="text" name="'.
1.122     ng       3547: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3548: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3549: 	}
                   3550:     }
1.474     albertel 3551:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3552:     return $result;
1.38      ng       3553: }
                   3554: 
1.44      ng       3555: #--- change scores for all the students in a section/class
                   3556: #    record does not get update if unchanged
1.38      ng       3557: sub editgrades {
1.608     www      3558:     my ($request,$symb) = @_;
1.41      ng       3559: 
1.433     banghart 3560:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3561:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3562:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3563: 
1.477     albertel 3564:     my $result= &Apache::loncommon::start_data_table().
                   3565: 	&Apache::loncommon::start_data_table_header_row().
                   3566: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3567: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3568:     my %scoreptr = (
                   3569: 		    'correct'  =>'correct_by_override',
                   3570: 		    'incorrect'=>'incorrect_by_override',
                   3571: 		    'excused'  =>'excused',
                   3572: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3573:                     'credited' =>'credit_attempted',
1.43      ng       3574: 		    'nothing'  => '',
                   3575: 		    );
1.257     albertel 3576:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3577: 
1.44      ng       3578:     my (@partid);
                   3579:     my %weight = ();
1.54      albertel 3580:     my %columns = ();
1.44      ng       3581:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3582: 
1.582     raeburn  3583:     my $partserror;
                   3584:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3585:     if ($partserror) {
                   3586:         return &navmap_errormsg();
                   3587:     }
1.54      albertel 3588:     my $header;
1.257     albertel 3589:     while ($ctr < $env{'form.totalparts'}) {
                   3590: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3591: 	push(@partid,$partid);
1.257     albertel 3592: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3593: 	$ctr++;
1.54      albertel 3594:     }
1.324     albertel 3595:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3596:     foreach my $partid (@partid) {
1.478     albertel 3597: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3598: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3599: 	$columns{$partid}=2;
                   3600: 	foreach my $stores (@parts) {
                   3601: 	    my ($part,$type) = &split_part_type($stores);
                   3602: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3603: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3604: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3605: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3606:             my $narrowtext = &mt('Tries');
                   3607: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3608: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3609: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3610: 	    $columns{$partid}+=2;
                   3611: 	}
                   3612:     }
                   3613:     foreach my $partid (@partid) {
1.324     albertel 3614: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3615: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3616: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3617: 	    '</th>';
1.54      albertel 3618: 
1.44      ng       3619:     }
1.477     albertel 3620:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3621: 	&Apache::loncommon::start_data_table_header_row().
                   3622: 	$header.
                   3623: 	&Apache::loncommon::end_data_table_header_row();
                   3624:     my @noupdate;
1.126     ng       3625:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3626:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3627: 	my $line;
1.257     albertel 3628: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3629: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3630: 	my %newrecord;
                   3631: 	my $updateflag = 0;
1.281     albertel 3632: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3633: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3634: 	if (!&canmodify($usec)) {
1.126     ng       3635: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3636: 	    push(@noupdate,
1.478     albertel 3637: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3638: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3639: 	    next;
                   3640: 	}
1.269     raeburn  3641:         my %aggregate = ();
                   3642:         my $aggregateflag = 0;
1.281     albertel 3643: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3644: 	foreach (@partid) {
1.257     albertel 3645: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3646: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3647: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3648: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3649: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3650: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3651: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3652: 	    my $score;
                   3653: 	    if ($partial eq '') {
1.257     albertel 3654: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3655: 	    } elsif ($partial > 0) {
                   3656: 		$score = 'correct_by_override';
                   3657: 	    } elsif ($partial == 0) {
                   3658: 		$score = 'incorrect_by_override';
                   3659: 	    }
1.257     albertel 3660: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3661: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3662: 
1.292     albertel 3663: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3664: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3665: 	    if ($dropMenu eq 'reset status' &&
                   3666: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3667: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3668: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3669: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3670: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3671: 		$updateflag = 1;
1.269     raeburn  3672:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3673:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3674:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3675:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3676:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3677:                     $aggregateflag = 1;
                   3678:                 }
1.139     albertel 3679: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3680: 		$updateflag = 1;
                   3681: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3682: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3683: 		$rec_update++;
1.125     ng       3684: 	    }
                   3685: 
1.93      albertel 3686: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3687: 		'<td align="center">'.$awarded.
                   3688: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3689: 
1.54      albertel 3690: 
                   3691: 	    my $partid=$_;
                   3692: 	    foreach my $stores (@parts) {
                   3693: 		my ($part,$type) = &split_part_type($stores);
                   3694: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3695: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3696: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3697: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3698: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3699: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3700: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3701: 		    $updateflag=1;
                   3702: 		}
1.93      albertel 3703: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3704: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3705: 	    }
1.44      ng       3706: 	}
1.477     albertel 3707: 	$line.="\n";
1.301     albertel 3708: 
                   3709: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3710: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3711: 
1.44      ng       3712: 	if ($updateflag) {
                   3713: 	    $count++;
1.257     albertel 3714: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3715: 				    $udom,$uname);
1.301     albertel 3716: 
                   3717: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3718: 					      $cnum,$udom,$uname)) {
                   3719: 		# need to figure out if should be in queue.
                   3720: 		my %record =  
                   3721: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3722: 					     $udom,$uname);
                   3723: 		my $all_graded = 1;
                   3724: 		my $none_graded = 1;
                   3725: 		foreach my $part (@parts) {
                   3726: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3727: 			$all_graded = 0;
                   3728: 		    } else {
                   3729: 			$none_graded = 0;
                   3730: 		    }
                   3731: 		}
                   3732: 
                   3733: 		if ($all_graded || $none_graded) {
                   3734: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3735: 							   $symb,$cdom,$cnum,
                   3736: 							   $udom,$uname);
                   3737: 		}
                   3738: 	    }
                   3739: 
1.477     albertel 3740: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3741: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3742: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3743: 	    $updateCtr++;
1.93      albertel 3744: 	} else {
1.477     albertel 3745: 	    push(@noupdate,
                   3746: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3747: 	    $noupdateCtr++;
1.44      ng       3748: 	}
1.269     raeburn  3749:         if ($aggregateflag) {
                   3750:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3751: 				  $cdom,$cnum);
1.269     raeburn  3752:         }
1.93      albertel 3753:     }
1.477     albertel 3754:     if (@noupdate) {
1.126     ng       3755: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3756: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3757: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3758: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3759: 	    &mt('No Changes Occurred For the Students Below').
                   3760: 	    '</td>'.
1.477     albertel 3761: 	    &Apache::loncommon::end_data_table_row();
                   3762: 	foreach my $line (@noupdate) {
                   3763: 	    $result.=
                   3764: 		&Apache::loncommon::start_data_table_row().
                   3765: 		$line.
                   3766: 		&Apache::loncommon::end_data_table_row();
                   3767: 	}
1.44      ng       3768:     }
1.614     www      3769:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3770:     my $msg = '<p><b>'.
                   3771: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3772: 	    $rec_update,$count).'</b><br />'.
                   3773: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3774: 	'</b></p>';
1.44      ng       3775:     return $title.$msg.$result;
1.5       albertel 3776: }
1.54      albertel 3777: 
                   3778: sub split_part_type {
                   3779:     my ($partstr) = @_;
                   3780:     my ($temp,@allparts)=split(/_/,$partstr);
                   3781:     my $type=pop(@allparts);
1.439     albertel 3782:     my $part=join('_',@allparts);
1.54      albertel 3783:     return ($part,$type);
                   3784: }
                   3785: 
1.44      ng       3786: #------------- end of section for handling grading by section/class ---------
                   3787: #
                   3788: #----------------------------------------------------------------------------
                   3789: 
1.5       albertel 3790: 
1.44      ng       3791: #----------------------------------------------------------------------------
                   3792: #
                   3793: #-------------------------- Next few routines handles grading by csv upload
                   3794: #
                   3795: #--- Javascript to handle csv upload
1.27      albertel 3796: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3797:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3798:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3799:   return(<<ENDPICK);
                   3800:   function verify(vf) {
                   3801:     var foundsomething=0;
                   3802:     var founduname=0;
1.243     albertel 3803:     var foundID=0;
1.27      albertel 3804:     for (i=0;i<=vf.nfields.value;i++) {
                   3805:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3806:       if (i==0 && tw!=0) { foundID=1; }
                   3807:       if (i==1 && tw!=0) { founduname=1; }
                   3808:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3809:     }
1.246     albertel 3810:     if (founduname==0 && foundID==0) {
                   3811: 	alert('$error1');
                   3812: 	return;
1.27      albertel 3813:     }
                   3814:     if (foundsomething==0) {
1.246     albertel 3815: 	alert('$error2');
                   3816: 	return;
1.27      albertel 3817:     }
                   3818:     vf.submit();
                   3819:   }
                   3820:   function flip(vf,tf) {
                   3821:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3822:     var i;
                   3823:     for (i=0;i<=vf.nfields.value;i++) {
                   3824:       //can not pick the same destination field for both name and domain
                   3825:       if (((i ==0)||(i ==1)) && 
                   3826:           ((tf==0)||(tf==1)) && 
                   3827:           (i!=tf) &&
                   3828:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3829:         eval('vf.f'+i+'.selectedIndex=0;')
                   3830:       }
                   3831:     }
                   3832:   }
                   3833: ENDPICK
                   3834: }
                   3835: 
                   3836: sub csvupload_javascript_forward_associate {
1.573     bisitz   3837:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3838:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3839:   return(<<ENDPICK);
                   3840:   function verify(vf) {
                   3841:     var foundsomething=0;
                   3842:     var founduname=0;
1.243     albertel 3843:     var foundID=0;
1.27      albertel 3844:     for (i=0;i<=vf.nfields.value;i++) {
                   3845:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3846:       if (tw==1) { foundID=1; }
                   3847:       if (tw==2) { founduname=1; }
                   3848:       if (tw>3) { foundsomething=1; }
1.27      albertel 3849:     }
1.246     albertel 3850:     if (founduname==0 && foundID==0) {
                   3851: 	alert('$error1');
                   3852: 	return;
1.27      albertel 3853:     }
                   3854:     if (foundsomething==0) {
1.246     albertel 3855: 	alert('$error2');
                   3856: 	return;
1.27      albertel 3857:     }
                   3858:     vf.submit();
                   3859:   }
                   3860:   function flip(vf,tf) {
                   3861:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3862:     var i;
                   3863:     //can not pick the same destination field twice
                   3864:     for (i=0;i<=vf.nfields.value;i++) {
                   3865:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3866:         eval('vf.f'+i+'.selectedIndex=0;')
                   3867:       }
                   3868:     }
                   3869:   }
                   3870: ENDPICK
                   3871: }
                   3872: 
1.26      albertel 3873: sub csvuploadmap_header {
1.324     albertel 3874:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3875:     my $javascript;
1.257     albertel 3876:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3877: 	$javascript=&csvupload_javascript_reverse_associate();
                   3878:     } else {
                   3879: 	$javascript=&csvupload_javascript_forward_associate();
                   3880:     }
1.45      ng       3881: 
1.418     albertel 3882:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      3883:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   3884:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   3885:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   3886:     my $reverse=&mt("Reverse Association");
1.41      ng       3887:     $request->print(<<ENDPICK);
1.632     www      3888: <br />
                   3889: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3890: <input type="hidden" name="associate"  value="" />
                   3891: <input type="hidden" name="phase"      value="three" />
                   3892: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3893: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3894: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3895: <input type="hidden" name="upfile_associate" 
1.257     albertel 3896:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3897: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3898: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3899: <hr />
                   3900: ENDPICK
1.597     wenzelju 3901:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3902:     return '';
1.26      albertel 3903: 
                   3904: }
                   3905: 
                   3906: sub csvupload_fields {
1.582     raeburn  3907:     my ($symb,$errorref) = @_;
                   3908:     my (@parts) = &getpartlist($symb,$errorref);
                   3909:     if (ref($errorref)) {
                   3910:         if ($$errorref) {
                   3911:             return;
                   3912:         }
                   3913:     }
                   3914: 
1.556     weissno  3915:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3916: 		['username','Student Username'],
                   3917: 		['domain','Student Domain']);
1.324     albertel 3918:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3919:     foreach my $part (sort(@parts)) {
                   3920: 	my @datum;
                   3921: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3922: 	my $name=$part;
                   3923: 	if  (!$display) { $display = $name; }
                   3924: 	@datum=($name,$display);
1.244     albertel 3925: 	if ($name=~/^stores_(.*)_awarded/) {
                   3926: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3927: 	}
1.41      ng       3928: 	push(@fields,\@datum);
                   3929:     }
                   3930:     return (@fields);
1.26      albertel 3931: }
                   3932: 
                   3933: sub csvuploadmap_footer {
1.41      ng       3934:     my ($request,$i,$keyfields) =@_;
                   3935:     $request->print(<<ENDPICK);
1.26      albertel 3936: </table>
                   3937: <input type="hidden" name="nfields" value="$i" />
                   3938: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3939: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3940: </form>
                   3941: ENDPICK
                   3942: }
                   3943: 
1.283     albertel 3944: sub checkforfile_js {
1.638     www      3945:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3946:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3947:     function checkUpload(formname) {
                   3948: 	if (formname.upfile.value == "") {
1.539     riegler  3949: 	    alert("$alertmsg");
1.86      ng       3950: 	    return false;
                   3951: 	}
                   3952: 	formname.submit();
                   3953:     }
                   3954: CSVFORMJS
1.283     albertel 3955:     return $result;
                   3956: }
                   3957: 
                   3958: sub upcsvScores_form {
1.608     www      3959:     my ($request,$symb) = @_;
1.283     albertel 3960:     if (!$symb) {return '';}
                   3961:     my $result=&checkforfile_js();
1.632     www      3962:     $result.=&Apache::loncommon::start_data_table().
                   3963:              &Apache::loncommon::start_data_table_header_row().
                   3964:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   3965:              &Apache::loncommon::end_data_table_header_row().
                   3966:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3967:     my $upload=&mt("Upload Scores");
1.86      ng       3968:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3969:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3970:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3971:     $result.=<<ENDUPFORM;
1.106     albertel 3972: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3973: <input type="hidden" name="symb" value="$symb" />
                   3974: <input type="hidden" name="command" value="csvuploadmap" />
                   3975: $upfile_select
1.589     bisitz   3976: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3977: </form>
                   3978: ENDUPFORM
1.370     www      3979:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      3980:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3981:              '</td>'.
                   3982:             &Apache::loncommon::end_data_table_row().
                   3983:             &Apache::loncommon::end_data_table();
1.86      ng       3984:     return $result;
                   3985: }
                   3986: 
                   3987: 
1.26      albertel 3988: sub csvuploadmap {
1.608     www      3989:     my ($request,$symb)= @_;
1.41      ng       3990:     if (!$symb) {return '';}
1.72      ng       3991: 
1.41      ng       3992:     my $datatoken;
1.257     albertel 3993:     if (!$env{'form.datatoken'}) {
1.41      ng       3994: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3995:     } else {
1.257     albertel 3996: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3997: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3998:     }
1.41      ng       3999:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4000:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4001:     my ($i,$keyfields);
                   4002:     if (@records) {
1.582     raeburn  4003:         my $fieldserror;
                   4004: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4005:         if ($fieldserror) {
                   4006:             $request->print(&navmap_errormsg());
                   4007:             return;
                   4008:         }
1.257     albertel 4009: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4010: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4011: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4012: 							  \@fields);
                   4013: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4014: 	    chop($keyfields);
                   4015: 	} else {
                   4016: 	    unshift(@fields,['none','']);
                   4017: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4018: 							    \@fields);
1.311     banghart 4019:             foreach my $rec (@records) {
                   4020:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4021:                 if (%temp) {
                   4022:                     $keyfields=join(',',sort(keys(%temp)));
                   4023:                     last;
                   4024:                 }
                   4025:             }
1.41      ng       4026: 	}
                   4027:     }
                   4028:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4029: 
1.41      ng       4030:     return '';
1.27      albertel 4031: }
                   4032: 
1.246     albertel 4033: sub csvuploadoptions {
1.608     www      4034:     my ($request,$symb)= @_;
1.632     www      4035:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4036:     $request->print(<<ENDPICK);
                   4037: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4038: <input type="hidden" name="command"    value="csvuploadassign" />
                   4039: <p>
                   4040: <label>
                   4041:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4042:    $overwrite
1.246     albertel 4043: </label>
                   4044: </p>
                   4045: ENDPICK
                   4046:     my %fields=&get_fields();
                   4047:     if (!defined($fields{'domain'})) {
1.257     albertel 4048: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4049: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4050:     }
1.257     albertel 4051:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4052: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4053: 	my $cleankey=$1;
                   4054: 	if ($cleankey eq 'command') { next; }
                   4055: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4056: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4057:     }
                   4058:     # FIXME do a check for any duplicated user ids...
                   4059:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4060:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4061: <hr /></form>'."\n");
1.246     albertel 4062:     return '';
                   4063: }
                   4064: 
                   4065: sub get_fields {
                   4066:     my %fields;
1.257     albertel 4067:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4068:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4069: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4070: 	    if ($env{'form.f'.$i} ne 'none') {
                   4071: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4072: 	    }
                   4073: 	} else {
1.257     albertel 4074: 	    if ($env{'form.f'.$i} ne 'none') {
                   4075: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4076: 	    }
                   4077: 	}
1.27      albertel 4078:     }
1.246     albertel 4079:     return %fields;
                   4080: }
                   4081: 
                   4082: sub csvuploadassign {
1.608     www      4083:     my ($request,$symb)= @_;
1.246     albertel 4084:     if (!$symb) {return '';}
1.345     bowersj2 4085:     my $error_msg = '';
1.246     albertel 4086:     &Apache::loncommon::load_tmp_file($request);
                   4087:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4088:     my %fields=&get_fields();
1.257     albertel 4089:     my $courseid=$env{'request.course.id'};
1.97      albertel 4090:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4091:     my @notallowed;
1.41      ng       4092:     my @skipped;
1.657     raeburn  4093:     my @warnings;
1.41      ng       4094:     my $countdone=0;
                   4095:     foreach my $grade (@gradedata) {
                   4096: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4097: 	my $domain;
                   4098: 	if ($entries{$fields{'domain'}}) {
                   4099: 	    $domain=$entries{$fields{'domain'}};
                   4100: 	} else {
1.257     albertel 4101: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4102: 	}
1.243     albertel 4103: 	$domain=~s/\s//g;
1.41      ng       4104: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4105: 	$username=~s/\s//g;
1.243     albertel 4106: 	if (!$username) {
                   4107: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4108: 	    $id=~s/\s//g;
1.243     albertel 4109: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4110: 	    $username=$ids{$id};
                   4111: 	}
1.41      ng       4112: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4113: 	    my $id=$entries{$fields{'ID'}};
                   4114: 	    $id=~s/\s//g;
                   4115: 	    if ($id) {
                   4116: 		push(@skipped,"$id:$domain");
                   4117: 	    } else {
                   4118: 		push(@skipped,"$username:$domain");
                   4119: 	    }
1.41      ng       4120: 	    next;
                   4121: 	}
1.108     albertel 4122: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4123: 	if (!&canmodify($usec)) {
                   4124: 	    push(@notallowed,"$username:$domain");
                   4125: 	    next;
                   4126: 	}
1.244     albertel 4127: 	my %points;
1.41      ng       4128: 	my %grades;
                   4129: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4130: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4131: 		$dest eq 'domain') { next; }
                   4132: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4133: 	    if ($dest=~/stores_(.*)_points/) {
                   4134: 		my $part=$1;
                   4135: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4136: 					      $symb,$domain,$username);
1.345     bowersj2 4137:                 if ($wgt) {
                   4138:                     $entries{$fields{$dest}}=~s/\s//g;
                   4139:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4140:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4141:                                           : 'correct_by_override';
1.638     www      4142:                     if ($pcr>1) {
1.657     raeburn  4143:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4144:                     }
1.345     bowersj2 4145:                     $grades{"resource.$part.awarded"}=$pcr;
                   4146:                     $grades{"resource.$part.solved"}=$award;
                   4147:                     $points{$part}=1;
                   4148:                 } else {
                   4149:                     $error_msg = "<br />" .
                   4150:                         &mt("Some point values were assigned"
                   4151:                             ." for problems with a weight "
                   4152:                             ."of zero. These values were "
                   4153:                             ."ignored.");
                   4154:                 }
1.244     albertel 4155: 	    } else {
                   4156: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4157: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4158: 		my $store_key=$dest;
                   4159: 		$store_key=~s/^stores/resource/;
                   4160: 		$store_key=~s/_/\./g;
                   4161: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4162: 	    }
1.41      ng       4163: 	}
1.508     www      4164: 	if (! %grades) { 
                   4165:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4166:         } else {
                   4167: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4168: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4169: 					   $env{'request.course.id'},
                   4170: 					   $domain,$username);
1.508     www      4171: 	   if ($result eq 'ok') {
1.627     www      4172: # Successfully stored
1.508     www      4173: 	      $request->print('.');
1.627     www      4174: # Remove from grading queue
                   4175:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4176:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4177:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4178:                                              $domain,$username);
                   4179:               $countdone++;
                   4180:            } else {
1.508     www      4181: 	      $request->print("<p><span class=\"LC_error\">".
                   4182:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4183:                                   "$username:$domain",$result)."</span></p>");
                   4184: 	   }
                   4185: 	   $request->rflush();
                   4186:         }
1.41      ng       4187:     }
1.570     www      4188:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4189:     if (@warnings) {
                   4190:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4191:         $request->print(join(', ',@warnings));
                   4192:     }
1.41      ng       4193:     if (@skipped) {
1.571     www      4194: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4195:         $request->print(join(', ',@skipped));
1.106     albertel 4196:     }
                   4197:     if (@notallowed) {
1.571     www      4198: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4199: 	$request->print(join(', ',@notallowed));
1.41      ng       4200:     }
1.106     albertel 4201:     $request->print("<br />\n");
1.345     bowersj2 4202:     return $error_msg;
1.26      albertel 4203: }
1.44      ng       4204: #------------- end of section for handling csv file upload ---------
                   4205: #
                   4206: #-------------------------------------------------------------------
                   4207: #
1.122     ng       4208: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4209: #
                   4210: #--- Select a page/sequence and a student to grade
1.68      ng       4211: sub pickStudentPage {
1.608     www      4212:     my ($request,$symb) = @_;
1.68      ng       4213: 
1.539     riegler  4214:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4215:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4216: 
                   4217: function checkPickOne(formname) {
1.76      ng       4218:     if (radioSelection(formname.student) == null) {
1.539     riegler  4219: 	alert("$alertmsg");
1.68      ng       4220: 	return;
                   4221:     }
1.125     ng       4222:     ptr = pullDownSelection(formname.selectpage);
                   4223:     formname.page.value = formname["page"+ptr].value;
                   4224:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4225:     formname.submit();
                   4226: }
                   4227: 
                   4228: LISTJAVASCRIPT
1.118     ng       4229:     &commonJSfunctions($request);
1.608     www      4230: 
1.257     albertel 4231:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4232:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4233:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4234: 
1.398     albertel 4235:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4236: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4237: 
1.80      ng       4238:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4239:     my $map_error;
                   4240:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4241:     if ($map_error) {
                   4242:         $request->print(&navmap_errormsg());
                   4243:         return; 
                   4244:     }
1.137     albertel 4245:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4246: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4247: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4248:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4249:     my $ctr=0;
1.68      ng       4250:     foreach (@$titles) {
                   4251: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4252: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4253: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4254: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4255: 	$ctr++;
1.68      ng       4256:     }
1.485     albertel 4257:     $select.= '</select>';
1.539     riegler  4258:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4259: 
1.70      ng       4260:     $ctr=0;
                   4261:     foreach (@$titles) {
                   4262: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4263: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4264: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4265: 	$ctr++;
                   4266:     }
1.72      ng       4267:     $result.='<input type="hidden" name="page" />'."\n".
                   4268: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4269: 
1.485     albertel 4270:     my $options =
                   4271: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4272: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4273:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4274: 
                   4275:     $options =
                   4276: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4277: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4278: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4279:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4280:     
                   4281:     $result.=&build_section_inputs();
1.442     banghart 4282:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4283:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4284: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4285: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4286: 
1.539     riegler  4287:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4288: 
1.80      ng       4289:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4290:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4291: 
1.68      ng       4292:     $request->print($result);
                   4293: 
1.485     albertel 4294:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4295: 	&Apache::loncommon::start_data_table().
                   4296: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4297: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4298: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4299: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4300: 	'<th>'.&nameUserString('header').'</th>'.
                   4301: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4302:  
1.76      ng       4303:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4304:     my $ptr = 1;
1.294     albertel 4305:     foreach my $student (sort 
                   4306: 			 {
                   4307: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4308: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4309: 			     }
                   4310: 			     return $a cmp $b;
                   4311: 			 } (keys(%$fullname))) {
1.68      ng       4312: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4313: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4314:                                   : '</td>');
1.126     ng       4315: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4316: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4317: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4318: 	$studentTable.=
                   4319: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4320:                          : '');
1.68      ng       4321: 	$ptr++;
                   4322:     }
1.484     albertel 4323:     if ($ptr%2 == 0) {
                   4324: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4325: 	    &Apache::loncommon::end_data_table_row();
                   4326:     }
                   4327:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4328:     $studentTable.='<input type="button" '.
1.589     bisitz   4329:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4330: 
                   4331:     $request->print($studentTable);
                   4332: 
                   4333:     return '';
                   4334: }
                   4335: 
                   4336: sub getSymbMap {
1.582     raeburn  4337:     my ($map_error) = @_;
1.132     bowersj2 4338:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4339:     unless (ref($navmap)) {
                   4340:         if (ref($map_error)) {
                   4341:             $$map_error = 'navmap';
                   4342:         }
                   4343:         return;
                   4344:     }
1.68      ng       4345:     my %symbx = ();
                   4346:     my @titles = ();
1.117     bowersj2 4347:     my $minder = 0;
                   4348: 
                   4349:     # Gather every sequence that has problems.
1.240     albertel 4350:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4351: 					       1,0,1);
1.117     bowersj2 4352:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4353: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4354: 	    my $title = $minder.'.'.
                   4355: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4356: 	    push(@titles, $title); # minder in case two titles are identical
                   4357: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4358: 	    $minder++;
1.241     albertel 4359: 	}
1.68      ng       4360:     }
                   4361:     return \@titles,\%symbx;
                   4362: }
                   4363: 
1.72      ng       4364: #
                   4365: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4366: sub displayPage {
1.608     www      4367:     my ($request,$symb) = @_;
1.257     albertel 4368:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4369:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4370:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4371:     my $pageTitle = $env{'form.page'};
1.103     albertel 4372:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4373:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4374:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4375: 
                   4376:     #need to make sure we have the correct data for later EXT calls, 
                   4377:     #thus invalidate the cache
                   4378:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4379:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4380:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4381:     &Apache::lonnet::clear_EXT_cache_status();
                   4382: 
1.103     albertel 4383:     if (!&canview($usec)) {
1.485     albertel 4384: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4385: 	return;
                   4386:     }
1.398     albertel 4387:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4388:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4389: 	'</h3>'."\n";
1.500     albertel 4390:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4391:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4392: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4393:     } else {
                   4394: 	delete($env{'form.CODE'});
                   4395:     }
1.71      ng       4396:     &sub_page_js($request);
                   4397:     $request->print($result);
                   4398: 
1.132     bowersj2 4399:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4400:     unless (ref($navmap)) {
                   4401:         $request->print(&navmap_errormsg());
                   4402:         return;
                   4403:     }
1.257     albertel 4404:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4405:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4406:     if (!$map) {
1.485     albertel 4407: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4408: 	return; 
                   4409:     }
1.68      ng       4410:     my $iterator = $navmap->getIterator($map->map_start(),
                   4411: 					$map->map_finish());
                   4412: 
1.71      ng       4413:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4414: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4415: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4416: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4417: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4418: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4419: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4420: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4421: 
1.382     albertel 4422:     if (defined($env{'form.CODE'})) {
                   4423: 	$studentTable.=
                   4424: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4425:     }
1.381     albertel 4426:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4427: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4428: 
1.594     bisitz   4429:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4430:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4431:         '</span>'."\n".
1.484     albertel 4432: 	&Apache::loncommon::start_data_table().
                   4433: 	&Apache::loncommon::start_data_table_header_row().
                   4434: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4435: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4436: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4437: 
1.329     albertel 4438:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4439:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4440:     $iterator->next(); # skip the first BEGIN_MAP
                   4441:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4442:     while ($depth > 0) {
1.68      ng       4443:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4444:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4445: 
1.385     albertel 4446:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4447: 	    my $parts = $curRes->parts();
1.68      ng       4448:             my $title = $curRes->compTitle();
1.71      ng       4449: 	    my $symbx = $curRes->symb();
1.484     albertel 4450: 	    $studentTable.=
                   4451: 		&Apache::loncommon::start_data_table_row().
                   4452: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4453: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4454: 		                        : '<br />('.&mt('[_1]parts)',
                   4455: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4456: 		 ).
                   4457: 		 '</td>';
1.71      ng       4458: 	    $studentTable.='<td valign="top">';
1.382     albertel 4459: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4460: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4461: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4462: 					     undef,'both',\%form);
1.71      ng       4463: 	    } else {
1.382     albertel 4464: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4465: 		$companswer =~ s|<form(.*?)>||g;
                   4466: 		$companswer =~ s|</form>||g;
1.71      ng       4467: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4468: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4469: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4470: #		}
1.116     ng       4471: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4472: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4473: 	    }
                   4474: 
1.257     albertel 4475: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4476: 
1.257     albertel 4477: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4478: 		if ($record{'version'} eq '') {
1.485     albertel 4479: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4480: 		} else {
1.116     ng       4481: 		    my %responseType = ();
                   4482: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4483: 			my @responseIds =$curRes->responseIds($partid);
                   4484: 			my @responseType =$curRes->responseType($partid);
                   4485: 			my %responseIds;
                   4486: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4487: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4488: 			}
                   4489: 			$responseType{$partid} = \%responseIds;
1.116     ng       4490: 		    }
1.148     albertel 4491: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4492: 
1.71      ng       4493: 		}
1.257     albertel 4494: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4495: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4496: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4497: 									$env{'request.course.id'},
1.71      ng       4498: 									'','.submission');
                   4499:  
                   4500: 	    }
1.103     albertel 4501: 	    if (&canmodify($usec)) {
1.585     bisitz   4502:             $studentTable.=&gradeBox_start();
1.103     albertel 4503: 		foreach my $partid (@{$parts}) {
                   4504: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4505: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4506: 		    $question++;
                   4507: 		}
1.585     bisitz   4508:             $studentTable.=&gradeBox_end();
1.196     albertel 4509: 		$prob++;
1.71      ng       4510: 	    }
                   4511: 	    $studentTable.='</td></tr>';
1.68      ng       4512: 
1.103     albertel 4513: 	}
1.68      ng       4514:         $curRes = $iterator->next();
                   4515:     }
                   4516: 
1.589     bisitz   4517:     $studentTable.=
                   4518:         '</table>'."\n".
                   4519:         '<input type="button" value="'.&mt('Save').'" '.
                   4520:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4521:         '</form>'."\n";
1.71      ng       4522:     $request->print($studentTable);
                   4523: 
                   4524:     return '';
1.119     ng       4525: }
                   4526: 
                   4527: sub displaySubByDates {
1.148     albertel 4528:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4529:     my $isCODE=0;
1.335     albertel 4530:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4531:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4532:     my $studentTable=&Apache::loncommon::start_data_table().
                   4533: 	&Apache::loncommon::start_data_table_header_row().
                   4534: 	'<th>'.&mt('Date/Time').'</th>'.
                   4535: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4536: 	'<th>'.&mt('Submission').'</th>'.
                   4537: 	'<th>'.&mt('Status').'</th>'.
                   4538: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4539:     my ($version);
                   4540:     my %mark;
1.148     albertel 4541:     my %orders;
1.119     ng       4542:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4543:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4544: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4545:     }
1.335     albertel 4546: 
                   4547:     my $interaction;
1.525     raeburn  4548:     my $no_increment = 1;
1.640     raeburn  4549:     my %lastrndseed;
1.119     ng       4550:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4551: 	my $timestamp = 
                   4552: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4553: 	if (exists($$record{$version.':resource.0.version'})) {
                   4554: 	    $interaction = $$record{$version.':resource.0.version'};
                   4555: 	}
                   4556: 
                   4557: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4558: 		             : "$version:resource");
1.467     albertel 4559: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4560: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4561: 	if ($isCODE) {
                   4562: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4563: 	}
1.119     ng       4564: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4565: 	my @displaySub = ();
                   4566: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4567:             my ($hidden,$type);
                   4568:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4569:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4570:                 $hidden = 1;
                   4571:             }
1.335     albertel 4572: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4573: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4574: 	    
1.122     ng       4575: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4576: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4577: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4578: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4579: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4580:                     
1.335     albertel 4581: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4582: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4583:                     $displaySub[0].='<span class="LC_nobreak"';
                   4584:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4585:                                    .' <span class="LC_internal_info">'
1.625     www      4586:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4587:                                    .'</span>'
                   4588:                                    .' <b>';
1.596     raeburn  4589:                     if ($hidden) {
                   4590:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4591:                     } else {
1.640     raeburn  4592:                         my ($trial,$rndseed,$newvariation);
                   4593:                         if ($type eq 'randomizetry') {
                   4594:                             $trial = $$record{"$where.$partid.tries"};
                   4595:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4596:                         }
1.596     raeburn  4597: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4598: 			    $displaySub[0].=&mt('Trial not counted');
                   4599: 		        } else {
                   4600: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4601: 					    $$record{"$where.$partid.tries"});
1.640     raeburn  4602:                             if ($rndseed || $lastrndseed{$partid}) {
                   4603:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4604:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4605:                                 }
                   4606:                             }
                   4607:                             $lastrndseed{$partid} = $rndseed;
1.596     raeburn  4608: 		        }
                   4609: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4610:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4611: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4612: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4613: 			    $orders{$partid}->{$responseId}=
                   4614: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4615:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4616: 		        }
1.640     raeburn  4617: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4618: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4619: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4620:                     }
1.147     albertel 4621: 		}
                   4622: 	    }
1.335     albertel 4623: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4624: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4625: 				    $$record{"$where.$partid.checkedin"},
                   4626: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4627: 					'<br />';
1.335     albertel 4628: 	    }
                   4629: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4630: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4631: 		    lc($$record{"$where.$partid.award"}).' '.
                   4632: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4633: 		    '<br />';
                   4634: 	    }
1.335     albertel 4635: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4636: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4637: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4638: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4639: 		$displaySub[2].=
                   4640: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4641: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4642: 	    }
                   4643: 	}
                   4644: 	# needed because old essay regrader has not parts info
                   4645: 	if (exists $$record{"$version:resource.regrader"}) {
                   4646: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4647: 	}
                   4648: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4649: 	if ($displaySub[2]) {
1.467     albertel 4650: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4651: 	}
1.467     albertel 4652: 	$studentTable.='&nbsp;</td>'.
                   4653: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4654:     }
1.467     albertel 4655:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4656:     return $studentTable;
1.71      ng       4657: }
                   4658: 
                   4659: sub updateGradeByPage {
1.608     www      4660:     my ($request,$symb) = @_;
1.71      ng       4661: 
1.257     albertel 4662:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4663:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4664:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4665:     my $pageTitle = $env{'form.page'};
1.103     albertel 4666:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4667:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4668:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4669:     if (!&canmodify($usec)) {
1.526     raeburn  4670: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4671: 	return;
                   4672:     }
1.398     albertel 4673:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4674:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4675: 	'</h3>'."\n";
1.70      ng       4676: 
1.68      ng       4677:     $request->print($result);
                   4678: 
1.582     raeburn  4679: 
1.132     bowersj2 4680:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4681:     unless (ref($navmap)) {
                   4682:         $request->print(&navmap_errormsg());
                   4683:         return;
                   4684:     }
1.257     albertel 4685:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4686:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4687:     if (!$map) {
1.527     raeburn  4688: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4689: 	return; 
                   4690:     }
1.71      ng       4691:     my $iterator = $navmap->getIterator($map->map_start(),
                   4692: 					$map->map_finish());
1.70      ng       4693: 
1.484     albertel 4694:     my $studentTable=
                   4695: 	&Apache::loncommon::start_data_table().
                   4696: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4697: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4698: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4699: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4700: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4701: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4702: 
                   4703:     $iterator->next(); # skip the first BEGIN_MAP
                   4704:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4705:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4706:     while ($depth > 0) {
1.71      ng       4707:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4708:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4709: 
1.385     albertel 4710:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4711: 	    my $parts = $curRes->parts();
1.71      ng       4712:             my $title = $curRes->compTitle();
                   4713: 	    my $symbx = $curRes->symb();
1.484     albertel 4714: 	    $studentTable.=
                   4715: 		&Apache::loncommon::start_data_table_row().
                   4716: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4717: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4718:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4719: 		.')').'</td>';
1.71      ng       4720: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4721: 
                   4722: 	    my %newrecord=();
                   4723: 	    my @displayPts=();
1.269     raeburn  4724:             my %aggregate = ();
                   4725:             my $aggregateflag = 0;
1.71      ng       4726: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4727: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4728: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4729: 
1.257     albertel 4730: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4731: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4732: 		my $partial = $newpts/$wgt;
                   4733: 		my $score;
                   4734: 		if ($partial > 0) {
                   4735: 		    $score = 'correct_by_override';
1.125     ng       4736: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4737: 		    $score = 'incorrect_by_override';
                   4738: 		}
1.257     albertel 4739: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4740: 		if ($dropMenu eq 'excused') {
1.71      ng       4741: 		    $partial = '';
                   4742: 		    $score = 'excused';
1.125     ng       4743: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4744: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4745: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4746: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4747: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4748: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4749: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4750: 		    $changeflag++;
                   4751: 		    $newpts = '';
1.269     raeburn  4752:                     
                   4753:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4754:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4755:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4756:                     if ($aggtries > 0) {
                   4757:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4758:                         $aggregateflag = 1;
                   4759:                     }
1.71      ng       4760: 		}
1.324     albertel 4761: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4762: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4763: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4764: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4765: 		    '&nbsp;<br />';
1.526     raeburn  4766: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4767: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4768: 		    '&nbsp;<br />';
1.71      ng       4769: 		$question++;
1.380     albertel 4770: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4771: 
1.71      ng       4772: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4773: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4774: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4775: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4776: 
                   4777: 		$changeflag++;
                   4778: 	    }
                   4779: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4780: 		my %record = 
                   4781: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4782: 					     $udom,$uname);
                   4783: 
                   4784: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4785: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4786: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4787: 		    $newrecord{'resource.CODE'} = '';
                   4788: 		}
1.257     albertel 4789: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4790: 					$udom,$uname);
1.382     albertel 4791: 		%record = &Apache::lonnet::restore($symbx,
                   4792: 						   $env{'request.course.id'},
                   4793: 						   $udom,$uname);
1.380     albertel 4794: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4795: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4796: 	    }
1.380     albertel 4797: 	    
1.269     raeburn  4798:             if ($aggregateflag) {
                   4799:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4800:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4801:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4802:             }
1.125     ng       4803: 
1.71      ng       4804: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4805: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4806: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4807: 
1.196     albertel 4808: 	    $prob++;
1.68      ng       4809: 	}
1.71      ng       4810:         $curRes = $iterator->next();
1.68      ng       4811:     }
1.98      albertel 4812: 
1.484     albertel 4813:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4814:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4815: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4816: 		  $changeflag));
1.76      ng       4817:     $request->print($grademsg.$studentTable);
1.68      ng       4818: 
1.70      ng       4819:     return '';
                   4820: }
                   4821: 
1.72      ng       4822: #-------- end of section for handling grading by page/sequence ---------
                   4823: #
                   4824: #-------------------------------------------------------------------
                   4825: 
1.581     www      4826: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4827: #
                   4828: #------ start of section for handling grading by page/sequence ---------
                   4829: 
1.423     albertel 4830: =pod
                   4831: 
                   4832: =head1 Bubble sheet grading routines
                   4833: 
1.424     albertel 4834:   For this documentation:
                   4835: 
                   4836:    'scanline' refers to the full line of characters
                   4837:    from the file that we are parsing that represents one entire sheet
                   4838: 
                   4839:    'bubble line' refers to the data
1.659   ! raeburn  4840:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 4841: 
                   4842: 
1.659   ! raeburn  4843: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 4844: into a course. When a user wants to grade, they select a
1.659   ! raeburn  4845: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 4846: one of the predefined configurations for what each scanline looks
                   4847: like.
                   4848: 
                   4849: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4850: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4851: because too light bubbling), 'double bubble' (each bubble line should
                   4852: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4853: invalid student/employee ID
1.424     albertel 4854: 
                   4855: If the CODE option is used that determines the randomization of the
1.556     weissno  4856: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4857: username:domain.
                   4858: 
                   4859: During the validation phase the instructor can choose to skip scanlines. 
                   4860: 
1.659   ! raeburn  4861: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 4862: 
                   4863:   scantron_original_filename (unmodified original file)
                   4864:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4865:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4866: 
                   4867: Also there is a separate hash nohist_scantrondata that contains extra
1.659   ! raeburn  4868: correction information that isn't representable in the bubblesheet
1.424     albertel 4869: file (see &scantron_getfile() for more information)
                   4870: 
                   4871: After all scanlines are either valid, marked as valid or skipped, then
                   4872: foreach line foreach problem in the picked sequence, an ssi request is
                   4873: made that simulates a user submitting their selected letter(s) against
                   4874: the homework problem.
1.423     albertel 4875: 
                   4876: =over 4
                   4877: 
                   4878: 
                   4879: 
                   4880: =item defaultFormData
                   4881: 
                   4882:   Returns html hidden inputs used to hold context/default values.
                   4883: 
                   4884:  Arguments:
                   4885:   $symb - $symb of the current resource 
                   4886: 
                   4887: =cut
1.422     foxr     4888: 
1.81      albertel 4889: sub defaultFormData {
1.324     albertel 4890:     my ($symb)=@_;
1.613     www      4891:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4892: }
                   4893: 
1.447     foxr     4894: 
1.423     albertel 4895: =pod 
                   4896: 
                   4897: =item getSequenceDropDown
                   4898: 
                   4899:    Return html dropdown of possible sequences to grade
                   4900:  
                   4901:  Arguments:
1.582     raeburn  4902:    $symb - $symb of the current resource
                   4903:    $map_error - ref to scalar which will container error if
                   4904:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4905: 
                   4906: =cut
1.422     foxr     4907: 
1.75      albertel 4908: sub getSequenceDropDown {
1.582     raeburn  4909:     my ($symb,$map_error)=@_;
1.75      albertel 4910:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4911:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4912:     if (ref($map_error)) {
                   4913:         return if ($$map_error);
                   4914:     }
1.137     albertel 4915:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4916:     my $ctr=0;
                   4917:     foreach (@$titles) {
                   4918: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4919: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4920: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4921: 	    '>'.$showtitle.'</option>'."\n";
                   4922: 	$ctr++;
                   4923:     }
                   4924:     $result.= '</select>';
                   4925:     return $result;
                   4926: }
                   4927: 
1.495     albertel 4928: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4929:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4930: 
                   4931: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4932: 
1.509     raeburn  4933: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4934:                                    # matchresponse or rankresponse, where 
                   4935:                                    # an individual response can have multiple 
                   4936:                                    # lines
1.503     raeburn  4937: 
                   4938: my %responsetype_per_response;     # responsetype for each response
                   4939: 
1.495     albertel 4940: # Save and restore the bubble lines array to the form env.
                   4941: 
                   4942: 
                   4943: sub save_bubble_lines {
                   4944:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4945: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4946: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4947: 	    $first_bubble_line{$line};
1.503     raeburn  4948:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4949:             $subdivided_bubble_lines{$line};
                   4950:         $env{"form.scantron.responsetype.$line"} =
                   4951:             $responsetype_per_response{$line};
1.495     albertel 4952:     }
                   4953: }
                   4954: 
                   4955: 
                   4956: sub restore_bubble_lines {
                   4957:     my $line = 0;
                   4958:     %bubble_lines_per_response = ();
                   4959:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4960: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4961: 	$bubble_lines_per_response{$line} = $value;
                   4962: 	$first_bubble_line{$line}  =
                   4963: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4964:         $subdivided_bubble_lines{$line} =
                   4965:             $env{"form.scantron.sub_bubblelines.$line"};
                   4966:         $responsetype_per_response{$line} =
                   4967:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4968: 	$line++;
                   4969:     }
                   4970: }
                   4971: 
                   4972: #  Given the parsed scanline, get the response for 
                   4973: #  'answer' number n:
                   4974: 
                   4975: sub get_response_bubbles {
                   4976:     my ($parsed_line, $response)  = @_;
                   4977: 
                   4978:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4979:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4980:     
                   4981:     my $selected = "";
                   4982: 
                   4983:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4984: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4985: 	$bubble_line++;
                   4986:     }
                   4987:     return $selected;
                   4988: }
1.423     albertel 4989: 
                   4990: =pod 
                   4991: 
                   4992: =item scantron_filenames
                   4993: 
                   4994:    Returns a list of the scantron files in the current course 
                   4995: 
                   4996: =cut
1.422     foxr     4997: 
1.202     albertel 4998: sub scantron_filenames {
1.257     albertel 4999:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5000:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5001:     my $getpropath = 1;
1.157     albertel 5002:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5003:                                        $getpropath);
1.202     albertel 5004:     my @possiblenames;
1.201     albertel 5005:     foreach my $filename (sort(@files)) {
1.157     albertel 5006: 	($filename)=split(/&/,$filename);
                   5007: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5008: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5009: 	push(@possiblenames,$filename);
                   5010:     }
                   5011:     return @possiblenames;
                   5012: }
                   5013: 
1.423     albertel 5014: =pod 
                   5015: 
                   5016: =item scantron_uploads
                   5017: 
                   5018:    Returns  html drop-down list of scantron files in current course.
                   5019: 
                   5020:  Arguments:
                   5021:    $file2grade - filename to set as selected in the dropdown
                   5022: 
                   5023: =cut
1.422     foxr     5024: 
1.202     albertel 5025: sub scantron_uploads {
1.209     ng       5026:     my ($file2grade) = @_;
1.202     albertel 5027:     my $result=	'<select name="scantron_selectfile">';
                   5028:     $result.="<option></option>";
                   5029:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5030: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5031:     }
                   5032:     $result.="</select>";
                   5033:     return $result;
                   5034: }
                   5035: 
1.423     albertel 5036: =pod 
                   5037: 
                   5038: =item scantron_scantab
                   5039: 
                   5040:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5041:   file.
                   5042: 
                   5043: =cut
1.422     foxr     5044: 
1.82      albertel 5045: sub scantron_scantab {
                   5046:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5047:     $result.='<option></option>'."\n";
1.518     raeburn  5048:     my @lines = &get_scantronformat_file();
                   5049:     if (@lines > 0) {
                   5050:         foreach my $line (@lines) {
                   5051:             next if (($line =~ /^\#/) || ($line eq ''));
                   5052: 	    my ($name,$descrip)=split(/:/,$line);
                   5053: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5054:         }
1.82      albertel 5055:     }
                   5056:     $result.='</select>'."\n";
1.518     raeburn  5057:     return $result;
                   5058: }
                   5059: 
                   5060: =pod
                   5061: 
                   5062: =item get_scantronformat_file
                   5063: 
                   5064:   Returns an array containing lines from the scantron format file for
                   5065:   the domain of the course.
                   5066: 
                   5067:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5068:   lines are from this file.
                   5069: 
                   5070:   Otherwise, if a default.tab has been published in RES space by the 
                   5071:   domainconfig user, lines are from this file.
                   5072: 
                   5073:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5074:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5075: 
1.518     raeburn  5076: =cut
                   5077: 
                   5078: sub get_scantronformat_file {
                   5079:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5080:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5081:     my $gottab = 0;
                   5082:     my @lines;
                   5083:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5084:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5085:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5086:             if ($formatfile ne '-1') {
                   5087:                 @lines = split("\n",$formatfile,-1);
                   5088:                 $gottab = 1;
                   5089:             }
                   5090:         }
                   5091:     }
                   5092:     if (!$gottab) {
                   5093:         my $confname = $cdom.'-domainconfig';
                   5094:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5095:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5096:         if ($formatfile ne '-1') {
                   5097:             @lines = split("\n",$formatfile,-1);
                   5098:             $gottab = 1;
                   5099:         }
                   5100:     }
                   5101:     if (!$gottab) {
1.519     raeburn  5102:         my @domains = &Apache::lonnet::current_machine_domains();
                   5103:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5104:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5105:             @lines = <$fh>;
                   5106:             close($fh);
                   5107:         } else {
                   5108:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5109:             @lines = <$fh>;
                   5110:             close($fh);
                   5111:         }
1.518     raeburn  5112:     }
                   5113:     return @lines;
1.82      albertel 5114: }
                   5115: 
1.423     albertel 5116: =pod 
                   5117: 
                   5118: =item scantron_CODElist
                   5119: 
                   5120:   Returns html drop down of the saved CODE lists from current course,
                   5121:   generated from earlier printings.
                   5122: 
                   5123: =cut
1.422     foxr     5124: 
1.186     albertel 5125: sub scantron_CODElist {
1.257     albertel 5126:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5127:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5128:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5129:     my $namechoice='<option></option>';
1.225     albertel 5130:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5131: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5132: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5133: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5134:     }
                   5135:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5136:     return $namechoice;
                   5137: }
                   5138: 
1.423     albertel 5139: =pod 
                   5140: 
                   5141: =item scantron_CODEunique
                   5142: 
                   5143:   Returns the html for "Each CODE to be used once" radio.
                   5144: 
                   5145: =cut
1.422     foxr     5146: 
1.186     albertel 5147: sub scantron_CODEunique {
1.532     bisitz   5148:     my $result='<span class="LC_nobreak">
1.272     albertel 5149:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5150:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5151:                 </span>
1.532     bisitz   5152:                 <span class="LC_nobreak">
1.272     albertel 5153:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5154:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5155:                 </span>';
1.186     albertel 5156:     return $result;
                   5157: }
1.423     albertel 5158: 
                   5159: =pod 
                   5160: 
                   5161: =item scantron_selectphase
                   5162: 
1.659   ! raeburn  5163:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5164:   Allows for - starting a grading run.
1.424     albertel 5165:              - downloading existing scan data (original, corrected
1.423     albertel 5166:                                                 or skipped info)
                   5167: 
                   5168:              - uploading new scan data
                   5169: 
                   5170:  Arguments:
                   5171:   $r          - The Apache request object
                   5172:   $file2grade - name of the file that contain the scanned data to score
                   5173: 
                   5174: =cut
1.186     albertel 5175: 
1.75      albertel 5176: sub scantron_selectphase {
1.608     www      5177:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5178:     if (!$symb) {return '';}
1.582     raeburn  5179:     my $map_error;
                   5180:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5181:     if ($map_error) {
                   5182:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5183:         return;
                   5184:     }
1.324     albertel 5185:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5186:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5187:     my $format_selector=&scantron_scantab();
1.186     albertel 5188:     my $CODE_selector=&scantron_CODElist();
                   5189:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5190:     my $result;
1.422     foxr     5191: 
1.513     foxr     5192:     $ssi_error = 0;
                   5193: 
1.606     wenzelju 5194:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5195:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5196: 
                   5197: 	# Chunk of form to prompt for a scantron file upload.
                   5198: 
                   5199:         $r->print('
                   5200:     <br />
                   5201:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5202:        '.&Apache::loncommon::start_data_table_header_row().'
                   5203:             <th>
                   5204:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5205:             </th>
                   5206:        '.&Apache::loncommon::end_data_table_header_row().'
                   5207:        '.&Apache::loncommon::start_data_table_row().'
                   5208:             <td>
                   5209: ');
1.608     www      5210:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5211:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5212:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5213:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5214:     function checkUpload(formname) {
                   5215: 	if (formname.upfile.value == "") {
                   5216: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5217: 	    return false;
                   5218: 	}
                   5219: 	formname.submit();
                   5220:     }'));
                   5221:     $r->print('
                   5222:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5223:                 '.$default_form_data.'
                   5224:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5225:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5226:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5227:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5228:                 <br />
                   5229:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5230:               </form>
                   5231: ');
                   5232: 
                   5233:         $r->print('
                   5234:             </td>
                   5235:        '.&Apache::loncommon::end_data_table_row().'
                   5236:        '.&Apache::loncommon::end_data_table().'
                   5237: ');
                   5238:     }
                   5239: 
1.422     foxr     5240:     # Chunk of form to prompt for a file to grade and how:
                   5241: 
1.489     albertel 5242:     $result.= '
                   5243:     <br />
                   5244:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5245:     <input type="hidden" name="command" value="scantron_warning" />
                   5246:     '.$default_form_data.'
                   5247:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5248:        '.&Apache::loncommon::start_data_table_header_row().'
                   5249:             <th colspan="2">
1.492     albertel 5250:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5251:             </th>
                   5252:        '.&Apache::loncommon::end_data_table_header_row().'
                   5253:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5254:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5255:        '.&Apache::loncommon::end_data_table_row().'
                   5256:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5257:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5258:        '.&Apache::loncommon::end_data_table_row().'
                   5259:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5260:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5261:        '.&Apache::loncommon::end_data_table_row().'
                   5262:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5263:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5264:        '.&Apache::loncommon::end_data_table_row().'
                   5265:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5266:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5267:        '.&Apache::loncommon::end_data_table_row().'
                   5268:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5269: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5270:             <td>
1.492     albertel 5271: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5272:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5273:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5274: 	    </td>
1.489     albertel 5275:        '.&Apache::loncommon::end_data_table_row().'
                   5276:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5277:             <td colspan="2">
1.572     www      5278:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5279:             </td>
1.489     albertel 5280:        '.&Apache::loncommon::end_data_table_row().'
                   5281:     '.&Apache::loncommon::end_data_table().'
                   5282:     </form>
                   5283: ';
1.162     albertel 5284:    
                   5285:     $r->print($result);
                   5286: 
1.422     foxr     5287: 
                   5288: 
                   5289:     # Chunk of the form that prompts to view a scoring office file,
                   5290:     # corrected file, skipped records in a file.
                   5291: 
1.489     albertel 5292:     $r->print('
                   5293:    <br />
                   5294:    <form action="/adm/grades" name="scantron_download">
                   5295:      '.$default_form_data.'
                   5296:      <input type="hidden" name="command" value="scantron_download" />
                   5297:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5298:        '.&Apache::loncommon::start_data_table_header_row().'
                   5299:               <th>
1.492     albertel 5300:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5301:               </th>
                   5302:        '.&Apache::loncommon::end_data_table_header_row().'
                   5303:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5304:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5305:                 <br />
1.492     albertel 5306:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5307:        '.&Apache::loncommon::end_data_table_row().'
                   5308:      '.&Apache::loncommon::end_data_table().'
                   5309:    </form>
                   5310:    <br />
                   5311: ');
1.162     albertel 5312: 
1.457     banghart 5313:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5314: 
1.528     raeburn  5315:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5316:              $default_form_data."\n".
                   5317:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5318:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5319:              '<th colspan="2">
1.572     www      5320:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5321:              '</th>'."\n".
                   5322:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5323:               &Apache::loncommon::start_data_table_row()."\n".
                   5324:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5325:               '<td> '.$sequence_selector.' </td>'.
                   5326:               &Apache::loncommon::end_data_table_row()."\n".
                   5327:               &Apache::loncommon::start_data_table_row()."\n".
                   5328:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5329:               '<td> '.$file_selector.' </td>'."\n".
                   5330:               &Apache::loncommon::end_data_table_row()."\n".
                   5331:               &Apache::loncommon::start_data_table_row()."\n".
                   5332:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5333:               '<td> '.$format_selector.' </td>'."\n".
                   5334:               &Apache::loncommon::end_data_table_row()."\n".
                   5335:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5336:               '<td> '.&mt('Options').' </td>'."\n".
                   5337:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5338:               &Apache::loncommon::end_data_table_row()."\n".
                   5339:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5340:               '<td colspan="2">'."\n".
                   5341:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5342:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5343:               '</td>'."\n".
                   5344:               &Apache::loncommon::end_data_table_row()."\n".
                   5345:               &Apache::loncommon::end_data_table()."\n".
                   5346:               '</form><br />');
                   5347:     return;
1.75      albertel 5348: }
                   5349: 
1.423     albertel 5350: =pod
                   5351: 
                   5352: =item get_scantron_config
                   5353: 
                   5354:    Parse and return the scantron configuration line selected as a
                   5355:    hash of configuration file fields.
                   5356: 
                   5357:  Arguments:
                   5358:     which - the name of the configuration to parse from the file.
                   5359: 
                   5360: 
                   5361:  Returns:
                   5362:             If the named configuration is not in the file, an empty
                   5363:             hash is returned.
                   5364:     a hash with the fields
                   5365:       name         - internal name for the this configuration setup
                   5366:       description  - text to display to operator that describes this config
                   5367:       CODElocation - if 0 or the string 'none'
                   5368:                           - no CODE exists for this config
                   5369:                      if -1 || the string 'letter'
                   5370:                           - a CODE exists for this config and is
                   5371:                             a string of letters
                   5372:                      Unsupported value (but planned for future support)
                   5373:                           if a positive integer
                   5374:                                - The CODE exists as the first n items from
                   5375:                                  the question section of the form
                   5376:                           if the string 'number'
                   5377:                                - The CODE exists for this config and is
                   5378:                                  a string of numbers
                   5379:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5380:                      the CODE starts
                   5381:       CODElength  - length of the CODE
1.573     bisitz   5382:       IDstart     - column where the student/employee ID starts
1.556     weissno  5383:       IDlength    - length of the student/employee ID info
1.423     albertel 5384:       Qstart      - column where the information from the bubbled
                   5385:                     'questions' start
                   5386:       Qlength     - number of columns comprising a single bubble line from
                   5387:                     the sheet. (usually either 1 or 10)
1.424     albertel 5388:       Qon         - either a single character representing the character used
1.423     albertel 5389:                     to signal a bubble was chosen in the positional setup, or
                   5390:                     the string 'letter' if the letter of the chosen bubble is
                   5391:                     in the final, or 'number' if a number representing the
                   5392:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5393:       Qoff        - the character used to represent that a bubble was
                   5394:                     left blank
1.423     albertel 5395:       PaperID     - if the scanning process generates a unique number for each
                   5396:                     sheet scanned the column that this ID number starts in
                   5397:       PaperIDlength - number of columns that comprise the unique ID number
                   5398:                       for the sheet of paper
1.424     albertel 5399:       FirstName   - column that the first name starts in
1.423     albertel 5400:       FirstNameLength - number of columns that the first name spans
                   5401:  
                   5402:       LastName    - column that the last name starts in
                   5403:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5404:       BubblesPerRow - number of bubbles available in each row used to 
                   5405:                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5406: =cut
1.422     foxr     5407: 
1.82      albertel 5408: sub get_scantron_config {
                   5409:     my ($which) = @_;
1.518     raeburn  5410:     my @lines = &get_scantronformat_file();
1.82      albertel 5411:     my %config;
1.157     albertel 5412:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5413:     foreach my $line (@lines) {
1.82      albertel 5414: 	my ($name,$descrip)=split(/:/,$line);
                   5415: 	if ($name ne $which ) { next; }
                   5416: 	chomp($line);
                   5417: 	my @config=split(/:/,$line);
                   5418: 	$config{'name'}=$config[0];
                   5419: 	$config{'description'}=$config[1];
                   5420: 	$config{'CODElocation'}=$config[2];
                   5421: 	$config{'CODEstart'}=$config[3];
                   5422: 	$config{'CODElength'}=$config[4];
                   5423: 	$config{'IDstart'}=$config[5];
                   5424: 	$config{'IDlength'}=$config[6];
                   5425: 	$config{'Qstart'}=$config[7];
1.497     foxr     5426:  	$config{'Qlength'}=$config[8];
1.82      albertel 5427: 	$config{'Qoff'}=$config[9];
                   5428: 	$config{'Qon'}=$config[10];
1.157     albertel 5429: 	$config{'PaperID'}=$config[11];
                   5430: 	$config{'PaperIDlength'}=$config[12];
                   5431: 	$config{'FirstName'}=$config[13];
                   5432: 	$config{'FirstNamelength'}=$config[14];
                   5433: 	$config{'LastName'}=$config[15];
                   5434: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5435:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5436: 	last;
                   5437:     }
                   5438:     return %config;
                   5439: }
                   5440: 
1.423     albertel 5441: =pod 
                   5442: 
                   5443: =item username_to_idmap
                   5444: 
1.556     weissno  5445:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5446:     student username:domain.
                   5447: 
                   5448:   Arguments:
                   5449: 
                   5450:     $classlist - reference to the class list hash. This is a hash
                   5451:                  keyed by student name:domain  whose elements are references
1.424     albertel 5452:                  to arrays containing various chunks of information
1.423     albertel 5453:                  about the student. (See loncoursedata for more info).
                   5454: 
                   5455:   Returns
                   5456:     %idmap - the constructed hash
                   5457: 
                   5458: =cut
                   5459: 
1.82      albertel 5460: sub username_to_idmap {
                   5461:     my ($classlist)= @_;
                   5462:     my %idmap;
                   5463:     foreach my $student (keys(%$classlist)) {
                   5464: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5465: 	    $student;
                   5466:     }
                   5467:     return %idmap;
                   5468: }
1.423     albertel 5469: 
                   5470: =pod
                   5471: 
1.424     albertel 5472: =item scantron_fixup_scanline
1.423     albertel 5473: 
                   5474:    Process a requested correction to a scanline.
                   5475: 
                   5476:   Arguments:
                   5477:     $scantron_config   - hash from &get_scantron_config()
                   5478:     $scan_data         - hash of correction information 
                   5479:                           (see &scantron_getfile())
                   5480:     $line              - existing scanline
                   5481:     $whichline         - line number of the passed in scanline
                   5482:     $field             - type of change to process 
                   5483:                          (either 
1.573     bisitz   5484:                           'ID'     -> correct the student/employee ID
1.423     albertel 5485:                           'CODE'   -> correct the CODE
                   5486:                           'answer' -> fixup the submitted answers)
                   5487:     
                   5488:    $args               - hash of additional info,
                   5489:                           - 'ID' 
                   5490:                                'newid' -> studentID to use in replacement
1.424     albertel 5491:                                           of existing one
1.423     albertel 5492:                           - 'CODE' 
                   5493:                                'CODE_ignore_dup' - set to true if duplicates
                   5494:                                                    should be ignored.
                   5495: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5496:                                         if the existing unfound code should
1.423     albertel 5497:                                         be used as is
                   5498:                           - 'answer'
                   5499:                                'response' - new answer or 'none' if blank
                   5500:                                'question' - the bubble line to change
1.503     raeburn  5501:                                'questionnum' - the question identifier,
                   5502:                                                may include subquestion. 
1.423     albertel 5503: 
                   5504:   Returns:
                   5505:     $line - the modified scanline
                   5506: 
                   5507:   Side effects: 
                   5508:     $scan_data - may be updated
                   5509: 
                   5510: =cut
                   5511: 
1.82      albertel 5512: 
1.157     albertel 5513: sub scantron_fixup_scanline {
                   5514:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5515:     if ($field eq 'ID') {
                   5516: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5517: 	    return ($line,1,'New value too large');
1.157     albertel 5518: 	}
                   5519: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5520: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5521: 				     $args->{'newid'});
                   5522: 	}
                   5523: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5524: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5525: 	if ($args->{'newid'}=~/^\s*$/) {
                   5526: 	    &scan_data($scan_data,"$whichline.user",
                   5527: 		       $args->{'username'}.':'.$args->{'domain'});
                   5528: 	}
1.186     albertel 5529:     } elsif ($field eq 'CODE') {
1.192     albertel 5530: 	if ($args->{'CODE_ignore_dup'}) {
                   5531: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5532: 	}
                   5533: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5534: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5535: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5536: 		return ($line,1,'New CODE value too large');
                   5537: 	    }
                   5538: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5539: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5540: 	    }
                   5541: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5542: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5543: 	}
1.157     albertel 5544:     } elsif ($field eq 'answer') {
1.497     foxr     5545: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5546: 	my $off=$scantron_config->{'Qoff'};
                   5547: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5548: 	my $answer=${off}x$length;
                   5549: 	if ($args->{'response'} eq 'none') {
                   5550: 	    &scan_data($scan_data,
1.503     raeburn  5551: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5552: 	} else {
                   5553: 	    if ($on eq 'letter') {
                   5554: 		my @alphabet=('A'..'Z');
                   5555: 		$answer=$alphabet[$args->{'response'}];
                   5556: 	    } elsif ($on eq 'number') {
                   5557: 		$answer=$args->{'response'}+1;
                   5558: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5559: 	    } else {
1.497     foxr     5560: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5561: 	    }
1.497     foxr     5562: 	    &scan_data($scan_data,
1.503     raeburn  5563: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5564: 	}
1.497     foxr     5565: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5566: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5567:     }
                   5568:     return $line;
                   5569: }
1.423     albertel 5570: 
                   5571: =pod
                   5572: 
                   5573: =item scan_data
                   5574: 
                   5575:     Edit or look up  an item in the scan_data hash.
                   5576: 
                   5577:   Arguments:
                   5578:     $scan_data  - The hash (see scantron_getfile)
                   5579:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5580:                   scantronfilename_key).
1.423     albertel 5581:     $data        - New value of the hash entry.
                   5582:     $delete      - If true, the entry is removed from the hash.
                   5583: 
                   5584:   Returns:
                   5585:     The new value of the hash table field (undefined if deleted).
                   5586: 
                   5587: =cut
                   5588: 
                   5589: 
1.157     albertel 5590: sub scan_data {
                   5591:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5592:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5593:     if (defined($value)) {
                   5594: 	$scan_data->{$filename.'_'.$key} = $value;
                   5595:     }
                   5596:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5597:     return $scan_data->{$filename.'_'.$key};
                   5598: }
1.423     albertel 5599: 
1.495     albertel 5600: # ----- These first few routines are general use routines.----
                   5601: 
                   5602: # Return the number of occurences of a pattern in a string.
                   5603: 
                   5604: sub occurence_count {
                   5605:     my ($string, $pattern) = @_;
                   5606: 
                   5607:     my @matches = ($string =~ /$pattern/g);
                   5608: 
                   5609:     return scalar(@matches);
                   5610: }
                   5611: 
                   5612: 
                   5613: # Take a string known to have digits and convert all the
                   5614: # digits into letters in the range J,A..I.
                   5615: 
                   5616: sub digits_to_letters {
                   5617:     my ($input) = @_;
                   5618: 
                   5619:     my @alphabet = ('J', 'A'..'I');
                   5620: 
                   5621:     my @input    = split(//, $input);
                   5622:     my $output ='';
                   5623:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5624: 	if ($input[$i] =~ /\d/) {
                   5625: 	    $output .= $alphabet[$input[$i]];
                   5626: 	} else {
                   5627: 	    $output .= $input[$i];
                   5628: 	}
                   5629:     }
                   5630:     return $output;
                   5631: }
                   5632: 
1.423     albertel 5633: =pod 
                   5634: 
                   5635: =item scantron_parse_scanline
                   5636: 
                   5637:   Decodes a scanline from the selected scantron file
                   5638: 
                   5639:  Arguments:
                   5640:     line             - The text of the scantron file line to process
                   5641:     whichline        - Line number
                   5642:     scantron_config  - Hash describing the format of the scantron lines.
                   5643:     scan_data        - Hash of extra information about the scanline
                   5644:                        (see scantron_getfile for more information)
                   5645:     just_header      - True if should not process question answers but only
                   5646:                        the stuff to the left of the answers.
                   5647:  Returns:
                   5648:    Hash containing the result of parsing the scanline
                   5649: 
                   5650:    Keys are all proceeded by the string 'scantron.'
                   5651: 
                   5652:        CODE    - the CODE in use for this scanline
                   5653:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5654:                  by the operator
                   5655:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5656:                             CODEs were selected, but the usage has been
                   5657:                             forced by the operator
1.556     weissno  5658:        ID  - student/employee ID
1.423     albertel 5659:        PaperID - if used, the ID number printed on the sheet when the 
                   5660:                  paper was scanned
                   5661:        FirstName - first name from the sheet
                   5662:        LastName  - last name from the sheet
                   5663: 
                   5664:      if just_header was not true these key may also exist
                   5665: 
1.447     foxr     5666:        missingerror - a list of bubble ranges that are considered to be answers
                   5667:                       to a single question that don't have any bubbles filled in.
                   5668:                       Of the form questionnumber:firstbubblenumber:count.
                   5669:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5670:                       to a single question that have more than one bubble filled in.
                   5671:                       Of the form questionnumber::firstbubblenumber:count
                   5672:    
                   5673:                 In the above, count is the number of bubble responses in the
                   5674:                 input line needed to represent the possible answers to the question.
                   5675:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5676:                 per line would have count = 2.
                   5677: 
1.423     albertel 5678:        maxquest     - the number of the last bubble line that was parsed
                   5679: 
                   5680:        (<number> starts at 1)
                   5681:        <number>.answer - zero or more letters representing the selected
                   5682:                          letters from the scanline for the bubble line 
                   5683:                          <number>.
                   5684:                          if blank there was either no bubble or there where
                   5685:                          multiple bubbles, (consult the keys missingerror and
                   5686:                          doubleerror if this is an error condition)
                   5687: 
                   5688: =cut
                   5689: 
1.82      albertel 5690: sub scantron_parse_scanline {
1.423     albertel 5691:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5692: 
1.82      albertel 5693:     my %record;
1.550     raeburn  5694:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5695:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5696:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5697:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5698: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5699: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5700: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5701: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5702: 	    $record{'scantron.CODE'}=substr($data,
                   5703: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5704: 					    $$scantron_config{'CODElength'});
1.191     albertel 5705: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5706: 		$record{'scantron.useCODE'}=1;
                   5707: 	    }
1.192     albertel 5708: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5709: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5710: 	    }
1.82      albertel 5711: 	} else {
                   5712: 	    #FIXME interpret first N questions
                   5713: 	}
                   5714:     }
1.83      albertel 5715:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5716: 				  $$scantron_config{'IDlength'});
1.157     albertel 5717:     $record{'scantron.PaperID'}=
                   5718: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5719: 	       $$scantron_config{'PaperIDlength'});
                   5720:     $record{'scantron.FirstName'}=
                   5721: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5722: 	       $$scantron_config{'FirstNamelength'});
                   5723:     $record{'scantron.LastName'}=
                   5724: 	substr($data,$$scantron_config{'LastName'}-1,
                   5725: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5726:     if ($just_header) { return \%record; }
1.194     albertel 5727: 
1.82      albertel 5728:     my @alphabet=('A'..'Z');
                   5729:     my $questnum=0;
1.447     foxr     5730:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5731: 
1.470     foxr     5732:     chomp($questions);		# Get rid of any trailing \n.
                   5733:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5734:     while (length($questions)) {
1.447     foxr     5735: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5736:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5737:                              || 1;
                   5738:         $questnum++;
                   5739:         my $quest_id = $questnum;
                   5740:         my $currentquest = substr($questions,0,$answer_length);
                   5741:         $questions       = substr($questions,$answer_length);
                   5742:         if (length($currentquest) < $answer_length) { next; }
                   5743: 
                   5744:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5745:             my $subquestnum = 1;
                   5746:             my $subquestions = $currentquest;
                   5747:             my @subanswers_needed = 
                   5748:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5749:             foreach my $subans (@subanswers_needed) {
                   5750:                 my $subans_length =
                   5751:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5752:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5753:                 $subquestions   = substr($subquestions,$subans_length);
                   5754:                 $quest_id = "$questnum.$subquestnum";
                   5755:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5756:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5757:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5758:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5759:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5760:                 } else {
                   5761:                     $ansnum = &scantron_validator_positional($ansnum,
                   5762:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5763:                 }
                   5764:                 $subquestnum ++;
                   5765:             }
                   5766:         } else {
                   5767:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5768:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5769:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5770:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5771:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5772:             } else {
                   5773:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5774:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5775:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5776:             }
                   5777:         }
                   5778:     }
                   5779:     $record{'scantron.maxquest'}=$questnum;
                   5780:     return \%record;
                   5781: }
1.447     foxr     5782: 
1.503     raeburn  5783: sub scantron_validator_lettnum {
                   5784:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5785:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5786: 
                   5787:     # Qon 'letter' implies for each slot in currquest we have:
                   5788:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5789:     #    about anything else (esp. a value of Qoff) for missing
                   5790:     #    bubbles.
                   5791:     #
                   5792:     # Qon 'number' implies each slot gives a digit that indexes the
                   5793:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5794:     #    and * or ? for double bubbles on a single line.
                   5795:     #
1.447     foxr     5796: 
1.503     raeburn  5797:     my $matchon;
                   5798:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5799:         $matchon = '[A-Z]';
                   5800:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5801:         $matchon = '\d';
                   5802:     }
                   5803:     my $occurrences = 0;
                   5804:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5805:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5806:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5807:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5808:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5809:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5810:         my @singlelines = split('',$currquest);
                   5811:         foreach my $entry (@singlelines) {
                   5812:             $occurrences = &occurence_count($entry,$matchon);
                   5813:             if ($occurrences > 1) {
                   5814:                 last;
                   5815:             }
                   5816:         } 
                   5817:     } else {
                   5818:         $occurrences = &occurence_count($currquest,$matchon); 
                   5819:     }
                   5820:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5821:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5822:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5823:             my $bubble = substr($currquest,$ans,1);
                   5824:             if ($bubble =~ /$matchon/ ) {
                   5825:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5826:                     if ($bubble == 0) {
                   5827:                         $bubble = 10; 
                   5828:                     }
                   5829:                     $record->{"scantron.$ansnum.answer"} = 
                   5830:                         $alphabet->[$bubble-1];
                   5831:                 } else {
                   5832:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5833:                 }
                   5834:             } else {
                   5835:                 $record->{"scantron.$ansnum.answer"}='';
                   5836:             }
                   5837:             $ansnum++;
                   5838:         }
                   5839:     } elsif (!defined($currquest)
                   5840:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5841:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5842:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5843:             $record->{"scantron.$ansnum.answer"}='';
                   5844:             $ansnum++;
                   5845:         }
                   5846:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5847:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5848:         }
                   5849:     } else {
                   5850:         if ($$scantron_config{'Qon'} eq 'number') {
                   5851:             $currquest = &digits_to_letters($currquest);            
                   5852:         }
                   5853:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5854:             my $bubble = substr($currquest,$ans,1);
                   5855:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5856:             $ansnum++;
                   5857:         }
                   5858:     }
                   5859:     return $ansnum;
                   5860: }
1.447     foxr     5861: 
1.503     raeburn  5862: sub scantron_validator_positional {
                   5863:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5864:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5865: 
1.503     raeburn  5866:     # Otherwise there's a positional notation;
                   5867:     # each bubble line requires Qlength items, and there are filled in
                   5868:     # bubbles for each case where there 'Qon' characters.
                   5869:     #
1.447     foxr     5870: 
1.503     raeburn  5871:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5872: 
1.503     raeburn  5873:     # If the split only gives us one element.. the full length of the
                   5874:     # answer string, no bubbles are filled in:
1.447     foxr     5875: 
1.507     raeburn  5876:     if ($answers_needed eq '') {
                   5877:         return;
                   5878:     }
                   5879: 
1.503     raeburn  5880:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5881:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5882:             $record->{"scantron.$ansnum.answer"}='';
                   5883:             $ansnum++;
                   5884:         }
                   5885:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5886:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5887:         }
                   5888:     } elsif (scalar(@array) == 2) {
                   5889:         my $location = length($array[0]);
                   5890:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5891:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5892:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5893:             if ($ans eq $line_num) {
                   5894:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5895:             } else {
                   5896:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5897:             }
                   5898:             $ansnum++;
                   5899:          }
                   5900:     } else {
                   5901:         #  If there's more than one instance of a bubble character
                   5902:         #  That's a double bubble; with positional notation we can
                   5903:         #  record all the bubbles filled in as well as the
                   5904:         #  fact this response consists of multiple bubbles.
                   5905:         #
                   5906:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5907:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5908:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5909:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5910:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5911:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5912:             my $doubleerror = 0;
                   5913:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5914:                    (!$doubleerror)) {
                   5915:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5916:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5917:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5918:                if (length(@currarray) > 2) {
                   5919:                    $doubleerror = 1;
                   5920:                } 
                   5921:             }
                   5922:             if ($doubleerror) {
                   5923:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5924:             }
                   5925:         } else {
                   5926:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5927:         }
                   5928:         my $item = $ansnum;
                   5929:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5930:             $record->{"scantron.$item.answer"} = '';
                   5931:             $item ++;
                   5932:         }
1.447     foxr     5933: 
1.503     raeburn  5934:         my @ans=@array;
                   5935:         my $i=0;
                   5936:         my $increment = 0;
                   5937:         while ($#ans) {
                   5938:             $i+=length($ans[0]) + $increment;
                   5939:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5940:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5941:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5942:             shift(@ans);
                   5943:             $increment = 1;
                   5944:         }
                   5945:         $ansnum += $answers_needed;
1.82      albertel 5946:     }
1.503     raeburn  5947:     return $ansnum;
1.82      albertel 5948: }
                   5949: 
1.423     albertel 5950: =pod
                   5951: 
                   5952: =item scantron_add_delay
                   5953: 
                   5954:    Adds an error message that occurred during the grading phase to a
                   5955:    queue of messages to be shown after grading pass is complete
                   5956: 
                   5957:  Arguments:
1.424     albertel 5958:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5959:    $scanline    - the scanline that caused the error
                   5960:    $errormesage - the error message
                   5961:    $errorcode   - a numeric code for the error
                   5962: 
                   5963:  Side Effects:
1.424     albertel 5964:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5965: 
                   5966: =cut
                   5967: 
1.82      albertel 5968: sub scantron_add_delay {
1.140     albertel 5969:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5970:     push(@$delayqueue,
                   5971: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5972: 	  'ecode' => $errorcode }
                   5973: 	 );
1.82      albertel 5974: }
                   5975: 
1.423     albertel 5976: =pod
                   5977: 
                   5978: =item scantron_find_student
                   5979: 
1.424     albertel 5980:    Finds the username for the current scanline
                   5981: 
                   5982:   Arguments:
                   5983:    $scantron_record - hash result from scantron_parse_scanline
                   5984:    $scan_data       - hash of correction information 
                   5985:                       (see &scantron_getfile() form more information)
                   5986:    $idmap           - hash from &username_to_idmap()
                   5987:    $line            - number of current scanline
                   5988:  
                   5989:   Returns:
                   5990:    Either 'username:domain' or undef if unknown
                   5991: 
1.423     albertel 5992: =cut
                   5993: 
1.82      albertel 5994: sub scantron_find_student {
1.157     albertel 5995:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5996:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5997:     if ($scanID =~ /^\s*$/) {
                   5998:  	return &scan_data($scan_data,"$line.user");
                   5999:     }
1.83      albertel 6000:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6001:  	if (lc($id) eq lc($scanID)) {
                   6002:  	    return $$idmap{$id};
                   6003:  	}
1.83      albertel 6004:     }
                   6005:     return undef;
                   6006: }
                   6007: 
1.423     albertel 6008: =pod
                   6009: 
                   6010: =item scantron_filter
                   6011: 
1.424     albertel 6012:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6013:    hidden resources was selected
                   6014: 
1.423     albertel 6015: =cut
                   6016: 
1.83      albertel 6017: sub scantron_filter {
                   6018:     my ($curres)=@_;
1.331     albertel 6019: 
                   6020:     if (ref($curres) && $curres->is_problem()) {
                   6021: 	# if the user has asked to not have either hidden
                   6022: 	# or 'randomout' controlled resources to be graded
                   6023: 	# don't include them
                   6024: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6025: 	    && $curres->randomout) {
                   6026: 	    return 0;
                   6027: 	}
1.83      albertel 6028: 	return 1;
                   6029:     }
                   6030:     return 0;
1.82      albertel 6031: }
                   6032: 
1.423     albertel 6033: =pod
                   6034: 
                   6035: =item scantron_process_corrections
                   6036: 
1.424     albertel 6037:    Gets correction information out of submitted form data and corrects
                   6038:    the scanline
                   6039: 
1.423     albertel 6040: =cut
                   6041: 
1.157     albertel 6042: sub scantron_process_corrections {
                   6043:     my ($r) = @_;
1.257     albertel 6044:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6045:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6046:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6047:     my $which=$env{'form.scantron_line'};
1.200     albertel 6048:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6049:     my ($skip,$err,$errmsg);
1.257     albertel 6050:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6051: 	$skip=1;
1.257     albertel 6052:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6053: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6054: 	    $env{'form.scantron_domain'};
1.157     albertel 6055: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6056: 	($line,$err,$errmsg)=
                   6057: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6058: 				     'ID',{'newid'=>$newid,
1.257     albertel 6059: 				    'username'=>$env{'form.scantron_username'},
                   6060: 				    'domain'=>$env{'form.scantron_domain'}});
                   6061:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6062: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6063: 	my $newCODE;
1.192     albertel 6064: 	my %args;
1.190     albertel 6065: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6066: 	    $newCODE='use_unfound';
1.190     albertel 6067: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6068: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6069: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6070: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6071: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6072: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6073: 	}
1.257     albertel 6074: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6075: 	    $args{'CODE_ignore_dup'}=1;
                   6076: 	}
                   6077: 	$args{'CODE'}=$newCODE;
1.186     albertel 6078: 	($line,$err,$errmsg)=
                   6079: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6080: 				     'CODE',\%args);
1.257     albertel 6081:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6082: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6083: 	    ($line,$err,$errmsg)=
                   6084: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6085: 					 $which,'answer',
                   6086: 					 { 'question'=>$question,
1.503     raeburn  6087: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6088:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6089: 	    if ($err) { last; }
                   6090: 	}
                   6091:     }
                   6092:     if ($err) {
1.398     albertel 6093: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6094:     } else {
1.200     albertel 6095: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6096: 	&scantron_putfile($scanlines,$scan_data);
                   6097:     }
                   6098: }
                   6099: 
1.423     albertel 6100: =pod
                   6101: 
                   6102: =item reset_skipping_status
                   6103: 
1.424     albertel 6104:    Forgets the current set of remember skipped scanlines (and thus
                   6105:    reverts back to considering all lines in the
                   6106:    scantron_skipped_<filename> file)
                   6107: 
1.423     albertel 6108: =cut
                   6109: 
1.200     albertel 6110: sub reset_skipping_status {
                   6111:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6112:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6113:     &scantron_putfile(undef,$scan_data);
                   6114: }
                   6115: 
1.423     albertel 6116: =pod
                   6117: 
                   6118: =item start_skipping
                   6119: 
1.424     albertel 6120:    Marks a scanline to be skipped. 
                   6121: 
1.423     albertel 6122: =cut
                   6123: 
1.376     albertel 6124: sub start_skipping {
1.200     albertel 6125:     my ($scan_data,$i)=@_;
                   6126:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6127:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6128: 	$remembered{$i}=2;
                   6129:     } else {
                   6130: 	$remembered{$i}=1;
                   6131:     }
1.200     albertel 6132:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6133: }
                   6134: 
1.423     albertel 6135: =pod
                   6136: 
                   6137: =item should_be_skipped
                   6138: 
1.424     albertel 6139:    Checks whether a scanline should be skipped.
                   6140: 
1.423     albertel 6141: =cut
                   6142: 
1.200     albertel 6143: sub should_be_skipped {
1.376     albertel 6144:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6145:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6146: 	# not redoing old skips
1.376     albertel 6147: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6148: 	return 0;
                   6149:     }
                   6150:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6151: 
                   6152:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6153: 	return 0;
                   6154:     }
1.200     albertel 6155:     return 1;
                   6156: }
                   6157: 
1.423     albertel 6158: =pod
                   6159: 
                   6160: =item remember_current_skipped
                   6161: 
1.424     albertel 6162:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6163:    file and remembers them into scan_data for later use.
                   6164: 
1.423     albertel 6165: =cut
                   6166: 
1.200     albertel 6167: sub remember_current_skipped {
                   6168:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6169:     my %to_remember;
                   6170:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6171: 	if ($scanlines->{'skipped'}[$i]) {
                   6172: 	    $to_remember{$i}=1;
                   6173: 	}
                   6174:     }
1.376     albertel 6175: 
1.200     albertel 6176:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6177:     &scantron_putfile(undef,$scan_data);
                   6178: }
                   6179: 
1.423     albertel 6180: =pod
                   6181: 
                   6182: =item check_for_error
                   6183: 
1.424     albertel 6184:     Checks if there was an error when attempting to remove a specific
1.659   ! raeburn  6185:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6186:     something went wrong.
                   6187: 
1.423     albertel 6188: =cut
                   6189: 
1.200     albertel 6190: sub check_for_error {
                   6191:     my ($r,$result)=@_;
                   6192:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6193: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6194:     }
                   6195: }
1.157     albertel 6196: 
1.423     albertel 6197: =pod
                   6198: 
                   6199: =item scantron_warning_screen
                   6200: 
1.424     albertel 6201:    Interstitial screen to make sure the operator has selected the
                   6202:    correct options before we start the validation phase.
                   6203: 
1.423     albertel 6204: =cut
                   6205: 
1.203     albertel 6206: sub scantron_warning_screen {
1.650     raeburn  6207:     my ($button_text,$symb)=@_;
1.257     albertel 6208:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6209:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6210:     my $CODElist;
1.284     albertel 6211:     if ($scantron_config{'CODElocation'} &&
                   6212: 	$scantron_config{'CODEstart'} &&
                   6213: 	$scantron_config{'CODElength'}) {
                   6214: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6215: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6216: 	$CODElist=
1.492     albertel 6217: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6218: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6219:     }
1.492     albertel 6220:     return ('
1.203     albertel 6221: <p>
1.492     albertel 6222: <span class="LC_warning">
                   6223: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6224: </p>
                   6225: <table>
1.492     albertel 6226: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6227: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6228: '.$CODElist.'
1.203     albertel 6229: </table>
1.650     raeburn  6230: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
                   6231: '.&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 6232: 
                   6233: <br />
1.492     albertel 6234: ');
1.203     albertel 6235: }
                   6236: 
1.423     albertel 6237: =pod
                   6238: 
                   6239: =item scantron_do_warning
                   6240: 
1.424     albertel 6241:    Check if the operator has picked something for all required
                   6242:    fields. Error out if something is missing.
                   6243: 
1.423     albertel 6244: =cut
                   6245: 
1.203     albertel 6246: sub scantron_do_warning {
1.608     www      6247:     my ($r,$symb)=@_;
1.203     albertel 6248:     if (!$symb) {return '';}
1.324     albertel 6249:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6250:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6251:     if ( $env{'form.selectpage'} eq '' ||
                   6252: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6253: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6254: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6255: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6256: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6257: 	} 
1.257     albertel 6258: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6259: 	    $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 6260: 	} 
1.257     albertel 6261: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6262: 	    $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 6263: 	} 
                   6264:     } else {
1.650     raeburn  6265: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.492     albertel 6266: 	$r->print('
                   6267: '.$warning.'
                   6268: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6269: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6270: ');
1.237     albertel 6271:     }
1.614     www      6272:     $r->print("</form><br />");
1.203     albertel 6273:     return '';
                   6274: }
                   6275: 
1.423     albertel 6276: =pod
                   6277: 
                   6278: =item scantron_form_start
                   6279: 
1.424     albertel 6280:     html hidden input for remembering all selected grading options
                   6281: 
1.423     albertel 6282: =cut
                   6283: 
1.203     albertel 6284: sub scantron_form_start {
                   6285:     my ($max_bubble)=@_;
                   6286:     my $result= <<SCANTRONFORM;
                   6287: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6288:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6289:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6290:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6291:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6292:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6293:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6294:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6295:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6296:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6297: SCANTRONFORM
1.447     foxr     6298: 
                   6299:   my $line = 0;
                   6300:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6301:        my $chunk =
                   6302: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6303:        $chunk .=
                   6304: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6305:        $chunk .= 
                   6306:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6307:        $chunk .=
                   6308:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6309:        $result .= $chunk;
                   6310:        $line++;
                   6311:    }
1.203     albertel 6312:     return $result;
                   6313: }
                   6314: 
1.423     albertel 6315: =pod
                   6316: 
                   6317: =item scantron_validate_file
                   6318: 
1.659   ! raeburn  6319:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6320: 
                   6321:     Also processes any necessary information resets that need to
                   6322:     occur before validation begins (ignore previous corrections,
                   6323:     restarting the skipped records processing)
                   6324: 
1.423     albertel 6325: =cut
                   6326: 
1.157     albertel 6327: sub scantron_validate_file {
1.608     www      6328:     my ($r,$symb) = @_;
1.157     albertel 6329:     if (!$symb) {return '';}
1.324     albertel 6330:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6331:     
                   6332:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6333:     # them when doing the corrections reset
1.257     albertel 6334:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6335: 	&reset_skipping_status();
                   6336:     }
1.257     albertel 6337:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6338: 	&remember_current_skipped();
1.257     albertel 6339: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6340:     }
                   6341: 
1.257     albertel 6342:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6343: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6344: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6345: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6346: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6347:     }
1.200     albertel 6348: 
1.257     albertel 6349:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6350: 	&scantron_process_corrections($r);
                   6351:     }
1.503     raeburn  6352:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6353:     #get the student pick code ready
                   6354:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6355:     my $nav_error;
1.649     raeburn  6356:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6357:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6358:     if ($nav_error) {
                   6359:         $r->print(&navmap_errormsg());
                   6360:         return '';
                   6361:     }
1.203     albertel 6362:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6363:     $r->print($result);
                   6364:     
1.334     albertel 6365:     my @validate_phases=( 'sequence',
                   6366: 			  'ID',
1.157     albertel 6367: 			  'CODE',
                   6368: 			  'doublebubble',
                   6369: 			  'missingbubbles');
1.257     albertel 6370:     if (!$env{'form.validatepass'}) {
                   6371: 	$env{'form.validatepass'} = 0;
1.157     albertel 6372:     }
1.257     albertel 6373:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6374: 
1.448     foxr     6375: 
1.157     albertel 6376:     my $stop=0;
                   6377:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6378: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6379: 	$r->rflush();
                   6380: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6381: 	{
                   6382: 	    no strict 'refs';
                   6383: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6384: 	}
                   6385:     }
                   6386:     if (!$stop) {
1.650     raeburn  6387: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6388: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6389:                   $warning.
                   6390:                   &mt('Perform verification for each student after storage of submissions?').
                   6391:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6392:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6393:                   ('&nbsp;'x3).'<label>'.
                   6394:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6395:                   '</label></span><br />'.
                   6396:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6397:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6398:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6399:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6400:     } else {
                   6401: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6402: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6403:     }
                   6404:     if ($stop) {
1.334     albertel 6405: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6406: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6407: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6408: 
1.650     raeburn  6409: 	    $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 6410: 	} else {
1.503     raeburn  6411:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6412: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6413:             } else {
1.539     riegler  6414:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6415:             }
1.492     albertel 6416: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6417: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6418: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6419: 	}
1.157     albertel 6420:     }
1.614     www      6421:     $r->print(" </form><br />");
1.157     albertel 6422:     return '';
                   6423: }
                   6424: 
1.423     albertel 6425: 
                   6426: =pod
                   6427: 
                   6428: =item scantron_remove_file
                   6429: 
1.659   ! raeburn  6430:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6431:    scantron_original_<filename> is never removed
                   6432: 
                   6433: 
1.423     albertel 6434: =cut
                   6435: 
1.200     albertel 6436: sub scantron_remove_file {
1.192     albertel 6437:     my ($which)=@_;
1.257     albertel 6438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6440:     my $file='scantron_';
1.200     albertel 6441:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6442: 	$file.=$which.'_';
1.192     albertel 6443:     } else {
                   6444: 	return 'refused';
                   6445:     }
1.257     albertel 6446:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6447:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6448: }
                   6449: 
1.423     albertel 6450: 
                   6451: =pod
                   6452: 
                   6453: =item scantron_remove_scan_data
                   6454: 
1.659   ! raeburn  6455:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6456:    data file.  (In the case that both the are doing skipped records we need
                   6457:    to remember the old skipped lines for the time being so that element
                   6458:    persists for a while.)
                   6459: 
1.423     albertel 6460: =cut
                   6461: 
1.200     albertel 6462: sub scantron_remove_scan_data {
1.257     albertel 6463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6465:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6466:     my @todelete;
1.257     albertel 6467:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6468:     foreach my $key (@keys) {
                   6469: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6470: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6471: 		$key=~/remember_skipping/) {
                   6472: 		next;
                   6473: 	    }
1.192     albertel 6474: 	    push(@todelete,$key);
                   6475: 	}
                   6476:     }
1.200     albertel 6477:     my $result;
1.192     albertel 6478:     if (@todelete) {
1.491     albertel 6479: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6480: 				       \@todelete,$cdom,$cname);
                   6481:     } else {
                   6482: 	$result = 'ok';
1.192     albertel 6483:     }
                   6484:     return $result;
                   6485: }
                   6486: 
1.423     albertel 6487: 
                   6488: =pod
                   6489: 
                   6490: =item scantron_getfile
                   6491: 
1.659   ! raeburn  6492:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6493:     the scan_data hash
                   6494:   
                   6495:   Arguments:
                   6496:     None
                   6497: 
                   6498:   Returns:
                   6499:     2 hash references
                   6500: 
                   6501:      - first one has 
                   6502:          orig      -
                   6503:          corrected -
                   6504:          skipped   -  each of which points to an array ref of the specified
                   6505:                       file broken up into individual lines
                   6506:          count     - number of scanlines
                   6507:  
                   6508:      - second is the scan_data hash possible keys are
1.425     albertel 6509:        ($number refers to scanline numbered $number and thus the key affects
                   6510:         only that scanline
                   6511:         $bubline refers to the specific bubble line element and the aspects
                   6512:         refers to that specific bubble line element)
                   6513: 
                   6514:        $number.user - username:domain to use
                   6515:        $number.CODE_ignore_dup 
                   6516:                     - ignore the duplicate CODE error 
                   6517:        $number.useCODE
                   6518:                     - use the CODE in the scanline as is
                   6519:        $number.no_bubble.$bubline
                   6520:                     - it is valid that there is no bubbled in bubble
                   6521:                       at $number $bubline
                   6522:        remember_skipping
                   6523:                     - a frozen hash containing keys of $number and values
                   6524:                       of either 
                   6525:                         1 - we are on a 'do skipped records pass' and plan
                   6526:                             on processing this line
                   6527:                         2 - we are on a 'do skipped records pass' and this
                   6528:                             scanline has been marked to skip yet again
1.424     albertel 6529: 
1.423     albertel 6530: =cut
                   6531: 
1.157     albertel 6532: sub scantron_getfile {
1.200     albertel 6533:     #FIXME really would prefer a scantron directory
1.257     albertel 6534:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6535:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6536:     my $lines;
                   6537:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6538: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6539:     my %scanlines;
                   6540:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6541:     my $temp=$scanlines{'orig'};
                   6542:     $scanlines{'count'}=$#$temp;
                   6543: 
                   6544:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6545: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6546:     if ($lines eq '-1') {
                   6547: 	$scanlines{'corrected'}=[];
                   6548:     } else {
                   6549: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6550:     }
                   6551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6552: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6553:     if ($lines eq '-1') {
                   6554: 	$scanlines{'skipped'}=[];
                   6555:     } else {
                   6556: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6557:     }
1.175     albertel 6558:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6559:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6560:     my %scan_data = @tmp;
                   6561:     return (\%scanlines,\%scan_data);
                   6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item lonnet_putfile
                   6567: 
1.424     albertel 6568:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6569: 
                   6570:  Arguments:
                   6571:    $contents - data to store
                   6572:    $filename - filename to store $contents into
                   6573: 
                   6574:  Returns:
                   6575:    result value from &Apache::lonnet::finishuserfileupload
                   6576: 
1.423     albertel 6577: =cut
                   6578: 
1.157     albertel 6579: sub lonnet_putfile {
                   6580:     my ($contents,$filename)=@_;
1.257     albertel 6581:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6582:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6583:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6584:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6585: 
                   6586: }
                   6587: 
1.423     albertel 6588: =pod
                   6589: 
                   6590: =item scantron_putfile
                   6591: 
1.659   ! raeburn  6592:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6593:     scan_data hash. (Does not modify the original version only the
                   6594:     corrected and skipped versions.
                   6595: 
                   6596:  Arguments:
                   6597:     $scanlines - hash ref that looks like the first return value from
                   6598:                  &scantron_getfile()
                   6599:     $scan_data - hash ref that looks like the second return value from
                   6600:                  &scantron_getfile()
                   6601: 
1.423     albertel 6602: =cut
                   6603: 
1.157     albertel 6604: sub scantron_putfile {
                   6605:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6606:     #FIXME really would prefer a scantron directory
1.257     albertel 6607:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6608:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6609:     if ($scanlines) {
                   6610: 	my $prefix='scantron_';
1.157     albertel 6611: # no need to update orig, shouldn't change
                   6612: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6613: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6614: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6615: 			$prefix.'corrected_'.
1.257     albertel 6616: 			$env{'form.scantron_selectfile'});
1.200     albertel 6617: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6618: 			$prefix.'skipped_'.
1.257     albertel 6619: 			$env{'form.scantron_selectfile'});
1.200     albertel 6620:     }
1.175     albertel 6621:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6622: }
                   6623: 
1.423     albertel 6624: =pod
                   6625: 
                   6626: =item scantron_get_line
                   6627: 
1.424     albertel 6628:    Returns the correct version of the scanline
                   6629: 
                   6630:  Arguments:
                   6631:     $scanlines - hash ref that looks like the first return value from
                   6632:                  &scantron_getfile()
                   6633:     $scan_data - hash ref that looks like the second return value from
                   6634:                  &scantron_getfile()
                   6635:     $i         - number of the requested line (starts at 0)
                   6636: 
                   6637:  Returns:
                   6638:    A scanline, (either the original or the corrected one if it
                   6639:    exists), or undef if the requested scanline should be
                   6640:    skipped. (Either because it's an skipped scanline, or it's an
                   6641:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6642:    pass.
                   6643: 
1.423     albertel 6644: =cut
                   6645: 
1.157     albertel 6646: sub scantron_get_line {
1.200     albertel 6647:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6648:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6649:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6650:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6651:     return $scanlines->{'orig'}[$i]; 
                   6652: }
                   6653: 
1.423     albertel 6654: =pod
                   6655: 
                   6656: =item scantron_todo_count
                   6657: 
1.424     albertel 6658:     Counts the number of scanlines that need processing.
                   6659: 
                   6660:  Arguments:
                   6661:     $scanlines - hash ref that looks like the first return value from
                   6662:                  &scantron_getfile()
                   6663:     $scan_data - hash ref that looks like the second return value from
                   6664:                  &scantron_getfile()
                   6665: 
                   6666:  Returns:
                   6667:     $count - number of scanlines to process
                   6668: 
1.423     albertel 6669: =cut
                   6670: 
1.200     albertel 6671: sub get_todo_count {
                   6672:     my ($scanlines,$scan_data)=@_;
                   6673:     my $count=0;
                   6674:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6675: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6676: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6677: 	$count++;
                   6678:     }
                   6679:     return $count;
                   6680: }
                   6681: 
1.423     albertel 6682: =pod
                   6683: 
                   6684: =item scantron_put_line
                   6685: 
1.659   ! raeburn  6686:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 6687:     data file.
                   6688: 
                   6689:  Arguments:
                   6690:     $scanlines - hash ref that looks like the first return value from
                   6691:                  &scantron_getfile()
                   6692:     $scan_data - hash ref that looks like the second return value from
                   6693:                  &scantron_getfile()
                   6694:     $i         - line number to update
                   6695:     $newline   - contents of the updated scanline
                   6696:     $skip      - if true make the line for skipping and update the
                   6697:                  'skipped' file
                   6698: 
1.423     albertel 6699: =cut
                   6700: 
1.157     albertel 6701: sub scantron_put_line {
1.200     albertel 6702:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6703:     if ($skip) {
                   6704: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6705: 	&start_skipping($scan_data,$i);
1.157     albertel 6706: 	return;
                   6707:     }
                   6708:     $scanlines->{'corrected'}[$i]=$newline;
                   6709: }
                   6710: 
1.423     albertel 6711: =pod
                   6712: 
                   6713: =item scantron_clear_skip
                   6714: 
1.424     albertel 6715:    Remove a line from the 'skipped' file
                   6716: 
                   6717:  Arguments:
                   6718:     $scanlines - hash ref that looks like the first return value from
                   6719:                  &scantron_getfile()
                   6720:     $scan_data - hash ref that looks like the second return value from
                   6721:                  &scantron_getfile()
                   6722:     $i         - line number to update
                   6723: 
1.423     albertel 6724: =cut
                   6725: 
1.376     albertel 6726: sub scantron_clear_skip {
                   6727:     my ($scanlines,$scan_data,$i)=@_;
                   6728:     if (exists($scanlines->{'skipped'}[$i])) {
                   6729: 	undef($scanlines->{'skipped'}[$i]);
                   6730: 	return 1;
                   6731:     }
                   6732:     return 0;
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_filter_not_exam
                   6738: 
1.424     albertel 6739:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6740:    filter out resources that are not marked as 'exam' mode
                   6741: 
1.423     albertel 6742: =cut
                   6743: 
1.334     albertel 6744: sub scantron_filter_not_exam {
                   6745:     my ($curres)=@_;
                   6746:     
                   6747:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6748: 	# if the user has asked to not have either hidden
                   6749: 	# or 'randomout' controlled resources to be graded
                   6750: 	# don't include them
                   6751: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6752: 	    && $curres->randomout) {
                   6753: 	    return 0;
                   6754: 	}
                   6755: 	return 1;
                   6756:     }
                   6757:     return 0;
                   6758: }
                   6759: 
1.423     albertel 6760: =pod
                   6761: 
                   6762: =item scantron_validate_sequence
                   6763: 
1.424     albertel 6764:     Validates the selected sequence, checking for resource that are
                   6765:     not set to exam mode.
                   6766: 
1.423     albertel 6767: =cut
                   6768: 
1.334     albertel 6769: sub scantron_validate_sequence {
                   6770:     my ($r,$currentphase) = @_;
                   6771: 
                   6772:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6773:     unless (ref($navmap)) {
                   6774:         $r->print(&navmap_errormsg());
                   6775:         return (1,$currentphase);
                   6776:     }
1.334     albertel 6777:     my (undef,undef,$sequence)=
                   6778: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6779: 
                   6780:     my $map=$navmap->getResourceByUrl($sequence);
                   6781: 
                   6782:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6783:                                     value="ignore" />');
                   6784:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6785: 	my @resources=
                   6786: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6787: 	if (@resources) {
1.357     banghart 6788: 	    $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 6789: 	    return (1,$currentphase);
                   6790: 	}
                   6791:     }
                   6792: 
                   6793:     return (0,$currentphase+1);
                   6794: }
                   6795: 
1.423     albertel 6796: 
                   6797: 
1.157     albertel 6798: sub scantron_validate_ID {
                   6799:     my ($r,$currentphase) = @_;
                   6800:     
                   6801:     #get student info
                   6802:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6803:     my %idmap=&username_to_idmap($classlist);
                   6804: 
                   6805:     #get scantron line setup
1.257     albertel 6806:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6807:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6808: 
                   6809:     my $nav_error;
1.649     raeburn  6810:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6811:     if ($nav_error) {
                   6812:         $r->print(&navmap_errormsg());
                   6813:         return(1,$currentphase);
                   6814:     }
1.157     albertel 6815: 
                   6816:     my %found=('ids'=>{},'usernames'=>{});
                   6817:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6818: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6819: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6820: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6821: 						 $scan_data);
                   6822: 	my $id=$$scan_record{'scantron.ID'};
                   6823: 	my $found;
                   6824: 	foreach my $checkid (keys(%idmap)) {
                   6825: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6826: 	}
                   6827: 	if ($found) {
                   6828: 	    my $username=$idmap{$found};
                   6829: 	    if ($found{'ids'}{$found}) {
                   6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6831: 					 $line,'duplicateID',$found);
1.194     albertel 6832: 		return(1,$currentphase);
1.157     albertel 6833: 	    } elsif ($found{'usernames'}{$username}) {
                   6834: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6835: 					 $line,'duplicateID',$username);
1.194     albertel 6836: 		return(1,$currentphase);
1.157     albertel 6837: 	    }
1.186     albertel 6838: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6839: 	    $found{'ids'}{$found}++;
                   6840: 	    $found{'usernames'}{$username}++;
                   6841: 	} else {
                   6842: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6843: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6844: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6845: 		    &scantron_get_correction($r,$i,$scan_record,
                   6846: 					     \%scantron_config,
                   6847: 					     $line,'duplicateID',$username);
1.194     albertel 6848: 		    return(1,$currentphase);
1.157     albertel 6849: 		} elsif (!defined($username)) {
                   6850: 		    &scantron_get_correction($r,$i,$scan_record,
                   6851: 					     \%scantron_config,
                   6852: 					     $line,'incorrectID');
1.194     albertel 6853: 		    return(1,$currentphase);
1.157     albertel 6854: 		}
                   6855: 		$found{'usernames'}{$username}++;
                   6856: 	    } else {
                   6857: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6858: 					 $line,'incorrectID');
1.194     albertel 6859: 		return(1,$currentphase);
1.157     albertel 6860: 	    }
                   6861: 	}
                   6862:     }
                   6863: 
                   6864:     return (0,$currentphase+1);
                   6865: }
                   6866: 
1.423     albertel 6867: 
1.157     albertel 6868: sub scantron_get_correction {
                   6869:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6870: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6871: #to show both the current line and the previous one and allow skipping
                   6872: #the previous one or the current one
                   6873: 
1.333     albertel 6874:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   6875:         $r->print(
                   6876:             '<p class="LC_warning">'
                   6877:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   6878:                 "<b>$error</b>",
                   6879:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   6880:            ."</p> \n");
1.157     albertel 6881:     } else {
1.658     bisitz   6882:         $r->print(
                   6883:             '<p class="LC_warning">'
                   6884:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   6885:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   6886:            ."</p> \n");
                   6887:     }
                   6888:     my $message =
                   6889:         '<p>'
                   6890:        .&mt('The ID on the form is [_1]',
                   6891:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   6892:        .'<br />'
                   6893:        .&mt('The name on the paper is [_2], [_3]',
                   6894:             $$scan_record{'scantron.LastName'},
                   6895:             $$scan_record{'scantron.FirstName'})
                   6896:        .'</p>';
1.242     albertel 6897: 
1.157     albertel 6898:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6899:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6900:                            # Array populated for doublebubble or
                   6901:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6902:                            # to validate radio button checking   
                   6903: 
1.157     albertel 6904:     if ($error =~ /ID$/) {
1.186     albertel 6905: 	if ($error eq 'incorrectID') {
1.658     bisitz   6906:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 6907: 		      "</p>\n");
1.157     albertel 6908: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   6909:             $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 6910: 	}
1.242     albertel 6911: 	$r->print($message);
1.492     albertel 6912: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6913: 	$r->print("\n<ul><li> ");
                   6914: 	#FIXME it would be nice if this sent back the user ID and
                   6915: 	#could do partial userID matches
                   6916: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6917: 				       'scantron_username','scantron_domain'));
                   6918: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6919: 	$r->print("\n@".
1.257     albertel 6920: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6921: 
                   6922: 	$r->print('</li>');
1.186     albertel 6923:     } elsif ($error =~ /CODE$/) {
                   6924: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   6925: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6926: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   6927: 	    $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 6928: 	}
1.658     bisitz   6929: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   6930: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   6931:                  ."</p>\n");
1.242     albertel 6932: 	$r->print($message);
1.658     bisitz   6933: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 6934: 	$r->print("\n<br /> ");
1.194     albertel 6935: 	my $i=0;
1.273     albertel 6936: 	if ($error eq 'incorrectCODE' 
                   6937: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6938: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6939: 	    if ($closest > 0) {
                   6940: 		foreach my $testcode (@{$closest}) {
                   6941: 		    my $checked='';
1.569     bisitz   6942: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6943: 		    $r->print("
                   6944:    <label>
1.569     bisitz   6945:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6946:        ".&mt("Use the similar CODE [_1] instead.",
                   6947: 	    "<b><tt>".$testcode."</tt></b>")."
                   6948:     </label>
                   6949:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6950: 		    $r->print("\n<br />");
                   6951: 		    $i++;
                   6952: 		}
1.194     albertel 6953: 	    }
                   6954: 	}
1.273     albertel 6955: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6956: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6957: 	    $r->print("
                   6958:     <label>
1.569     bisitz   6959:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659   ! raeburn  6960:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 6961: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6962:     </label>");
1.273     albertel 6963: 	    $r->print("\n<br />");
                   6964: 	}
1.194     albertel 6965: 
1.597     wenzelju 6966: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6967: function change_radio(field) {
1.190     albertel 6968:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6969:     var i;
                   6970:     for (i=0;i<slct.length;i++) {
                   6971:         if (slct[i].value==field) { slct[i].checked=true; }
                   6972:     }
                   6973: }
                   6974: ENDSCRIPT
1.187     albertel 6975: 	my $href="/adm/pickcode?".
1.359     www      6976: 	   "form=".&escape("scantronupload").
                   6977: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6978: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6979: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6980: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6981: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6982: 	    $r->print("
                   6983:     <label>
                   6984:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6985:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6986: 	     "<a target='_blank' href='$href'>","</a>")."
                   6987:     </label> 
1.558     bisitz   6988:     ".&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 6989: 	    $r->print("\n<br />");
                   6990: 	}
1.492     albertel 6991: 	$r->print("
                   6992:     <label>
                   6993:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6994:        ".&mt("Use [_1] as the CODE.",
                   6995: 	     "</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 6996: 	$r->print("\n<br /><br />");
1.157     albertel 6997:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   6998: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6999: 
                   7000: 	# The form field scantron_questions is acutally a list of line numbers.
                   7001: 	# represented by this form so:
                   7002: 
                   7003: 	my $line_list = &questions_to_line_list($arg);
                   7004: 
1.157     albertel 7005: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7006: 		  $line_list.'" />');
1.242     albertel 7007: 	$r->print($message);
1.492     albertel 7008: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7009: 	foreach my $question (@{$arg}) {
1.503     raeburn  7010: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7011:                                                    $scan_record, $error);
1.524     raeburn  7012:             push(@lines_to_correct,@linenums);
1.157     albertel 7013: 	}
1.503     raeburn  7014:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7015:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7016: 	$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 7017: 	$r->print($message);
1.492     albertel 7018: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7019: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7020: 
1.503     raeburn  7021: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7022: 	# a list of question numbers. Therefore:
                   7023: 	#
                   7024: 	
                   7025: 	my $line_list = &questions_to_line_list($arg);
                   7026: 
1.157     albertel 7027: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7028: 		  $line_list.'" />');
1.157     albertel 7029: 	foreach my $question (@{$arg}) {
1.503     raeburn  7030: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7031:                                                    $scan_record, $error);
1.524     raeburn  7032:             push(@lines_to_correct,@linenums);
1.157     albertel 7033: 	}
1.503     raeburn  7034:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7035:     } else {
                   7036: 	$r->print("\n<ul>");
                   7037:     }
                   7038:     $r->print("\n</li></ul>");
1.497     foxr     7039: }
                   7040: 
1.503     raeburn  7041: sub verify_bubbles_checked {
                   7042:     my (@ansnums) = @_;
                   7043:     my $ansnumstr = join('","',@ansnums);
                   7044:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7045:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7046: function verify_bubble_radio(form) {
                   7047:     var ansnumArray = new Array ("$ansnumstr");
                   7048:     var need_bubble_count = 0;
                   7049:     for (var i=0; i<ansnumArray.length; i++) {
                   7050:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7051:             var bubble_picked = 0; 
                   7052:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7053:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7054:                     bubble_picked = 1;
                   7055:                 }
                   7056:             }
                   7057:             if (bubble_picked == 0) {
                   7058:                 need_bubble_count ++;
                   7059:             }
                   7060:         }
                   7061:     }
                   7062:     if (need_bubble_count) {
                   7063:         alert("$warning");
                   7064:         return;
                   7065:     }
                   7066:     form.submit(); 
                   7067: }
                   7068: ENDSCRIPT
                   7069:     return $output;
                   7070: }
                   7071: 
1.497     foxr     7072: =pod
                   7073: 
                   7074: =item  questions_to_line_list
1.157     albertel 7075: 
1.497     foxr     7076: Converts a list of questions into a string of comma separated
                   7077: line numbers in the answer sheet used by the questions.  This is
                   7078: used to fill in the scantron_questions form field.
                   7079: 
                   7080:   Arguments:
                   7081:      questions    - Reference to an array of questions.
                   7082: 
                   7083: =cut
                   7084: 
                   7085: 
                   7086: sub questions_to_line_list {
                   7087:     my ($questions) = @_;
                   7088:     my @lines;
                   7089: 
1.503     raeburn  7090:     foreach my $item (@{$questions}) {
                   7091:         my $question = $item;
                   7092:         my ($first,$count,$last);
                   7093:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7094:             $question = $1;
                   7095:             my $subquestion = $2;
                   7096:             $first = $first_bubble_line{$question-1} + 1;
                   7097:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7098:             my $subcount = 1;
                   7099:             while ($subcount<$subquestion) {
                   7100:                 $first += $subans[$subcount-1];
                   7101:                 $subcount ++;
                   7102:             }
                   7103:             $count = $subans[$subquestion-1];
                   7104:         } else {
                   7105: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7106: 	    $count   = $bubble_lines_per_response{$question-1};
                   7107:         }
1.506     raeburn  7108:         $last = $first+$count-1;
1.503     raeburn  7109:         push(@lines, ($first..$last));
1.497     foxr     7110:     }
                   7111:     return join(',', @lines);
                   7112: }
                   7113: 
                   7114: =pod 
                   7115: 
                   7116: =item prompt_for_corrections
                   7117: 
                   7118: Prompts for a potentially multiline correction to the
                   7119: user's bubbling (factors out common code from scantron_get_correction
                   7120: for multi and missing bubble cases).
                   7121: 
                   7122:  Arguments:
                   7123:    $r           - Apache request object.
                   7124:    $question    - The question number to prompt for.
                   7125:    $scan_config - The scantron file configuration hash.
                   7126:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7127:    $error       - Type of error
1.497     foxr     7128: 
                   7129:  Implicit inputs:
                   7130:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7131:                                   Numbered from 0 (but question numbers are from
                   7132:                                   1.
                   7133:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7134:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7135:                                   type problems render as separate sub-questions, 
1.503     raeburn  7136:                                   in exam mode. This hash contains a 
                   7137:                                   comma-separated list of the lines per 
                   7138:                                   sub-question.
1.510     raeburn  7139:    %responsetype_per_response   - essayresponse, formularesponse,
                   7140:                                   stringresponse, imageresponse, reactionresponse,
                   7141:                                   and organicresponse type problem parts can have
1.503     raeburn  7142:                                   multiple lines per response if the weight
                   7143:                                   assigned exceeds 10.  In this case, only
                   7144:                                   one bubble per line is permitted, but more 
                   7145:                                   than one line might contain bubbles, e.g.
                   7146:                                   bubbling of: line 1 - J, line 2 - J, 
                   7147:                                   line 3 - B would assign 22 points.  
1.497     foxr     7148: 
                   7149: =cut
                   7150: 
                   7151: sub prompt_for_corrections {
1.503     raeburn  7152:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7153:     my ($current_line,$lines);
                   7154:     my @linenums;
                   7155:     my $questionnum = $question;
                   7156:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7157:         $question = $1;
                   7158:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7159:         my $subquestion = $2;
                   7160:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7161:         my $subcount = 1;
                   7162:         while ($subcount<$subquestion) {
                   7163:             $current_line += $subans[$subcount-1];
                   7164:             $subcount ++;
                   7165:         }
                   7166:         $lines = $subans[$subquestion-1];
                   7167:     } else {
                   7168:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7169:         $lines        = $bubble_lines_per_response{$question-1};
                   7170:     }
1.497     foxr     7171:     if ($lines > 1) {
1.503     raeburn  7172:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7173:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7174:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7175:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7176:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7177:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7178:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7179:             $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  7180:         } else {
                   7181:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7182:         }
1.497     foxr     7183:     }
                   7184:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7185:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7186: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7187: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7188:         push(@linenums,$current_line);
1.497     foxr     7189: 	$current_line++;
                   7190:     }
                   7191:     if ($lines > 1) {
                   7192: 	$r->print("<hr /><br />");
                   7193:     }
1.503     raeburn  7194:     return @linenums;
1.157     albertel 7195: }
1.423     albertel 7196: 
                   7197: =pod
                   7198: 
                   7199: =item scantron_bubble_selector
                   7200:   
                   7201:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7202:    possibly showing the existing the selected bubbles if known
1.423     albertel 7203: 
                   7204:  Arguments:
                   7205:     $r           - Apache request object
                   7206:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7207:     $line        - Number of the line being displayed.
1.503     raeburn  7208:     $questionnum - Question number (may include subquestion)
                   7209:     $error       - Type of error.
1.497     foxr     7210:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7211: 
                   7212: =cut
                   7213: 
1.157     albertel 7214: sub scantron_bubble_selector {
1.503     raeburn  7215:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7216:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7217: 
                   7218:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7219:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7220:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7221:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7222:             $max=$$scan_config{'BubblesPerRow'};
                   7223:             if (($scmode eq 'number') && ($max > 10)) {
                   7224:                 $max = 10;
                   7225:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7226:                 $max = 26;
                   7227:             }
                   7228:         } else {
                   7229:             $max = 10;
                   7230:         }
                   7231:     }
1.274     albertel 7232: 
1.157     albertel 7233:     my @alphabet=('A'..'Z');
1.503     raeburn  7234:     $r->print(&Apache::loncommon::start_data_table().
                   7235:               &Apache::loncommon::start_data_table_row());
                   7236:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7237:     for (my $i=0;$i<$max+1;$i++) {
                   7238: 	$r->print("\n".'<td align="center">');
                   7239: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7240: 	else { $r->print('&nbsp;'); }
                   7241: 	$r->print('</td>');
                   7242:     }
1.503     raeburn  7243:     $r->print(&Apache::loncommon::end_data_table_row().
                   7244:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7245:     for (my $i=0;$i<$max;$i++) {
                   7246: 	$r->print("\n".
                   7247: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7248: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7249:     }
1.503     raeburn  7250:     my $nobub_checked = ' ';
                   7251:     if ($error eq 'missingbubble') {
                   7252:         $nobub_checked = ' checked = "checked" ';
                   7253:     }
                   7254:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7255: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7256:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7257:               $line.'" value="'.$questionnum.'" /></td>');
                   7258:     $r->print(&Apache::loncommon::end_data_table_row().
                   7259:               &Apache::loncommon::end_data_table());
1.157     albertel 7260: }
                   7261: 
1.423     albertel 7262: =pod
                   7263: 
                   7264: =item num_matches
                   7265: 
1.424     albertel 7266:    Counts the number of characters that are the same between the two arguments.
                   7267: 
                   7268:  Arguments:
                   7269:    $orig - CODE from the scanline
                   7270:    $code - CODE to match against
                   7271: 
                   7272:  Returns:
                   7273:    $count - integer count of the number of same characters between the
                   7274:             two arguments
                   7275: 
1.423     albertel 7276: =cut
                   7277: 
1.194     albertel 7278: sub num_matches {
                   7279:     my ($orig,$code) = @_;
                   7280:     my @code=split(//,$code);
                   7281:     my @orig=split(//,$orig);
                   7282:     my $same=0;
                   7283:     for (my $i=0;$i<scalar(@code);$i++) {
                   7284: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7285:     }
                   7286:     return $same;
                   7287: }
                   7288: 
1.423     albertel 7289: =pod
                   7290: 
                   7291: =item scantron_get_closely_matching_CODEs
                   7292: 
1.424     albertel 7293:    Cycles through all CODEs and finds the set that has the greatest
                   7294:    number of same characters as the provided CODE
                   7295: 
                   7296:  Arguments:
                   7297:    $allcodes - hash ref returned by &get_codes()
                   7298:    $CODE     - CODE from the current scanline
                   7299: 
                   7300:  Returns:
                   7301:    2 element list
                   7302:     - first elements is number of how closely matching the best fit is 
                   7303:       (5 means best set has 5 matching characters)
                   7304:     - second element is an arrary ref containing the set of valid CODEs
                   7305:       that best fit the passed in CODE
                   7306: 
1.423     albertel 7307: =cut
                   7308: 
1.194     albertel 7309: sub scantron_get_closely_matching_CODEs {
                   7310:     my ($allcodes,$CODE)=@_;
                   7311:     my @CODEs;
                   7312:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7313: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7314:     }
                   7315: 
                   7316:     return ($#CODEs,$CODEs[-1]);
                   7317: }
                   7318: 
1.423     albertel 7319: =pod
                   7320: 
                   7321: =item get_codes
                   7322: 
1.424     albertel 7323:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7324:    set of remembered CODEs.
                   7325: 
                   7326:  Arguments:
                   7327:   $old_name - name of the set of remembered CODEs
                   7328:   $cdom     - domain of the course
                   7329:   $cnum     - internal course name
                   7330: 
                   7331:  Returns:
                   7332:   %allcodes - keys are the valid CODEs, values are all 1
                   7333: 
1.423     albertel 7334: =cut
                   7335: 
1.194     albertel 7336: sub get_codes {
1.280     foxr     7337:     my ($old_name, $cdom, $cnum) = @_;
                   7338:     if (!$old_name) {
                   7339: 	$old_name=$env{'form.scantron_CODElist'};
                   7340:     }
                   7341:     if (!$cdom) {
                   7342: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7343:     }
                   7344:     if (!$cnum) {
                   7345: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7346:     }
1.278     albertel 7347:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7348: 				    $cdom,$cnum);
                   7349:     my %allcodes;
                   7350:     if ($result{"type\0$old_name"} eq 'number') {
                   7351: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7352:     } else {
                   7353: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7354:     }
1.194     albertel 7355:     return %allcodes;
                   7356: }
                   7357: 
1.423     albertel 7358: =pod
                   7359: 
                   7360: =item scantron_validate_CODE
                   7361: 
1.424     albertel 7362:    Validates all scanlines in the selected file to not have any
                   7363:    invalid or underspecified CODEs and that none of the codes are
                   7364:    duplicated if this was requested.
                   7365: 
1.423     albertel 7366: =cut
                   7367: 
1.157     albertel 7368: sub scantron_validate_CODE {
                   7369:     my ($r,$currentphase) = @_;
1.257     albertel 7370:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7371:     if ($scantron_config{'CODElocation'} &&
                   7372: 	$scantron_config{'CODEstart'} &&
                   7373: 	$scantron_config{'CODElength'}) {
1.257     albertel 7374: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7375: 	    &FIXME_blow_up()
                   7376: 	}
                   7377:     } else {
                   7378: 	return (0,$currentphase+1);
                   7379:     }
                   7380:     
                   7381:     my %usedCODEs;
                   7382: 
1.194     albertel 7383:     my %allcodes=&get_codes();
1.186     albertel 7384: 
1.582     raeburn  7385:     my $nav_error;
1.649     raeburn  7386:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7387:     if ($nav_error) {
                   7388:         $r->print(&navmap_errormsg());
                   7389:         return(1,$currentphase);
                   7390:     }
1.447     foxr     7391: 
1.186     albertel 7392:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7393:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7394: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7395: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7396: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7397: 						 $scan_data);
                   7398: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7399: 	my $error=0;
1.224     albertel 7400: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7401: 	    &scantron_get_correction($r,$i,$scan_record,
                   7402: 				     \%scantron_config,
                   7403: 				     $line,'incorrectCODE',\%allcodes);
                   7404: 	    return(1,$currentphase);
                   7405: 	}
1.221     albertel 7406: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7407: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7408: 	    &scantron_get_correction($r,$i,$scan_record,
                   7409: 				     \%scantron_config,
1.194     albertel 7410: 				     $line,'incorrectCODE',\%allcodes);
                   7411: 	    return(1,$currentphase);
1.186     albertel 7412: 	}
1.214     albertel 7413: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7414: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7415: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7416: 	    &scantron_get_correction($r,$i,$scan_record,
                   7417: 				     \%scantron_config,
1.194     albertel 7418: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7419: 	    return(1,$currentphase);
1.186     albertel 7420: 	}
1.524     raeburn  7421: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7422:     }
1.157     albertel 7423:     return (0,$currentphase+1);
                   7424: }
                   7425: 
1.423     albertel 7426: =pod
                   7427: 
                   7428: =item scantron_validate_doublebubble
                   7429: 
1.424     albertel 7430:    Validates all scanlines in the selected file to not have any
                   7431:    bubble lines with multiple bubbles marked.
                   7432: 
1.423     albertel 7433: =cut
                   7434: 
1.157     albertel 7435: sub scantron_validate_doublebubble {
                   7436:     my ($r,$currentphase) = @_;
                   7437:     #get student info
                   7438:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7439:     my %idmap=&username_to_idmap($classlist);
                   7440: 
                   7441:     #get scantron line setup
1.257     albertel 7442:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7443:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7444:     my $nav_error;
1.649     raeburn  7445:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7446:     if ($nav_error) {
                   7447:         $r->print(&navmap_errormsg());
                   7448:         return(1,$currentphase);
                   7449:     }
1.447     foxr     7450: 
1.157     albertel 7451:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7452: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7453: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7454: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7455: 						 $scan_data);
                   7456: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7457: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7458: 				 'doublebubble',
                   7459: 				 $$scan_record{'scantron.doubleerror'});
                   7460:     	return (1,$currentphase);
                   7461:     }
                   7462:     return (0,$currentphase+1);
                   7463: }
                   7464: 
1.423     albertel 7465: 
1.503     raeburn  7466: sub scantron_get_maxbubble {
1.649     raeburn  7467:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7468:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7469: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7470: 	&restore_bubble_lines();
1.257     albertel 7471: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7472:     }
1.330     albertel 7473: 
1.447     foxr     7474:     my (undef, undef, $sequence) =
1.257     albertel 7475: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7476: 
1.447     foxr     7477:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7478:     unless (ref($navmap)) {
                   7479:         if (ref($nav_error)) {
                   7480:             $$nav_error = 1;
                   7481:         }
1.591     raeburn  7482:         return;
1.582     raeburn  7483:     }
1.191     albertel 7484:     my $map=$navmap->getResourceByUrl($sequence);
                   7485:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  7486:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7487: 
                   7488:     &Apache::lonxml::clear_problem_counter();
                   7489: 
1.557     raeburn  7490:     my $uname       = $env{'user.name'};
                   7491:     my $udom        = $env{'user.domain'};
1.435     foxr     7492:     my $cid         = $env{'request.course.id'};
                   7493:     my $total_lines = 0;
                   7494:     %bubble_lines_per_response = ();
1.447     foxr     7495:     %first_bubble_line         = ();
1.503     raeburn  7496:     %subdivided_bubble_lines   = ();
                   7497:     %responsetype_per_response = ();
1.554     raeburn  7498: 
1.447     foxr     7499:     my $response_number = 0;
                   7500:     my $bubble_line     = 0;
1.191     albertel 7501:     foreach my $resource (@resources) {
1.649     raeburn  7502:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
1.542     raeburn  7503:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7504: 	    foreach my $part_id (@{$parts}) {
                   7505:                 my $lines;
                   7506: 
                   7507: 	        # TODO - make this a persistent hash not an array.
                   7508: 
                   7509:                 # optionresponse, matchresponse and rankresponse type items 
                   7510:                 # render as separate sub-questions in exam mode.
                   7511:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7512:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7513:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7514:                     my ($numbub,$numshown);
                   7515:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7516:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7517:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7518:                         }
                   7519:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7520:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7521:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7522:                         }
                   7523:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7524:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7525:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7526:                         }
                   7527:                     }
                   7528:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7529:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7530:                     }
1.649     raeburn  7531:                     my $bubbles_per_row =
                   7532:                         &bubblesheet_bubbles_per_row($scantron_config);
                   7533:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7534:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7535:                         $inner_bubble_lines++;
                   7536:                     }
                   7537:                     for (my $i=0; $i<$numshown; $i++) {
                   7538:                         $subdivided_bubble_lines{$response_number} .= 
                   7539:                             $inner_bubble_lines.',';
                   7540:                     }
                   7541:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7542:                     $lines = $numshown * $inner_bubble_lines;
                   7543:                 } else {
                   7544:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  7545:                 }
1.542     raeburn  7546: 
                   7547:                 $first_bubble_line{$response_number} = $bubble_line;
                   7548: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7549:                 $responsetype_per_response{$response_number} = 
                   7550:                     $analysis->{$part_id.'.type'};
                   7551: 	        $response_number++;
                   7552: 
                   7553: 	        $bubble_line +=  $lines;
                   7554: 	        $total_lines +=  $lines;
                   7555: 	    }
                   7556:         }
                   7557:     }
1.552     raeburn  7558:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7559: 
                   7560:     &save_bubble_lines();
                   7561:     $env{'form.scantron_maxbubble'} =
                   7562: 	$total_lines;
                   7563:     return $env{'form.scantron_maxbubble'};
                   7564: }
1.523     raeburn  7565: 
1.649     raeburn  7566: sub bubblesheet_bubbles_per_row {
                   7567:     my ($scantron_config) = @_;
                   7568:     my $bubbles_per_row;
                   7569:     if (ref($scantron_config) eq 'HASH') {
                   7570:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7571:     }
                   7572:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7573:         $bubbles_per_row = 10;
                   7574:     }
                   7575:     return $bubbles_per_row;
                   7576: }
                   7577: 
1.157     albertel 7578: sub scantron_validate_missingbubbles {
                   7579:     my ($r,$currentphase) = @_;
                   7580:     #get student info
                   7581:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7582:     my %idmap=&username_to_idmap($classlist);
                   7583: 
                   7584:     #get scantron line setup
1.257     albertel 7585:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7586:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7587:     my $nav_error;
1.649     raeburn  7588:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7589:     if ($nav_error) {
                   7590:         return(1,$currentphase);
                   7591:     }
1.157     albertel 7592:     if (!$max_bubble) { $max_bubble=2**31; }
                   7593:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7594: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7595: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7596: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7597: 						 $scan_data);
                   7598: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7599: 	my @to_correct;
1.470     foxr     7600: 	
                   7601: 	# Probably here's where the error is...
                   7602: 
1.157     albertel 7603: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7604:             my $lastbubble;
                   7605:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7606:                my $question = $1;
                   7607:                my $subquestion = $2;
                   7608:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7609:                my $first = $first_bubble_line{$question-1};
                   7610:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7611:                my $subcount = 1;
                   7612:                while ($subcount<$subquestion) {
                   7613:                    $first += $subans[$subcount-1];
                   7614:                    $subcount ++;
                   7615:                }
                   7616:                my $count = $subans[$subquestion-1];
                   7617:                $lastbubble = $first + $count;
                   7618:             } else {
                   7619:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7620:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7621:             }
                   7622:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7623: 	    push(@to_correct,$missing);
                   7624: 	}
                   7625: 	if (@to_correct) {
                   7626: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7627: 				     $line,'missingbubble',\@to_correct);
                   7628: 	    return (1,$currentphase);
                   7629: 	}
                   7630: 
                   7631:     }
                   7632:     return (0,$currentphase+1);
                   7633: }
                   7634: 
1.423     albertel 7635: 
1.82      albertel 7636: sub scantron_process_students {
1.608     www      7637:     my ($r,$symb) = @_;
1.513     foxr     7638: 
1.257     albertel 7639:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7640:     if (!$symb) {
                   7641: 	return '';
                   7642:     }
1.324     albertel 7643:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7644: 
1.257     albertel 7645:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7646:     my $bubbles_per_row =
                   7647:         &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 7648:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7649:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7650:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7651:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7652:     unless (ref($navmap)) {
                   7653:         $r->print(&navmap_errormsg());
                   7654:         return '';
                   7655:     }  
1.83      albertel 7656:     my $map=$navmap->getResourceByUrl($sequence);
                   7657:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7658:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7659:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  7660:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.586     raeburn  7661:     my $resource_error;
1.557     raeburn  7662:     foreach my $resource (@resources) {
1.586     raeburn  7663:         my $ressymb;
                   7664:         if (ref($resource)) {
                   7665:             $ressymb = $resource->symb();
                   7666:         } else {
                   7667:             $resource_error = 1;
                   7668:             last;
                   7669:         }
1.557     raeburn  7670:         my ($analysis,$parts) =
                   7671:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7672:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7673:         $grader_partids_by_symb{$ressymb} = $parts;
                   7674:         if (ref($analysis) eq 'HASH') {
                   7675:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7676:                 $grader_randomlists_by_symb{$ressymb} = 
                   7677:                     $analysis->{'parts_withrandomlist'};
                   7678:             }
                   7679:         }
                   7680:     }
1.586     raeburn  7681:     if ($resource_error) {
                   7682:         $r->print(&navmap_errormsg());
                   7683:         return '';
                   7684:     }
1.557     raeburn  7685: 
1.554     raeburn  7686:     my ($uname,$udom);
1.82      albertel 7687:     my $result= <<SCANTRONFORM;
1.81      albertel 7688: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7689:   <input type="hidden" name="command" value="scantron_configphase" />
                   7690:   $default_form_data
                   7691: SCANTRONFORM
1.82      albertel 7692:     $r->print($result);
                   7693: 
                   7694:     my @delayqueue;
1.542     raeburn  7695:     my (%completedstudents,%scandata);
1.140     albertel 7696:     
1.520     www      7697:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7698:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7699:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7700:  				    'Bubblesheet Progress',$count,
1.195     albertel 7701: 				    'inline',undef,'scantronupload');
1.140     albertel 7702:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7703: 					  'Processing first student');
1.542     raeburn  7704:     $r->print('<br />');
1.140     albertel 7705:     my $start=&Time::HiRes::time();
1.158     albertel 7706:     my $i=-1;
1.542     raeburn  7707:     my $started;
1.447     foxr     7708: 
1.582     raeburn  7709:     my $nav_error;
1.649     raeburn  7710:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7711:     if ($nav_error) {
                   7712:         $r->print(&navmap_errormsg());
                   7713:         return '';
                   7714:     }
                   7715: 
1.513     foxr     7716:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7717:     # the user and return.
                   7718: 
                   7719:     if ($ssi_error) {
                   7720: 	$r->print("</form>");
                   7721: 	&ssi_print_error($r);
1.520     www      7722:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7723: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7724:     }
1.447     foxr     7725: 
1.542     raeburn  7726:     my %lettdig = &letter_to_digits();
                   7727:     my $numletts = scalar(keys(%lettdig));
                   7728: 
1.157     albertel 7729:     while ($i<$scanlines->{'count'}) {
                   7730:  	($uname,$udom)=('','');
                   7731:  	$i++;
1.200     albertel 7732:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7733:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7734: 	if ($started) {
                   7735: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7736: 						     'last student');
                   7737: 	}
                   7738: 	$started=1;
1.157     albertel 7739:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7740:  						 $scan_data);
                   7741:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7742:  					      \%idmap,$i)) {
                   7743:   	    &scantron_add_delay(\@delayqueue,$line,
                   7744:  				'Unable to find a student that matches',1);
                   7745:  	    next;
                   7746:   	}
                   7747:  	if (exists $completedstudents{$uname}) {
                   7748:  	    &scantron_add_delay(\@delayqueue,$line,
                   7749:  				'Student '.$uname.' has multiple sheets',2);
                   7750:  	    next;
                   7751:  	}
                   7752:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7753: 
1.586     raeburn  7754:         my (%partids_by_symb,$res_error);
1.554     raeburn  7755:         foreach my $resource (@resources) {
1.586     raeburn  7756:             my $ressymb;
                   7757:             if (ref($resource)) {
                   7758:                 $ressymb = $resource->symb();
                   7759:             } else {
                   7760:                 $res_error = 1;
                   7761:                 last;
                   7762:             }
1.557     raeburn  7763:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7764:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7765:                 my ($analysis,$parts) =
1.649     raeburn  7766:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7767:                 $partids_by_symb{$ressymb} = $parts;
                   7768:             } else {
                   7769:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7770:             }
1.554     raeburn  7771:         }
                   7772: 
1.586     raeburn  7773:         if ($res_error) {
                   7774:             &scantron_add_delay(\@delayqueue,$line,
                   7775:                                 'An error occurred while grading student '.$uname,2);
                   7776:             next;
                   7777:         }
                   7778: 
1.330     albertel 7779: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7780:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7781: 
                   7782: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7783: 	    &scantron_putfile($scanlines,$scan_data);
                   7784: 	}
1.161     albertel 7785: 	
1.542     raeburn  7786:         my $scancode;
                   7787:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7788:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7789:             $scancode = $scan_record->{'scantron.CODE'};
                   7790:         } else {
                   7791:             $scancode = '';
                   7792:         }
                   7793: 
                   7794:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7795:                                    \@resources,\%partids_by_symb,
                   7796:                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  7797:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7798:             $r->print("</form>");
                   7799:             &ssi_print_error($r);
                   7800:             &Apache::lonnet::remove_lock($lock);
                   7801:             return '';      # Why return ''?  Beats me.
                   7802:         }
1.513     foxr     7803: 
1.140     albertel 7804: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7805:         if ($env{'form.verifyrecord'}) {
                   7806:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7807:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7808:             chomp($studentdata);
                   7809:             $studentdata =~ s/\r$//;
                   7810:             my $studentrecord = '';
                   7811:             my $counter = -1;
                   7812:             foreach my $resource (@resources) {
1.554     raeburn  7813:                 my $ressymb = $resource->symb();
1.542     raeburn  7814:                 ($counter,my $recording) =
                   7815:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7816:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7817:                                              \%scantron_config,\%lettdig,$numletts);
                   7818:                 $studentrecord .= $recording;
                   7819:             }
                   7820:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7821:                 &Apache::lonxml::clear_problem_counter();
                   7822:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.649     raeburn  7823:                                            \@resources,\%partids_by_symb,
                   7824:                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  7825:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7826:                     $r->print("</form>");
                   7827:                     &ssi_print_error($r);
                   7828:                     &Apache::lonnet::remove_lock($lock);
                   7829:                     delete($completedstudents{$uname});
                   7830:                     return '';
                   7831:                 }
1.542     raeburn  7832:                 $counter = -1;
                   7833:                 $studentrecord = '';
                   7834:                 foreach my $resource (@resources) {
1.554     raeburn  7835:                     my $ressymb = $resource->symb();
1.542     raeburn  7836:                     ($counter,my $recording) =
                   7837:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7838:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7839:                                                  \%scantron_config,\%lettdig,$numletts);
                   7840:                     $studentrecord .= $recording;
                   7841:                 }
                   7842:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   7843:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  7844:                     if ($scancode eq '') {
1.658     bisitz   7845:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  7846:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7847:                     } else {
1.658     bisitz   7848:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  7849:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7850:                     }
                   7851:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7852:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7853:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7854:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7855:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   7856:                               '<td>'.&mt('Bubblesheet').'</td>'.
                   7857:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  7858:                               &Apache::loncommon::end_data_table_row().
                   7859:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   7860:                               '<td>'.&mt('Stored submissions').'</td>'.
                   7861:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  7862:                               &Apache::loncommon::end_data_table_row().
                   7863:                               &Apache::loncommon::end_data_table().'</p>');
                   7864:                 } else {
                   7865:                     $r->print('<br /><span class="LC_warning">'.
                   7866:                              &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 />'.
                   7867:                              &mt("As a consequence, this user's submission history records two tries.").
                   7868:                                  '</span><br />');
                   7869:                 }
                   7870:             }
                   7871:         }
1.543     raeburn  7872:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7873:     } continue {
1.330     albertel 7874: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7875: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7876:     }
1.140     albertel 7877:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7878:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7879: #    my $lasttime = &Time::HiRes::time()-$start;
                   7880: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7881: 
1.200     albertel 7882:     $r->print("</form>");
1.157     albertel 7883:     return '';
1.75      albertel 7884: }
1.157     albertel 7885: 
1.557     raeburn  7886: sub graders_resources_pass {
1.649     raeburn  7887:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   7888:         $bubbles_per_row) = @_;
1.557     raeburn  7889:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7890:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7891:         foreach my $resource (@{$resources}) {
                   7892:             my $ressymb = $resource->symb();
                   7893:             my ($analysis,$parts) =
                   7894:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.649     raeburn  7895:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
1.557     raeburn  7896:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7897:             if (ref($analysis) eq 'HASH') {
                   7898:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7899:                     $grader_randomlists_by_symb->{$ressymb} =
                   7900:                         $analysis->{'parts_withrandomlist'};
                   7901:                 }
                   7902:             }
                   7903:         }
                   7904:     }
                   7905:     return;
                   7906: }
                   7907: 
1.542     raeburn  7908: sub grade_student_bubbles {
1.649     raeburn  7909:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
                   7910: # Walk folder as student here to get resources in order student sees.
1.554     raeburn  7911:     if (ref($resources) eq 'ARRAY') {
                   7912:         my $count = 0;
                   7913:         foreach my $resource (@{$resources}) {
                   7914:             my $ressymb = $resource->symb();
                   7915:             my %form = ('submitted'      => 'scantron',
                   7916:                         'grade_target'   => 'grade',
                   7917:                         'grade_username' => $uname,
                   7918:                         'grade_domain'   => $udom,
                   7919:                         'grade_courseid' => $env{'request.course.id'},
                   7920:                         'grade_symb'     => $ressymb,
                   7921:                         'CODE'           => $scancode
                   7922:                        );
1.649     raeburn  7923:             if ($bubbles_per_row ne '') {
                   7924:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   7925:             }
1.554     raeburn  7926:             if (ref($parts) eq 'HASH') {
                   7927:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7928:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7929:                         $form{'scantron_questnum_start.'.$part} =
                   7930:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7931:                         $count++;
                   7932:                     }
                   7933:                 }
                   7934:             }
                   7935:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7936:             return 'ssi_error' if ($ssi_error);
                   7937:             last if (&Apache::loncommon::connection_aborted($r));
                   7938:         }
1.542     raeburn  7939:     }
                   7940:     return;
                   7941: }
                   7942: 
1.157     albertel 7943: sub scantron_upload_scantron_data {
1.608     www      7944:     my ($r,$symb)=@_;
1.565     raeburn  7945:     my $dom = $env{'request.role.domain'};
                   7946:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7947:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7948:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7949: 							  'domainid',
1.565     raeburn  7950: 							  'coursename',$dom);
                   7951:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7952:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7953:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7954:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7955:     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 7956:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7957:     function checkUpload(formname) {
                   7958: 	if (formname.upfile.value == "") {
1.579     raeburn  7959: 	    alert("'.$nofile_alert.'");
1.157     albertel 7960: 	    return false;
                   7961: 	}
1.565     raeburn  7962:         if (formname.courseid.value == "") {
1.579     raeburn  7963:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7964:             return false;
                   7965:         }
1.157     albertel 7966: 	formname.submit();
                   7967:     }
1.565     raeburn  7968: 
                   7969:     function ToSyllabus() {
                   7970:         var cdom = '."'$dom'".';
                   7971:         var cnum = document.rules.courseid.value;
                   7972:         if (cdom == "" || cdom == null) {
                   7973:             return;
                   7974:         }
                   7975:         if (cnum == "" || cnum == null) {
                   7976:            return;
                   7977:         }
                   7978:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7979:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7980:         return;
                   7981:     }
                   7982: 
1.597     wenzelju 7983: '));
                   7984:     $r->print('
1.648     bisitz   7985: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  7986: 
1.492     albertel 7987: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7988: '.$default_form_data.
                   7989:   &Apache::lonhtmlcommon::start_pick_box().
                   7990:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7991:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7992:   &Apache::lonhtmlcommon::row_closure().
                   7993:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7994:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7995:   &Apache::lonhtmlcommon::row_closure().
                   7996:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7997:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7998:   &Apache::lonhtmlcommon::row_closure().
                   7999:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8000:   '<input type="file" name="upfile" size="50" />'.
                   8001:   &Apache::lonhtmlcommon::row_closure(1).
                   8002:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8003: 
1.492     albertel 8004: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8005: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8006: </form>
1.492     albertel 8007: ');
1.157     albertel 8008:     return '';
                   8009: }
                   8010: 
1.423     albertel 8011: 
1.157     albertel 8012: sub scantron_upload_scantron_data_save {
1.608     www      8013:     my($r,$symb)=@_;
1.182     albertel 8014:     my $doanotherupload=
                   8015: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8016: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8017: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8018: 	'</form>'."\n";
1.257     albertel 8019:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8020: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8021: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8022: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8023: 	unless ($symb) {
1.182     albertel 8024: 	    $r->print($doanotherupload);
                   8025: 	}
1.162     albertel 8026: 	return '';
                   8027:     }
1.257     albertel 8028:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8029:     my $uploadedfile;
1.567     raeburn  8030:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8031:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8032:         $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 8033:     } else {
1.568     raeburn  8034:         my $result = 
                   8035:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8036:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8037: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8038: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8039:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8040: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8041:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8042:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8043:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8044: 	} else {
1.567     raeburn  8045: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8046:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8047: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8048: 	}
                   8049:     }
1.174     albertel 8050:     if ($symb) {
1.612     www      8051: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8052:     } else {
1.182     albertel 8053: 	$r->print($doanotherupload);
1.174     albertel 8054:     }
1.157     albertel 8055:     return '';
                   8056: }
                   8057: 
1.567     raeburn  8058: sub validate_uploaded_scantron_file {
                   8059:     my ($cdom,$cname,$fname) = @_;
                   8060:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8061:     my @lines;
                   8062:     if ($scanlines ne '-1') {
                   8063:         @lines=split("\n",$scanlines,-1);
                   8064:     }
                   8065:     my $output;
                   8066:     if (@lines) {
                   8067:         my (%counts,$max_match_format);
                   8068:         my ($max_match_count,$max_match_pct) = (0,0);
                   8069:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8070:         my %idmap = &username_to_idmap($classlist);
                   8071:         foreach my $key (keys(%idmap)) {
                   8072:             my $lckey = lc($key);
                   8073:             $idmap{$lckey} = $idmap{$key};
                   8074:         }
                   8075:         my %unique_formats;
                   8076:         my @formatlines = &get_scantronformat_file();
                   8077:         foreach my $line (@formatlines) {
                   8078:             chomp($line);
                   8079:             my @config = split(/:/,$line);
                   8080:             my $idstart = $config[5];
                   8081:             my $idlength = $config[6];
                   8082:             if (($idstart ne '') && ($idlength > 0)) {
                   8083:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8084:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8085:                 } else {
                   8086:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8087:                 }
                   8088:             }
                   8089:         }
                   8090:         foreach my $key (keys(%unique_formats)) {
                   8091:             my ($idstart,$idlength) = split(':',$key);
                   8092:             %{$counts{$key}} = (
                   8093:                                'found'   => 0,
                   8094:                                'total'   => 0,
                   8095:                               );
                   8096:             foreach my $line (@lines) {
                   8097:                 next if ($line =~ /^#/);
                   8098:                 next if ($line =~ /^[\s\cz]*$/);
                   8099:                 my $id = substr($line,$idstart-1,$idlength);
                   8100:                 $id = lc($id);
                   8101:                 if (exists($idmap{$id})) {
                   8102:                     $counts{$key}{'found'} ++;
                   8103:                 }
                   8104:                 $counts{$key}{'total'} ++;
                   8105:             }
                   8106:             if ($counts{$key}{'total'}) {
                   8107:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8108:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8109:                     $max_match_pct = $percent_match;
                   8110:                     $max_match_format = $key;
                   8111:                     $max_match_count = $counts{$key}{'total'};
                   8112:                 }
                   8113:             }
                   8114:         }
                   8115:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8116:             my $format_descs;
                   8117:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8118:             for (my $i=0; $i<$numwithformat; $i++) {
                   8119:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8120:                 if ($i<$numwithformat-2) {
                   8121:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8122:                 } elsif ($i==$numwithformat-2) {
                   8123:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8124:                 } elsif ($i==$numwithformat-1) {
                   8125:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8126:                 }
                   8127:             }
                   8128:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8129:             $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).
                   8130:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8131:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8132:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8133:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8134:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8135:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8136:                        '</ul>';
                   8137:         }
                   8138:     } else {
                   8139:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8140:     }
                   8141:     return $output;
                   8142: }
                   8143: 
1.202     albertel 8144: sub valid_file {
                   8145:     my ($requested_file)=@_;
                   8146:     foreach my $filename (sort(&scantron_filenames())) {
                   8147: 	if ($requested_file eq $filename) { return 1; }
                   8148:     }
                   8149:     return 0;
                   8150: }
                   8151: 
                   8152: sub scantron_download_scantron_data {
1.608     www      8153:     my ($r,$symb)=@_;
                   8154:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8155:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8156:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8157:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8158:     if (! &valid_file($file)) {
1.492     albertel 8159: 	$r->print('
1.202     albertel 8160: 	<p>
1.492     albertel 8161: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8162:         </p>
1.492     albertel 8163: ');
1.202     albertel 8164: 	return;
                   8165:     }
                   8166:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8167:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8168:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8169:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8170:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8171:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8172:     $r->print('
1.202     albertel 8173:     <p>
1.492     albertel 8174: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8175: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8176:     </p>
                   8177:     <p>
1.492     albertel 8178: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8179: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8180:     </p>
                   8181:     <p>
1.492     albertel 8182: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8183: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8184:     </p>
1.492     albertel 8185: ');
1.202     albertel 8186:     return '';
                   8187: }
1.157     albertel 8188: 
1.523     raeburn  8189: sub checkscantron_results {
1.608     www      8190:     my ($r,$symb) = @_;
1.523     raeburn  8191:     if (!$symb) {return '';}
                   8192:     my $cid = $env{'request.course.id'};
1.542     raeburn  8193:     my %lettdig = &letter_to_digits();
1.523     raeburn  8194:     my $numletts = scalar(keys(%lettdig));
                   8195:     my $cnum = $env{'course.'.$cid.'.num'};
                   8196:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8197:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8198:     my %record;
                   8199:     my %scantron_config =
                   8200:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8201:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8202:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8203:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8204:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8205:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8206:     unless (ref($navmap)) {
                   8207:         $r->print(&navmap_errormsg());
                   8208:         return '';
                   8209:     }
1.523     raeburn  8210:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8211:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8212:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8213:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8214: 
1.554     raeburn  8215:     my ($uname,$udom);
1.523     raeburn  8216:     my (%scandata,%lastname,%bylast);
                   8217:     $r->print('
                   8218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8219: 
                   8220:     my @delayqueue;
                   8221:     my %completedstudents;
                   8222: 
                   8223:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8224:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8225:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8226:                                     'inline',undef,'checkscantron');
1.546     raeburn  8227:     my ($username,$domain,$started);
1.582     raeburn  8228:     my $nav_error;
1.649     raeburn  8229:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8230:     if ($nav_error) {
                   8231:         $r->print(&navmap_errormsg());
                   8232:         return '';
                   8233:     }
1.523     raeburn  8234: 
                   8235:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8236:                                           'Processing first student');
                   8237:     my $start=&Time::HiRes::time();
                   8238:     my $i=-1;
                   8239: 
                   8240:     while ($i<$scanlines->{'count'}) {
                   8241:         ($username,$domain,$uname)=('','','');
                   8242:         $i++;
                   8243:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8244:         if ($line=~/^[\s\cz]*$/) { next; }
                   8245:         if ($started) {
                   8246:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8247:                                                      'last student');
                   8248:         }
                   8249:         $started=1;
                   8250:         my $scan_record=
                   8251:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8252:                                                      $scan_data);
                   8253:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8254:                                                               \%idmap,$i)) {
                   8255:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8256:                                 'Unable to find a student that matches',1);
                   8257:             next;
                   8258:         }
                   8259:         if (exists $completedstudents{$uname}) {
                   8260:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8261:                                 'Student '.$uname.' has multiple sheets',2);
                   8262:             next;
                   8263:         }
                   8264:         my $pid = $scan_record->{'scantron.ID'};
                   8265:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8266:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8267:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8268:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8269:         chomp($scandata{$pid});
                   8270:         $scandata{$pid} =~ s/\r$//;
                   8271:         ($username,$domain)=split(/:/,$uname);
                   8272:         my $counter = -1;
                   8273:         foreach my $resource (@resources) {
1.557     raeburn  8274:             my $parts;
1.554     raeburn  8275:             my $ressymb = $resource->symb();
1.557     raeburn  8276:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8277:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8278:                 (my $analysis,$parts) =
1.649     raeburn  8279:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
1.557     raeburn  8280:             } else {
                   8281:                 $parts = $grader_partids_by_symb{$ressymb};
                   8282:             }
1.542     raeburn  8283:             ($counter,my $recording) =
                   8284:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8285:                                          $scandata{$pid},$parts,
1.542     raeburn  8286:                                          \%scantron_config,\%lettdig,$numletts);
                   8287:             $record{$pid} .= $recording;
1.523     raeburn  8288:         }
                   8289:     }
                   8290:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8291:     $r->print('<br />');
                   8292:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8293:     $passed = 0;
                   8294:     $failed = 0;
                   8295:     $numstudents = 0;
                   8296:     foreach my $last (sort(keys(%bylast))) {
                   8297:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8298:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8299:                 my $showscandata = $scandata{$pid};
                   8300:                 my $showrecord = $record{$pid};
                   8301:                 $showscandata =~ s/\s/&nbsp;/g;
                   8302:                 $showrecord =~ s/\s/&nbsp;/g;
                   8303:                 if ($scandata{$pid} eq $record{$pid}) {
                   8304:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8305:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8306: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8307: '</tr>'."\n".
                   8308: '<tr class="'.$css_class.'">'."\n".
                   8309: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8310:                     $passed ++;
                   8311:                 } else {
                   8312:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8313:                     $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  8314: '</tr>'."\n".
                   8315: '<tr class="'.$css_class.'">'."\n".
                   8316: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8317: '</tr>'."\n";
                   8318:                     $failed ++;
                   8319:                 }
                   8320:                 $numstudents ++;
                   8321:             }
                   8322:         }
                   8323:     }
1.648     bisitz   8324:     $r->print(
                   8325:         '<p>'
                   8326:        .&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).',
                   8327:             '<b>',
                   8328:             $numstudents,
                   8329:             '</b>',
                   8330:             $env{'form.scantron_maxbubble'})
                   8331:        .'</p>'
                   8332:     );
1.523     raeburn  8333:     $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>');
                   8334:     if ($passed) {
1.572     www      8335:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8336:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8337:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8338:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8339:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8340:                  $okstudents."\n".
                   8341:                  &Apache::loncommon::end_data_table().'<br />');
                   8342:     }
                   8343:     if ($failed) {
1.572     www      8344:         $r->print(&mt('Students with differences 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:                  $badstudents."\n".
                   8350:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8351:                  &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  8352:     }
1.614     www      8353:     $r->print('</form><br />');
1.523     raeburn  8354:     return;
                   8355: }
                   8356: 
1.542     raeburn  8357: sub verify_scantron_grading {
1.554     raeburn  8358:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8359:         $scantron_config,$lettdig,$numletts) = @_;
                   8360:     my ($record,%expected,%startpos);
                   8361:     return ($counter,$record) if (!ref($resource));
                   8362:     return ($counter,$record) if (!$resource->is_problem());
                   8363:     my $symb = $resource->symb();
1.554     raeburn  8364:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8365:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8366:         $counter ++;
                   8367:         $expected{$part_id} = 0;
                   8368:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8369:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8370:             foreach my $item (@sub_lines) {
                   8371:                 $expected{$part_id} += $item;
                   8372:             }
                   8373:         } else {
                   8374:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8375:         }
                   8376:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8377:     }
                   8378:     if ($symb) {
                   8379:         my %recorded;
                   8380:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8381:         if ($returnhash{'version'}) {
                   8382:             my %lasthash=();
                   8383:             my $version;
                   8384:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8385:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8386:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8387:                 }
                   8388:             }
                   8389:             foreach my $key (keys(%lasthash)) {
                   8390:                 if ($key =~ /\.scantron$/) {
                   8391:                     my $value = &unescape($lasthash{$key});
                   8392:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8393:                     if ($value eq '') {
                   8394:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8395:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8396:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8397:                             }
                   8398:                         }
                   8399:                     } else {
                   8400:                         my @tocheck;
                   8401:                         my @items = split(//,$value);
                   8402:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8403:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8404:                             if (@items < $expected{$part_id}) {
                   8405:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8406:                                 my @singles = split(//,$fragment);
                   8407:                                 foreach my $pos (@singles) {
                   8408:                                     if ($pos eq ' ') {
                   8409:                                         push(@tocheck,$pos);
                   8410:                                     } else {
                   8411:                                         my $next = shift(@items);
                   8412:                                         push(@tocheck,$next);
                   8413:                                     }
                   8414:                                 }
                   8415:                             } else {
                   8416:                                 @tocheck = @items;
                   8417:                             }
                   8418:                             foreach my $letter (@tocheck) {
                   8419:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8420:                                     if ($letter !~ /^[A-J]$/) {
                   8421:                                         $letter = $scantron_config->{'Qoff'};
                   8422:                                     }
                   8423:                                     $recorded{$part_id} .= $letter;
                   8424:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8425:                                     my $digit;
                   8426:                                     if ($letter !~ /^[A-J]$/) {
                   8427:                                         $digit = $scantron_config->{'Qoff'};
                   8428:                                     } else {
                   8429:                                         $digit = $lettdig->{$letter};
                   8430:                                     }
                   8431:                                     $recorded{$part_id} .= $digit;
                   8432:                                 }
                   8433:                             }
                   8434:                         } else {
                   8435:                             @tocheck = @items;
                   8436:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8437:                                 my $curr_sub = shift(@tocheck);
                   8438:                                 my $digit;
                   8439:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8440:                                     $digit = $lettdig->{$curr_sub}-1;
                   8441:                                 }
                   8442:                                 if ($curr_sub eq 'J') {
                   8443:                                     $digit += scalar($numletts);
                   8444:                                 }
                   8445:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8446:                                     if ($j == $digit) {
                   8447:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8448:                                     } else {
                   8449:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8450:                                     }
                   8451:                                 }
                   8452:                             }
                   8453:                         }
                   8454:                     }
                   8455:                 }
                   8456:             }
                   8457:         }
1.554     raeburn  8458:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8459:             if ($recorded{$part_id} eq '') {
                   8460:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8461:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8462:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8463:                     }
                   8464:                 }
                   8465:             }
                   8466:             $record .= $recorded{$part_id};
                   8467:         }
                   8468:     }
                   8469:     return ($counter,$record);
                   8470: }
                   8471: 
                   8472: sub letter_to_digits { 
                   8473:     my %lettdig = (
                   8474:                     A => 1,
                   8475:                     B => 2,
                   8476:                     C => 3,
                   8477:                     D => 4,
                   8478:                     E => 5,
                   8479:                     F => 6,
                   8480:                     G => 7,
                   8481:                     H => 8,
                   8482:                     I => 9,
                   8483:                     J => 0,
                   8484:                   );
                   8485:     return %lettdig;
                   8486: }
                   8487: 
1.423     albertel 8488: 
1.75      albertel 8489: #-------- end of section for handling grading scantron forms -------
                   8490: #
                   8491: #-------------------------------------------------------------------
                   8492: 
1.72      ng       8493: #-------------------------- Menu interface -------------------------
                   8494: #
1.614     www      8495: #--- Href with symb and command ---
                   8496: 
                   8497: sub href_symb_cmd {
                   8498:     my ($symb,$cmd)=@_;
                   8499:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8500: }
                   8501: 
1.443     banghart 8502: sub grading_menu {
1.608     www      8503:     my ($request,$symb) = @_;
1.443     banghart 8504:     if (!$symb) {return '';}
                   8505: 
                   8506:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8507:                   'command'=>'individual');
1.538     schulted 8508:     
1.598     www      8509:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8510: 
                   8511:     $fields{'command'}='ungraded';
                   8512:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8513: 
                   8514:     $fields{'command'}='table';
                   8515:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8516: 
                   8517:     $fields{'command'}='all_for_one';
                   8518:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8519: 
1.621     www      8520:     $fields{'command'}='downloadfilesselect';
                   8521:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8522: 
1.443     banghart 8523:     $fields{'command'} = 'csvform';
1.538     schulted 8524:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8525:     
1.443     banghart 8526:     $fields{'command'} = 'processclicker';
1.538     schulted 8527:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8528:     
1.443     banghart 8529:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8530:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8531: 
                   8532:     $fields{'command'} = 'initialverifyreceipt';
                   8533:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8534:     
1.598     www      8535:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8536:             items =>[
1.598     www      8537:                         {	linktext => 'Select individual students to grade',
                   8538:                     		url => $url1a,
1.538     schulted 8539:                     		permission => 'F',
1.636     wenzelju 8540:                     		icon => 'grade_students.png',
1.598     www      8541:                     		linktitle => 'Grade current resource for a selection of students.'
                   8542:                         }, 
                   8543:                         {       linktext => 'Grade ungraded submissions.',
                   8544:                                 url => $url1b,
                   8545:                                 permission => 'F',
1.636     wenzelju 8546:                                 icon => 'ungrade_sub.png',
1.598     www      8547:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8548:                         },
1.598     www      8549: 
                   8550:                         {       linktext => 'Grading table',
                   8551:                                 url => $url1c,
                   8552:                                 permission => 'F',
1.636     wenzelju 8553:                                 icon => 'grading_table.png',
1.598     www      8554:                                 linktitle => 'Grade current resource for all students.'
                   8555:                         },
1.615     www      8556:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8557:                                 url => $url1d,
                   8558:                                 permission => 'F',
1.636     wenzelju 8559:                                 icon => 'grade_PageFolder.png',
1.598     www      8560:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8561:                         },
                   8562:                         {       linktext => 'Download submissions',
                   8563:                                 url => $url1e,
                   8564:                                 permission => 'F',
1.636     wenzelju 8565:                                 icon => 'download_sub.png',
1.621     www      8566:                                 linktitle => 'Download all students submissions.'
1.598     www      8567:                         }]},
                   8568:                          { categorytitle=>'Automated Grading',
                   8569:                items =>[
                   8570: 
1.538     schulted 8571:                 	    {	linktext => 'Upload Scores',
                   8572:                     		url => $url2,
                   8573:                     		permission => 'F',
                   8574:                     		icon => 'uploadscores.png',
                   8575:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8576:                 	    },
                   8577:                 	    {	linktext => 'Process Clicker',
                   8578:                     		url => $url3,
                   8579:                     		permission => 'F',
                   8580:                     		icon => 'addClickerInfoFile.png',
                   8581:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8582:                 	    },
1.587     raeburn  8583:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8584:                     		url => $url4,
                   8585:                     		permission => 'F',
1.636     wenzelju 8586:                     		icon => 'bubblesheet.png',
1.648     bisitz   8587:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      8588:                 	    },
1.616     www      8589:                             {   linktext => 'Verify Receipt Number',
1.602     www      8590:                                 url => $url5,
                   8591:                                 permission => 'F',
1.636     wenzelju 8592:                                 icon => 'receipt_number.png',
1.602     www      8593:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8594:                             }
                   8595: 
1.538     schulted 8596:                     ]
                   8597:             });
                   8598: 
1.443     banghart 8599:     # Create the menu
                   8600:     my $Str;
1.445     banghart 8601:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8602:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8603:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8604: 
1.602     www      8605:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8606:     return $Str;    
                   8607: }
                   8608: 
1.598     www      8609: 
                   8610: sub ungraded {
                   8611:     my ($request)=@_;
                   8612:     &submit_options($request);
                   8613: }
                   8614: 
1.599     www      8615: sub submit_options_sequence {
1.608     www      8616:     my ($request,$symb) = @_;
1.599     www      8617:     if (!$symb) {return '';}
1.600     www      8618:     &commonJSfunctions($request);
                   8619:     my $result;
1.599     www      8620: 
1.600     www      8621:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8622:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8623:     $result.=&selectfield(0).
1.601     www      8624:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8625:             <div>
                   8626:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8627:             </div>
                   8628:         </div>
                   8629:   </form>';
                   8630:     return $result;
                   8631: }
                   8632: 
                   8633: sub submit_options_table {
1.608     www      8634:     my ($request,$symb) = @_;
1.600     www      8635:     if (!$symb) {return '';}
1.599     www      8636:     &commonJSfunctions($request);
                   8637:     my $result;
                   8638: 
                   8639:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8640:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8641: 
1.632     www      8642:     $result.=&selectfield(0).
1.601     www      8643:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8644:             <div>
                   8645:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8646:             </div>
                   8647:         </div>
                   8648:   </form>';
                   8649:     return $result;
                   8650: }
1.443     banghart 8651: 
1.621     www      8652: sub submit_options_download {
                   8653:     my ($request,$symb) = @_;
                   8654:     if (!$symb) {return '';}
                   8655: 
                   8656:     &commonJSfunctions($request);
                   8657: 
                   8658:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8659:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8660:     $result.='
                   8661: <h2>
                   8662:   '.&mt('Select Students for Which to Download Submissions').'
                   8663: </h2>'.&selectfield(1).'
                   8664:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8665:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8666:             </div>
                   8667:           </div>
1.600     www      8668: 
                   8669: 
1.621     www      8670:   </form>';
                   8671:     return $result;
                   8672: }
                   8673: 
1.443     banghart 8674: #--- Displays the submissions first page -------
                   8675: sub submit_options {
1.608     www      8676:     my ($request,$symb) = @_;
1.72      ng       8677:     if (!$symb) {return '';}
                   8678: 
1.118     ng       8679:     &commonJSfunctions($request);
1.473     albertel 8680:     my $result;
1.533     bisitz   8681: 
1.72      ng       8682:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8683: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      8684:     $result.=&selectfield(1).'
1.601     www      8685:                 <input type="hidden" name="command" value="submission" /> 
                   8686: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8687:             </div>
                   8688:           </div>
                   8689: 
                   8690: 
                   8691:   </form>';
                   8692:     return $result;
                   8693: }
1.533     bisitz   8694: 
1.601     www      8695: sub selectfield {
                   8696:    my ($full)=@_;
1.635     raeburn  8697:    my %options = 
                   8698:           (&Apache::lonlocal::texthash(
                   8699:              'yes'       => 'with submissions',
                   8700:              'queued'    => 'in grading queue',
                   8701:              'graded'    => 'with ungraded submissions',
                   8702:              'incorrect' => 'with incorrect submissions',
                   8703:              'all'       => 'with any status'),
                   8704:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      8705:    my $result='<div class="LC_columnSection">
1.537     harmsja  8706:   
1.533     bisitz   8707:     <fieldset>
                   8708:       <legend>
                   8709:        '.&mt('Sections').'
                   8710:       </legend>
1.601     www      8711:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8712:     </fieldset>
1.537     harmsja  8713:   
1.533     bisitz   8714:     <fieldset>
                   8715:       <legend>
                   8716:         '.&mt('Groups').'
                   8717:       </legend>
                   8718:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8719:     </fieldset>
1.537     harmsja  8720:   
1.533     bisitz   8721:     <fieldset>
                   8722:       <legend>
                   8723:         '.&mt('Access Status').'
                   8724:       </legend>
1.601     www      8725:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8726:     </fieldset>';
                   8727:     if ($full) {
                   8728:        $result.='
1.533     bisitz   8729:     <fieldset>
                   8730:       <legend>
                   8731:         '.&mt('Submission Status').'
1.601     www      8732:       </legend>'.
1.635     raeburn  8733:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      8734:    '</fieldset>';
                   8735:     }
                   8736:     $result.='</div><br />';
1.44      ng       8737:     return $result;
1.2       albertel 8738: }
                   8739: 
1.285     albertel 8740: sub reset_perm {
                   8741:     undef(%perm);
                   8742: }
                   8743: 
                   8744: sub init_perm {
                   8745:     &reset_perm();
1.300     albertel 8746:     foreach my $test_perm ('vgr','mgr','opa') {
                   8747: 
                   8748: 	my $scope = $env{'request.course.id'};
                   8749: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8750: 
                   8751: 	    $scope .= '/'.$env{'request.course.sec'};
                   8752: 	    if ( $perm{$test_perm}=
                   8753: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8754: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8755: 	    } else {
                   8756: 		delete($perm{$test_perm});
                   8757: 	    }
1.285     albertel 8758: 	}
                   8759:     }
                   8760: }
                   8761: 
1.400     www      8762: sub gather_clicker_ids {
1.408     albertel 8763:     my %clicker_ids;
1.400     www      8764: 
                   8765:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8766: 
                   8767:     # Set up a couple variables.
1.407     albertel 8768:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8769:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8770:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8771: 
1.407     albertel 8772:     foreach my $student (keys(%$classlist)) {
1.438     www      8773:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8774:         my $username = $classlist->{$student}->[$username_idx];
                   8775:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8776:         my $clickers =
1.408     albertel 8777: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8778:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8779:             $id=~s/^[\#0]+//;
1.421     www      8780:             $id=~s/[\-\:]//g;
1.407     albertel 8781:             if (exists($clicker_ids{$id})) {
1.408     albertel 8782: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8783:             } else {
1.408     albertel 8784: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8785:             }
                   8786:         }
                   8787:     }
1.407     albertel 8788:     return %clicker_ids;
1.400     www      8789: }
                   8790: 
1.402     www      8791: sub gather_adv_clicker_ids {
1.408     albertel 8792:     my %clicker_ids;
1.402     www      8793:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8794:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8795:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8796:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8797:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8798:             my ($puname,$pudom)=split(/\:/,$person);
                   8799:             my $clickers =
1.408     albertel 8800: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8801:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8802: 		$id=~s/^[\#0]+//;
1.421     www      8803:                 $id=~s/[\-\:]//g;
1.408     albertel 8804: 		if (exists($clicker_ids{$id})) {
                   8805: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8806: 		} else {
                   8807: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8808: 		}
1.405     www      8809:             }
1.402     www      8810:         }
                   8811:     }
1.407     albertel 8812:     return %clicker_ids;
1.402     www      8813: }
                   8814: 
1.413     www      8815: sub clicker_grading_parameters {
                   8816:     return ('gradingmechanism' => 'scalar',
                   8817:             'upfiletype' => 'scalar',
                   8818:             'specificid' => 'scalar',
                   8819:             'pcorrect' => 'scalar',
                   8820:             'pincorrect' => 'scalar');
                   8821: }
                   8822: 
1.400     www      8823: sub process_clicker {
1.608     www      8824:     my ($r,$symb)=@_;
1.400     www      8825:     if (!$symb) {return '';}
                   8826:     my $result=&checkforfile_js();
1.632     www      8827:     $result.=&Apache::loncommon::start_data_table().
                   8828:              &Apache::loncommon::start_data_table_header_row().
                   8829:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   8830:              &Apache::loncommon::end_data_table_header_row().
                   8831:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8832: # Attempt to restore parameters from last session, set defaults if not present
                   8833:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8834:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8835:                                                  \%Saveable_Parameters);
                   8836:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8837:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8838:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8839:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8840: 
                   8841:     my %checked;
1.521     www      8842:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8843:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8844:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8845:        }
                   8846:     }
                   8847: 
1.632     www      8848:     my $upload=&mt("Evaluate File");
1.400     www      8849:     my $type=&mt("Type");
1.402     www      8850:     my $attendance=&mt("Award points just for participation");
                   8851:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8852:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8853:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8854:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8855:     my $pcorrect=&mt("Percentage points for correct solution");
                   8856:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8857:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  8858: 						   {'iclicker' => 'i>clicker',
                   8859:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8860:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8861:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8862: function sanitycheck() {
                   8863: // Accept only integer percentages
                   8864:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8865:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8866: // Find out grading choice
                   8867:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8868:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8869:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8870:       }
                   8871:    }
                   8872: // By default, new choice equals user selection
                   8873:    newgradingchoice=gradingchoice;
                   8874: // Not good to give more points for false answers than correct ones
                   8875:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8876:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8877:    }
                   8878: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8879:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8880:       document.forms.gradesupload.pcorrect.value=100;
                   8881:       document.forms.gradesupload.pincorrect.value=100;
                   8882:    }
                   8883: // If the values are different, cannot be attendance only
                   8884:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8885:        (gradingchoice=='attendance')) {
                   8886:        newgradingchoice='personnel';
                   8887:    }
                   8888: // Change grading choice to new one
                   8889:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8890:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8891:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8892:       } else {
                   8893:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8894:       }
                   8895:    }
                   8896: // Remember the old state
                   8897:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8898: }
1.597     wenzelju 8899: ENDUPFORM
                   8900:     $result.= <<ENDUPFORM;
1.400     www      8901: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8902: <input type="hidden" name="symb" value="$symb" />
                   8903: <input type="hidden" name="command" value="processclickerfile" />
                   8904: <input type="file" name="upfile" size="50" />
                   8905: <br /><label>$type: $selectform</label>
1.632     www      8906: ENDUPFORM
                   8907:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8908:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   8909:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8910: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8911: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8912: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8913: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8914: <br />&nbsp;&nbsp;&nbsp;
                   8915: <input type="text" name="givenanswer" size="50" />
1.413     www      8916: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      8917: ENDGRADINGFORM
                   8918:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   8919:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   8920:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8921: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8922: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8923: </form>'
1.632     www      8924: ENDPERCFORM
                   8925:     $result.='</td>'.
                   8926:              &Apache::loncommon::end_data_table_row().
                   8927:              &Apache::loncommon::end_data_table();
1.400     www      8928:     return $result;
                   8929: }
                   8930: 
                   8931: sub process_clicker_file {
1.608     www      8932:     my ($r,$symb)=@_;
1.400     www      8933:     if (!$symb) {return '';}
1.413     www      8934: 
                   8935:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8936:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8937:                                               \%Saveable_Parameters);
1.598     www      8938:     my $result='';
1.404     www      8939:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8940: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8941: 	return $result;
1.404     www      8942:     }
1.522     www      8943:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8944:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8945:         return $result;
1.521     www      8946:     }
1.522     www      8947:     my $foundgiven=0;
1.521     www      8948:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8949:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8950:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      8951:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      8952:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8953:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8954:         $foundgiven=$#answers+1;
1.521     www      8955:     }
1.407     albertel 8956:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8957:     my %correct_ids;
1.404     www      8958:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8959: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8960:     }
                   8961:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8962: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8963: 	   $correct_id=~tr/a-z/A-Z/;
                   8964: 	   $correct_id=~s/\s//gs;
                   8965: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8966:            $correct_id=~s/[\-\:]//g;
1.414     www      8967:            if ($correct_id) {
                   8968: 	      $correct_ids{$correct_id}='specified';
                   8969:            }
                   8970:         }
1.400     www      8971:     }
1.404     www      8972:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8973: 	$result.=&mt('Score based on attendance only');
1.521     www      8974:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8975:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8976:     } else {
1.408     albertel 8977: 	my $number=0;
1.411     www      8978: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8979: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8980: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8981: 	    if ($correct_ids{$id} eq 'specified') {
                   8982: 		$result.=&mt('specified');
                   8983: 	    } else {
                   8984: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8985: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8986: 	    }
                   8987: 	    $number++;
                   8988: 	}
1.411     www      8989:         $result.="</p>\n";
1.408     albertel 8990: 	if ($number==0) {
                   8991: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8992: 	    return $result;
1.408     albertel 8993: 	}
1.404     www      8994:     }
1.405     www      8995:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8996:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8997: 		     '<span class="LC_error">',
                   8998: 		     '</span>',
                   8999: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      9000:         return $result;
1.405     www      9001:     }
1.410     www      9002: 
                   9003: # Were able to get all the info needed, now analyze the file
                   9004: 
1.411     www      9005:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9006:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9007:     $result.=&Apache::loncommon::start_data_table().
                   9008:              &Apache::loncommon::start_data_table_header_row().
                   9009:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9010:              &Apache::loncommon::end_data_table_header_row().
                   9011:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9012: <td>
1.410     www      9013: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9014: <input type="hidden" name="symb" value="$symb" />
                   9015: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9016: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9017: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9018: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9019: ENDHEADER
1.522     www      9020:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9021:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9022:     } 
1.408     albertel 9023:     my %responses;
                   9024:     my @questiontitles;
1.405     www      9025:     my $errormsg='';
                   9026:     my $number=0;
                   9027:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9028: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9029:     }
1.419     www      9030:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9031:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9032:     }
1.411     www      9033:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9034:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9035:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9036:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9037:              '<br />';
1.522     www      9038:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9039:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9040:        return $result;
1.522     www      9041:     } 
1.414     www      9042: # Remember Question Titles
                   9043: # FIXME: Possibly need delimiter other than ":"
                   9044:     for (my $i=0;$i<$number;$i++) {
                   9045:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9046:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9047:     }
1.411     www      9048:     my $correct_count=0;
                   9049:     my $student_count=0;
                   9050:     my $unknown_count=0;
1.414     www      9051: # Match answers with usernames
                   9052: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9053:     foreach my $id (keys(%responses)) {
1.410     www      9054:        if ($correct_ids{$id}) {
1.414     www      9055:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9056:           $correct_count++;
1.410     www      9057:        } elsif ($clicker_ids{$id}) {
1.437     www      9058:           if ($clicker_ids{$id}=~/\,/) {
                   9059: # More than one user with the same clicker!
1.632     www      9060:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9061:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9062:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9063:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9064:                            "<select name='multi".$id."'>";
                   9065:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9066:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9067:              }
                   9068:              $result.='</select>';
                   9069:              $unknown_count++;
                   9070:           } else {
                   9071: # Good: found one and only one user with the right clicker
                   9072:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9073:              $student_count++;
                   9074:           }
1.410     www      9075:        } else {
1.632     www      9076:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9077:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9078:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9079:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9080:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9081:                    "\n".&mt("Domain").": ".
                   9082:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9083:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9084:           $unknown_count++;
1.410     www      9085:        }
1.405     www      9086:     }
1.412     www      9087:     $result.='<hr />'.
                   9088:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9089:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9090:        if ($correct_count==0) {
                   9091:           $errormsg.="Found no correct answers answers for grading!";
                   9092:        } elsif ($correct_count>1) {
1.414     www      9093:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9094:        }
                   9095:     }
1.428     www      9096:     if ($number<1) {
                   9097:        $errormsg.="Found no questions.";
                   9098:     }
1.412     www      9099:     if ($errormsg) {
                   9100:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9101:     } else {
                   9102:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9103:     }
1.632     www      9104:     $result.='</form></td>'.
                   9105:              &Apache::loncommon::end_data_table_row().
                   9106:              &Apache::loncommon::end_data_table();
1.614     www      9107:     return $result;
1.400     www      9108: }
                   9109: 
1.405     www      9110: sub iclicker_eval {
1.406     www      9111:     my ($questiontitles,$responses)=@_;
1.405     www      9112:     my $number=0;
                   9113:     my $errormsg='';
                   9114:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9115:         my %components=&Apache::loncommon::record_sep($line);
                   9116:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9117: 	if ($entries[0] eq 'Question') {
                   9118: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9119: 		$$questiontitles[$number]=$entries[$i];
                   9120: 		$number++;
                   9121: 	    }
                   9122: 	}
                   9123: 	if ($entries[0]=~/^\#/) {
                   9124: 	    my $id=$entries[0];
                   9125: 	    my @idresponses;
                   9126: 	    $id=~s/^[\#0]+//;
                   9127: 	    for (my $i=0;$i<$number;$i++) {
                   9128: 		my $idx=3+$i*6;
1.644     www      9129:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9130: 		push(@idresponses,$entries[$idx]);
                   9131: 	    }
                   9132: 	    $$responses{$id}=join(',',@idresponses);
                   9133: 	}
1.405     www      9134:     }
                   9135:     return ($errormsg,$number);
                   9136: }
                   9137: 
1.419     www      9138: sub interwrite_eval {
                   9139:     my ($questiontitles,$responses)=@_;
                   9140:     my $number=0;
                   9141:     my $errormsg='';
1.420     www      9142:     my $skipline=1;
                   9143:     my $questionnumber=0;
                   9144:     my %idresponses=();
1.419     www      9145:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9146:         my %components=&Apache::loncommon::record_sep($line);
                   9147:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9148:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9149:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9150:         next if $skipline;
                   9151:         if ($entries[0]!=$questionnumber) {
                   9152:            $questionnumber=$entries[0];
                   9153:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9154:            $number++;
1.419     www      9155:         }
1.420     www      9156:         my $id=$entries[4];
                   9157:         $id=~s/^[\#0]+//;
1.421     www      9158:         $id=~s/^v\d*\://i;
                   9159:         $id=~s/[\-\:]//g;
1.420     www      9160:         $idresponses{$id}[$number]=$entries[6];
                   9161:     }
1.524     raeburn  9162:     foreach my $id (keys(%idresponses)) {
1.420     www      9163:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9164:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9165:     }
                   9166:     return ($errormsg,$number);
                   9167: }
                   9168: 
1.414     www      9169: sub assign_clicker_grades {
1.608     www      9170:     my ($r,$symb)=@_;
1.414     www      9171:     if (!$symb) {return '';}
1.416     www      9172: # See which part we are saving to
1.582     raeburn  9173:     my $res_error;
                   9174:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9175:     if ($res_error) {
                   9176:         return &navmap_errormsg();
                   9177:     }
1.416     www      9178: # FIXME: This should probably look for the first handgradeable part
                   9179:     my $part=$$partlist[0];
                   9180: # Start screen output
1.632     www      9181:     my $result=&Apache::loncommon::start_data_table().
                   9182:              &Apache::loncommon::start_data_table_header_row().
                   9183:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9184:              &Apache::loncommon::end_data_table_header_row().
                   9185:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9186: # Get correct result
                   9187: # FIXME: Possibly need delimiter other than ":"
                   9188:     my @correct=();
1.415     www      9189:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9190:     my $number=$env{'form.number'};
                   9191:     if ($gradingmechanism ne 'attendance') {
1.414     www      9192:        foreach my $key (keys(%env)) {
                   9193:           if ($key=~/^form\.correct\:/) {
                   9194:              my @input=split(/\,/,$env{$key});
                   9195:              for (my $i=0;$i<=$#input;$i++) {
                   9196:                  if (($correct[$i]) && ($input[$i]) &&
                   9197:                      ($correct[$i] ne $input[$i])) {
                   9198:                     $result.='<br /><span class="LC_warning">'.
                   9199:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9200:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      9201:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9202:                     $correct[$i]=$input[$i];
                   9203:                  }
                   9204:              }
                   9205:           }
                   9206:        }
1.415     www      9207:        for (my $i=0;$i<$number;$i++) {
1.644     www      9208:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9209:              $result.='<br /><span class="LC_error">'.
                   9210:                       &mt('No correct result given for question "[_1]"!',
                   9211:                           $env{'form.question:'.$i}).'</span>';
                   9212:           }
                   9213:        }
1.644     www      9214:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9215:     }
                   9216: # Start grading
1.415     www      9217:     my $pcorrect=$env{'form.pcorrect'};
                   9218:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9219:     my $storecount=0;
1.632     www      9220:     my %users=();
1.415     www      9221:     foreach my $key (keys(%env)) {
1.420     www      9222:        my $user='';
1.415     www      9223:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9224:           $user=$1;
                   9225:        }
                   9226:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9227:           my $id=$1;
                   9228:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9229:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9230:           } elsif ($env{'form.multi'.$id}) {
                   9231:              $user=$env{'form.multi'.$id};
1.420     www      9232:           }
                   9233:        }
1.632     www      9234:        if ($user) {
                   9235:           if ($users{$user}) {
                   9236:              $result.='<br /><span class="LC_warning">'.
                   9237:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9238:                       '</span><br />';
                   9239:           }
                   9240:           $users{$user}=1; 
1.415     www      9241:           my @answer=split(/\,/,$env{$key});
                   9242:           my $sum=0;
1.522     www      9243:           my $realnumber=$number;
1.415     www      9244:           for (my $i=0;$i<$number;$i++) {
1.576     www      9245:              if  ($correct[$i] eq '-') {
                   9246:                 $realnumber--;
1.644     www      9247:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      9248:                 if ($gradingmechanism eq 'attendance') {
                   9249:                    $sum+=$pcorrect;
1.576     www      9250:                 } elsif ($correct[$i] eq '*') {
1.522     www      9251:                    $sum+=$pcorrect;
1.415     www      9252:                 } else {
1.644     www      9253: # We actually grade if correct or not
                   9254:                    my $increment=$pincorrect;
                   9255: # Special case: numerical answer "0"
                   9256:                    if ($correct[$i] eq '0') {
                   9257:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9258:                          $increment=$pcorrect;
                   9259:                       }
                   9260: # General numerical answer, both evaluate to something non-zero
                   9261:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9262:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9263:                          $increment=$pcorrect;
                   9264:                       }
                   9265: # Must be just alphanumeric
                   9266:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9267:                       $increment=$pcorrect;
1.415     www      9268:                    }
1.644     www      9269:                    $sum+=$increment;
1.415     www      9270:                 }
                   9271:              }
                   9272:           }
1.522     www      9273:           my $ave=$sum/(100*$realnumber);
1.416     www      9274: # Store
                   9275:           my ($username,$domain)=split(/\:/,$user);
                   9276:           my %grades=();
                   9277:           $grades{"resource.$part.solved"}='correct_by_override';
                   9278:           $grades{"resource.$part.awarded"}=$ave;
                   9279:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9280:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9281:                                                  $env{'request.course.id'},
                   9282:                                                  $domain,$username);
                   9283:           if ($returncode ne 'ok') {
                   9284:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9285:           } else {
                   9286:              $storecount++;
                   9287:           }
1.415     www      9288:        }
                   9289:     }
                   9290: # We are done
1.549     hauer    9291:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      9292:              '</td>'.
                   9293:              &Apache::loncommon::end_data_table_row().
                   9294:              &Apache::loncommon::end_data_table();
1.614     www      9295:     return $result;
1.414     www      9296: }
                   9297: 
1.582     raeburn  9298: sub navmap_errormsg {
                   9299:     return '<div class="LC_error">'.
                   9300:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9301:            &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  9302:            '</div>';
                   9303: }
1.607     droeschl 9304: 
1.609     www      9305: sub startpage {
1.613     www      9306:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9307:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9308:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9309:                                           {'bread_crumbs' => $crumbs}));
1.645     www      9310:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
1.613     www      9311:     unless ($nodisplayflag) {
                   9312:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9313:     }
1.607     droeschl 9314: }
1.582     raeburn  9315: 
1.622     www      9316: sub select_problem {
                   9317:     my ($r)=@_;
1.632     www      9318:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9319:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9320:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9321:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9322: }
                   9323: 
1.1       albertel 9324: sub handler {
1.41      ng       9325:     my $request=$_[0];
1.434     albertel 9326:     &reset_caches();
1.646     raeburn  9327:     if ($request->header_only) {
                   9328:         &Apache::loncommon::content_type($request,'text/html');
                   9329:         $request->send_http_header;
                   9330:         return OK;
                   9331:     }
                   9332:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   9333: 
                   9334:     &init_perm();
                   9335:     if (!$env{'request.course.id'}) {
                   9336:         # Not in a course.
                   9337:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9338:         return HTTP_NOT_ACCEPTABLE;
                   9339:     } elsif (!%perm) {
                   9340:         $request->internal_redirect('/adm/quickgrades');
1.41      ng       9341:     }
1.646     raeburn  9342:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       9343:     $request->send_http_header;
1.646     raeburn  9344: 
1.608     www      9345: 
                   9346: # see what command we need to execute
                   9347: 
1.160     albertel 9348:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9349:     my $command=$commands[0];
1.447     foxr     9350: 
1.160     albertel 9351:     if ($#commands > 0) {
                   9352: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9353:     }
1.608     www      9354: 
                   9355: # see what the symb is
                   9356: 
                   9357:     my $symb=$env{'form.symb'};
                   9358:     unless ($symb) {
                   9359:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9360:        $symb=&Apache::lonnet::symbread($url);
                   9361:     }
1.646     raeburn  9362:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      9363: 
1.513     foxr     9364:     $ssi_error = 0;
1.637     www      9365:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      9366: #
1.637     www      9367: # Not called from a resource, but inside a course
1.601     www      9368: #    
1.622     www      9369:         &startpage($request,undef,[],1,1);
                   9370:         &select_problem($request);
1.41      ng       9371:     } else {
1.104     albertel 9372: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9373:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9374: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9375: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9376:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9377:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9378: 	    &pickStudentPage($request,$symb);
1.103     albertel 9379: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9380:             &startpage($request,$symb,
                   9381:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9382:                                        {href=>'',text=>'Select student'},
                   9383:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9384: 	    &displayPage($request,$symb);
1.104     albertel 9385: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9386:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9387:                                        {href=>'',text=>'Select student'},
                   9388:                                        {href=>'',text=>'Grade student'},
                   9389:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9390: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9391: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9392:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9393:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9394: 	    &processGroup($request,$symb);
1.104     albertel 9395: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9396:             &startpage($request,$symb);
                   9397: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9398: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9399:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9400: 	    $request->print(&submit_options($request,$symb));
1.598     www      9401:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9402:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9403:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9404:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9405:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9406:             $request->print(&submit_options_table($request,$symb));
1.598     www      9407:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9408:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9409:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9410: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9411:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9412: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9413: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9414:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9415:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9416: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9417: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9418:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9419:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9420:                                                                              text=>"Modify grades"},
                   9421:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9422: 	    $request->print(&editgrades($request,$symb));
1.602     www      9423:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9424:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9425:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9426: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9427:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9428:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9429: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9430:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9431:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9432:             $request->print(&process_clicker($request,$symb));
1.400     www      9433:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9434:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9435:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9436:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9437:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9438:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9439:                                        {href=>'', text=>'Process clicker file'},
                   9440:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9441:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9442: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9443:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9444: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9445: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9446:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9447: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9448: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9449:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9450: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9451: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9452: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9453:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9454: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9455: 	    } else {
1.257     albertel 9456: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9457: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9458: 		} else {
1.257     albertel 9459: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9460: 		}
1.627     www      9461:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9462: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9463: 	    }
1.246     albertel 9464: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9465:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9466: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9467: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9468:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9469: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9470:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9471:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9472:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9473: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9474:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9475: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9476: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9477:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9478: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9479:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9480:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9481: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9482:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9483:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9484:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9485:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9486: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9487:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9488:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9489:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 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_download_scantron_data($request,$symb));
1.523     raeburn  9493:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9494:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9495:             $request->print(&checkscantron_results($request,$symb));
                   9496:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9497:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9498:             $request->print(&submit_options_download($request,$symb));
                   9499:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9500:             &startpage($request,$symb,
                   9501:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9502:     {href=>'', text=>'Download submissions'}]);
                   9503:             &submit_download_link($request,$symb);
1.106     albertel 9504: 	} elsif ($command) {
1.620     www      9505:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9506: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9507: 	}
1.2       albertel 9508:     }
1.513     foxr     9509:     if ($ssi_error) {
                   9510: 	&ssi_print_error($request);
                   9511:     }
1.639     www      9512:     &Apache::lonquickgrades::endGradeScreen($request);
1.353     albertel 9513:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9514:     &reset_caches();
1.646     raeburn  9515:     return OK;
1.44      ng       9516: }
                   9517: 
1.1       albertel 9518: 1;
                   9519: 
1.13      albertel 9520: __END__;
1.531     jms      9521: 
                   9522: 
                   9523: =head1 NAME
                   9524: 
                   9525: Apache::grades
                   9526: 
                   9527: =head1 SYNOPSIS
                   9528: 
                   9529: Handles the viewing of grades.
                   9530: 
                   9531: This is part of the LearningOnline Network with CAPA project
                   9532: described at http://www.lon-capa.org.
                   9533: 
                   9534: =head1 OVERVIEW
                   9535: 
                   9536: Do an ssi with retries:
                   9537: While I'd love to factor out this with the vesrion in lonprintout,
                   9538: 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
                   9539: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9540: 
                   9541: At least the logic that drives this has been pulled out into loncommon.
                   9542: 
                   9543: 
                   9544: 
                   9545: ssi_with_retries - Does the server side include of a resource.
                   9546:                      if the ssi call returns an error we'll retry it up to
                   9547:                      the number of times requested by the caller.
                   9548:                      If we still have a proble, no text is appended to the
                   9549:                      output and we set some global variables.
                   9550:                      to indicate to the caller an SSI error occurred.  
                   9551:                      All of this is supposed to deal with the issues described
                   9552:                      in LonCAPA BZ 5631 see:
                   9553:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9554:                      by informing the user that this happened.
                   9555: 
                   9556: Parameters:
                   9557:   resource   - The resource to include.  This is passed directly, without
                   9558:                interpretation to lonnet::ssi.
                   9559:   form       - The form hash parameters that guide the interpretation of the resource
                   9560:                
                   9561:   retries    - Number of retries allowed before giving up completely.
                   9562: Returns:
                   9563:   On success, returns the rendered resource identified by the resource parameter.
                   9564: Side Effects:
                   9565:   The following global variables can be set:
                   9566:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9567:                               It is up to the caller to initialize this to false
                   9568:                               if desired.
                   9569:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9570:                               of the resource that could not be rendered by the ssi
                   9571:                               call.
                   9572:    ssi_error_message   - The error string fetched from the ssi response
                   9573:                               in the event of an error.
                   9574: 
                   9575: 
                   9576: =head1 HANDLER SUBROUTINE
                   9577: 
                   9578: ssi_with_retries()
                   9579: 
                   9580: =head1 SUBROUTINES
                   9581: 
                   9582: =over
                   9583: 
                   9584: =item scantron_get_correction() : 
                   9585: 
                   9586:    Builds the interface screen to interact with the operator to fix a
                   9587:    specific error condition in a specific scanline
                   9588: 
                   9589:  Arguments:
                   9590:     $r           - Apache request object
                   9591:     $i           - number of the current scanline
                   9592:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9593:     $scan_config - hash ref as returned from &get_scantron_config()
                   9594:     $line        - full contents of the current scanline
                   9595:     $error       - error condition, valid values are
                   9596:                    'incorrectCODE', 'duplicateCODE',
                   9597:                    'doublebubble', 'missingbubble',
                   9598:                    'duplicateID', 'incorrectID'
                   9599:     $arg         - extra information needed
                   9600:        For errors:
                   9601:          - duplicateID   - paper number that this studentID was seen before on
                   9602:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9603:                            seen on before
                   9604:          - incorrectCODE - current incorrect CODE 
                   9605:          - doublebubble  - array ref of the bubble lines that have double
                   9606:                            bubble errors
                   9607:          - missingbubble - array ref of the bubble lines that have missing
                   9608:                            bubble errors
                   9609: 
                   9610: =item  scantron_get_maxbubble() : 
                   9611: 
1.582     raeburn  9612:    Arguments:
                   9613:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9614:                       failure to retrieve a navmap object.
                   9615:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9616:        calling routine should trap the error condition and display the warning
                   9617:        found in &navmap_errormsg().
                   9618: 
1.649     raeburn  9619:        $scantron_config - Reference to bubblesheet format configuration hash.
                   9620: 
1.531     jms      9621:    Returns the maximum number of bubble lines that are expected to
                   9622:    occur. Does this by walking the selected sequence rendering the
                   9623:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9624:    for what the current value of the problem counter is.
                   9625: 
                   9626:    Caches the results to $env{'form.scantron_maxbubble'},
                   9627:    $env{'form.scantron.bubble_lines.n'}, 
                   9628:    $env{'form.scantron.first_bubble_line.n'} and
                   9629:    $env{"form.scantron.sub_bubblelines.n"}
                   9630:    which are the total number of bubble, lines, the number of bubble
                   9631:    lines for response n and number of the first bubble line for response n,
                   9632:    and a comma separated list of numbers of bubble lines for sub-questions
                   9633:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9634: 
                   9635: 
                   9636: =item  scantron_validate_missingbubbles() : 
                   9637: 
                   9638:    Validates all scanlines in the selected file to not have any
                   9639:     answers that don't have bubbles that have not been verified
                   9640:     to be bubble free.
                   9641: 
                   9642: =item  scantron_process_students() : 
                   9643: 
1.659   ! raeburn  9644:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      9645: 
                   9646:    The parsed scanline hash is added to %env 
                   9647: 
                   9648:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9649:    foreach resource , with the form data of
                   9650: 
                   9651: 	'submitted'     =>'scantron' 
                   9652: 	'grade_target'  =>'grade',
                   9653: 	'grade_username'=> username of student
                   9654: 	'grade_domain'  => domain of student
                   9655: 	'grade_courseid'=> of course
                   9656: 	'grade_symb'    => symb of resource to grade
                   9657: 
                   9658:     This triggers a grading pass. The problem grading code takes care
                   9659:     of converting the bubbled letter information (now in %env) into a
                   9660:     valid submission.
                   9661: 
                   9662: =item  scantron_upload_scantron_data() :
                   9663: 
1.659   ! raeburn  9664:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      9665: 
                   9666: =item  scantron_upload_scantron_data_save() : 
                   9667: 
                   9668:    Adds a provided bubble information data file to the course if user
                   9669:    has the correct privileges to do so. 
                   9670: 
                   9671: =item  valid_file() :
                   9672: 
                   9673:    Validates that the requested bubble data file exists in the course.
                   9674: 
                   9675: =item  scantron_download_scantron_data() : 
                   9676: 
                   9677:    Shows a list of the three internal files (original, corrected,
1.659   ! raeburn  9678:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      9679:    course.
                   9680: 
                   9681: =item  scantron_validate_ID() : 
                   9682: 
                   9683:    Validates all scanlines in the selected file to not have any
1.556     weissno  9684:    invalid or underspecified student/employee IDs
1.531     jms      9685: 
1.582     raeburn  9686: =item navmap_errormsg() :
                   9687: 
                   9688:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9689:    Should be called whenever the request to instantiate a navmap object fails.  
                   9690: 
1.531     jms      9691: =back
                   9692: 
                   9693: =cut

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